hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
ca5c6ac469f59d2ed0ae0e0e60e6752189d7aea2
6,473
cc
C++
INET_EC/networklayer/diffserv/DSCP_m.cc
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
null
null
null
INET_EC/networklayer/diffserv/DSCP_m.cc
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
null
null
null
INET_EC/networklayer/diffserv/DSCP_m.cc
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
1
2018-10-09T05:00:05.000Z
2018-10-09T05:00:05.000Z
// // Generated file, do not edit! Created by nedtool 5.1 from inet/networklayer/diffserv/DSCP.msg. // // Disable warnings about unused variables, empty switch stmts, etc: #ifdef _MSC_VER # pragma warning(disable:4101) # pragma warning(disable:4065) #endif #if defined(__clang__) # pragma clang diagnostic ignored "-Wshadow" # pragma clang diagnostic ignored "-Wconversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wunreachable-code-break" # pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) # pragma GCC diagnostic ignored "-Wshadow" # pragma GCC diagnostic ignored "-Wconversion" # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wold-style-cast" # pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" # pragma GCC diagnostic ignored "-Wfloat-conversion" #endif #include <iostream> #include <sstream> #include "DSCP_m.h" namespace omnetpp { // Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons. // They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument // Packing/unpacking an std::vector template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v) { int n = v.size(); doParsimPacking(buffer, n); for (int i = 0; i < n; i++) doParsimPacking(buffer, v[i]); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v) { int n; doParsimUnpacking(buffer, n); v.resize(n); for (int i = 0; i < n; i++) doParsimUnpacking(buffer, v[i]); } // Packing/unpacking an std::list template<typename T, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l) { doParsimPacking(buffer, (int)l.size()); for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it) doParsimPacking(buffer, (T&)*it); } template<typename T, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { l.push_back(T()); doParsimUnpacking(buffer, l.back()); } } // Packing/unpacking an std::set template<typename T, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s) { doParsimPacking(buffer, (int)s.size()); for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it) doParsimPacking(buffer, *it); } template<typename T, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { T x; doParsimUnpacking(buffer, x); s.insert(x); } } // Packing/unpacking an std::map template<typename K, typename V, typename Tr, typename A> void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m) { doParsimPacking(buffer, (int)m.size()); for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) { doParsimPacking(buffer, it->first); doParsimPacking(buffer, it->second); } } template<typename K, typename V, typename Tr, typename A> void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m) { int n; doParsimUnpacking(buffer, n); for (int i=0; i<n; i++) { K k; V v; doParsimUnpacking(buffer, k); doParsimUnpacking(buffer, v); m[k] = v; } } // Default pack/unpack function for arrays template<typename T> void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n) { for (int i = 0; i < n; i++) doParsimPacking(b, t[i]); } template<typename T> void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n) { for (int i = 0; i < n; i++) doParsimUnpacking(b, t[i]); } // Default rule to prevent compiler from choosing base class' doParsimPacking() function template<typename T> void doParsimPacking(omnetpp::cCommBuffer *, const T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t))); } template<typename T> void doParsimUnpacking(omnetpp::cCommBuffer *, T& t) { throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t))); } } // namespace omnetpp namespace inet { // forward template<typename T, typename A> std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec); // Template rule which fires if a struct or class doesn't have operator<< template<typename T> inline std::ostream& operator<<(std::ostream& out,const T&) {return out;} // operator<< for std::vector<T> template<typename T, typename A> inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec) { out.put('{'); for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it) { if (it != vec.begin()) { out.put(','); out.put(' '); } out << *it; } out.put('}'); char buf[32]; sprintf(buf, " (size=%u)", (unsigned int)vec.size()); out.write(buf, strlen(buf)); return out; } EXECUTE_ON_STARTUP( omnetpp::cEnum *e = omnetpp::cEnum::find("inet::DSCP"); if (!e) omnetpp::enums.getInstance()->add(e = new omnetpp::cEnum("inet::DSCP")); e->insert(DSCP_BE, "DSCP_BE"); e->insert(DSCP_AF11, "DSCP_AF11"); e->insert(DSCP_AF12, "DSCP_AF12"); e->insert(DSCP_AF13, "DSCP_AF13"); e->insert(DSCP_AF21, "DSCP_AF21"); e->insert(DSCP_AF22, "DSCP_AF22"); e->insert(DSCP_AF23, "DSCP_AF23"); e->insert(DSCP_AF31, "DSCP_AF31"); e->insert(DSCP_AF32, "DSCP_AF32"); e->insert(DSCP_AF33, "DSCP_AF33"); e->insert(DSCP_AF41, "DSCP_AF41"); e->insert(DSCP_AF42, "DSCP_AF42"); e->insert(DSCP_AF43, "DSCP_AF43"); e->insert(DSCP_EF, "DSCP_EF"); e->insert(DSCP_CS1, "DSCP_CS1"); e->insert(DSCP_CS2, "DSCP_CS2"); e->insert(DSCP_CS3, "DSCP_CS3"); e->insert(DSCP_CS4, "DSCP_CS4"); e->insert(DSCP_CS5, "DSCP_CS5"); e->insert(DSCP_CS6, "DSCP_CS6"); e->insert(DSCP_CS7, "DSCP_CS7"); e->insert(DSCP_MAX, "DSCP_MAX"); ) } // namespace inet
30.82381
128
0.663989
[ "vector" ]
ca5e3703d8308db872e9420390b786aab674b41a
7,315
cpp
C++
src/test/json/binding_factory.cpp
faizol/json
b4d9948bcfa51450628cab335a2088e24ba00fe2
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
src/test/json/binding_factory.cpp
faizol/json
b4d9948bcfa51450628cab335a2088e24ba00fe2
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
src/test/json/binding_factory.cpp
faizol/json
b4d9948bcfa51450628cab335a2088e24ba00fe2
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (c) 2018-2022 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/json/ #include "test.hpp" #include <tao/json.hpp> #include <tao/json/contrib/traits.hpp> namespace tao::json { class base_1 { public: virtual ~base_1() = default; base_1( const base_1& ) = delete; base_1( base_1&& ) = delete; void operator=( const base_1& ) = delete; void operator=( base_1&& ) = delete; protected: base_1() = default; }; class derived_1 : public base_1 { public: std::string s; }; class derived_2 : public base_1 { public: int i = 105; int j = 106; }; class derived_3 : public base_1 { public: int k = 107; }; template<> struct traits< derived_1 > : binding::object< TAO_JSON_BIND_REQUIRED( "s", &derived_1::s ) > { }; template<> struct traits< derived_2 > : binding::object< TAO_JSON_BIND_REQUIRED( "i", &derived_2::i ), TAO_JSON_BIND_REQUIRED( "j", &derived_2::j ) > { TAO_JSON_DEFAULT_KEY( "two" ); }; template<> struct traits< std::shared_ptr< base_1 > > : binding::factory< TAO_JSON_FACTORY_BIND( "one", derived_1 ), TAO_JSON_FACTORY_BIND1( derived_2 ) > {}; template<> struct traits< std::unique_ptr< base_1 > > : traits< std::shared_ptr< base_1 > > {}; void unit_test_1() { const value v = { { "one", { { "s", "foo" } } } }; const auto a = v.as< std::shared_ptr< base_1 > >(); TEST_ASSERT( a ); const auto b = std::dynamic_pointer_cast< derived_1 >( a ); TEST_ASSERT( b ); TEST_ASSERT( b->s == "foo" ); const value w = a; TEST_ASSERT( w == v ); const value x = produce::to_value( a ); TEST_ASSERT( w == x ); parts_parser p( to_string( v ), __FUNCTION__ ); const auto c = consume< std::shared_ptr< base_1 > >( p ); TEST_ASSERT( c ); const auto d = std::dynamic_pointer_cast< derived_1 >( c ); TEST_ASSERT( d ); TEST_ASSERT( d->s == "foo" ); } void unit_test_2() { const value v = { { "one", { { "s", "foo" } } } }; const auto a = v.as< std::unique_ptr< base_1 > >(); TEST_ASSERT( a ); const auto* b = dynamic_cast< derived_1* >( a.get() ); TEST_ASSERT( b ); TEST_ASSERT( b->s == "foo" ); const value w = a; TEST_ASSERT( w == v ); const value x = produce::to_value( a ); TEST_ASSERT( w == x ); parts_parser p( to_string( v ), __FUNCTION__ ); const auto c = consume< std::unique_ptr< base_1 > >( p ); TEST_ASSERT( c ); auto* const d = dynamic_cast< derived_1* >( c.get() ); TEST_ASSERT( d ); TEST_ASSERT( d->s == "foo" ); } void unit_test_3() { const value v = { { "two", { { "i", 42 }, { "j", 23 } } } }; const auto a = v.as< std::shared_ptr< base_1 > >(); TEST_ASSERT( a ); const auto b = std::dynamic_pointer_cast< derived_2 >( a ); TEST_ASSERT( b ); TEST_ASSERT( b->i == 42 ); TEST_ASSERT( b->j == 23 ); const value w = a; TEST_ASSERT( w == v ); const value x = produce::to_value( a ); TEST_ASSERT( w == x ); parts_parser p( to_string( v ), __FUNCTION__ ); const auto c = consume< std::shared_ptr< base_1 > >( p ); TEST_ASSERT( c ); const auto d = std::dynamic_pointer_cast< derived_2 >( c ); TEST_ASSERT( d ); TEST_ASSERT( d->i == 42 ); TEST_ASSERT( d->j == 23 ); } void unit_test_4() { const value v = { { "two", { { "i", 42 }, { "j", 23 } } } }; const auto a = v.as< std::unique_ptr< base_1 > >(); TEST_ASSERT( a ); const auto* b = dynamic_cast< derived_2* >( a.get() ); TEST_ASSERT( b ); TEST_ASSERT( b && ( b->i == 42 ) ); TEST_ASSERT( b && ( b->j == 23 ) ); const value w = a; TEST_ASSERT( w == v ); const value x = produce::to_value( a ); TEST_ASSERT( w == x ); parts_parser p( to_string( v ), __FUNCTION__ ); const auto c = consume< std::unique_ptr< base_1 > >( p ); TEST_ASSERT( c ); const auto* d = dynamic_cast< derived_2* >( c.get() ); TEST_ASSERT( d ); TEST_ASSERT( d && ( d->i == 42 ) ); TEST_ASSERT( d && ( d->j == 23 ) ); } void unit_test_5() { const value z = empty_object; TEST_THROWS( z.as< std::unique_ptr< base_1 > >() ); const value v = { { "one", { { "s", "foo" } } }, { "two", { { "i", 42 }, { "j", 23 } } } }; TEST_THROWS( v.as< std::unique_ptr< base_1 > >() ); const value w = { { "1", { { "s", "foo" } } } }; TEST_THROWS( w.as< std::unique_ptr< base_1 > >() ); TEST_THROWS( value( std::shared_ptr< base_1 >( new derived_3 ) ) ); events::discard d; TEST_THROWS( events::produce( d, std::shared_ptr< base_1 >( new derived_3 ) ) ); parts_parser p( "{ \"four\" : null }", __FUNCTION__ ); TEST_THROWS( consume< std::shared_ptr< base_1 > >( p ) ); } class base_2 { public: base_2( const base_2& ) = delete; base_2( base_2&& ) = delete; void operator=( const base_2& ) = delete; void operator=( base_2&& ) = delete; protected: base_2() = default; virtual ~base_2() = default; }; struct arg_dummy {}; struct derived_8 : public base_2 { derived_8( const value& /*unused*/, const arg_dummy& /*unused*/ ) {} }; struct derived_9 : public base_2 { derived_9( const value& /*unused*/, const arg_dummy& /*unused*/ ) {} }; template<> struct traits< std::shared_ptr< base_2 > > : binding::factory< TAO_JSON_FACTORY_BIND( "eight", derived_8 ), TAO_JSON_FACTORY_BIND( "nine", derived_9 ) > {}; void unit_test_6() { arg_dummy d; const auto v = from_string( "{ \"nine\" : 1 }" ); const auto a = v.as_with< std::shared_ptr< base_2 > >( d ); TEST_ASSERT( a ); } void unit_test_7() { arg_dummy d; const auto v = from_string( "[ { \"nine\" : 1 }, { \"eight\" : 2 } ]" ); const auto a = v.as_with< std::vector< std::shared_ptr< base_2 > > >( d ); TEST_ASSERT( a.size() == 2 ); TEST_ASSERT( a[ 0 ] && a[ 1 ] ); TEST_ASSERT( std::dynamic_pointer_cast< derived_9 >( a[ 0 ] ) ); TEST_ASSERT( std::dynamic_pointer_cast< derived_8 >( a[ 1 ] ) ); } void unit_test_8() { arg_dummy d; const auto v = from_string( "{ \"foo\" : { \"nine\" : 1 }, \"bar\" : { \"eight\" : 2 } }" ); const auto a = v.as_with< std::map< std::string, std::shared_ptr< base_2 >, std::less<> > >( d ); TEST_ASSERT( a.size() == 2 ); TEST_ASSERT( std::dynamic_pointer_cast< derived_9 >( a.at( "foo" ) ) ); TEST_ASSERT( std::dynamic_pointer_cast< derived_8 >( a.at( "bar" ) ) ); } void unit_test() { unit_test_1(); unit_test_2(); unit_test_3(); unit_test_4(); unit_test_5(); unit_test_6(); unit_test_7(); unit_test_8(); } } // namespace tao::json #include "main.hpp"
27.5
103
0.525906
[ "object", "vector" ]
ca5ea465b0cf24d9ccef108ed0424315945d5df4
25,462
cpp
C++
src/marched.cpp
Hyrtsi/cubnature
c10aebc736f56e15148ca2e89c1ff7ce72b82e2c
[ "MIT" ]
null
null
null
src/marched.cpp
Hyrtsi/cubnature
c10aebc736f56e15148ca2e89c1ff7ce72b82e2c
[ "MIT" ]
null
null
null
src/marched.cpp
Hyrtsi/cubnature
c10aebc736f56e15148ca2e89c1ff7ce72b82e2c
[ "MIT" ]
1
2021-12-26T10:01:08.000Z
2021-12-26T10:01:08.000Z
#include "marched.hpp" #include <iostream> #include <omp.h> #include <functional> #include <vector> using namespace glm; namespace { // From http://paulbourke.net/geometry/polygonise/ static const uint16_t EDGE_TABLE[256] = { 0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0 }; static const int16_t TRI_TABLE[256][16] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} }; struct IsoVert { vec3 pos; float value; }; struct Vertex { vec3 pos; vec3 normal; }; vec3 lerpI(const IsoVert& v1, const IsoVert& v2, const float threshold, std::vector<Vertex>* verts) { return v1.pos + float(threshold - v1.value) * (v2.pos - v1.pos) / float(v2.value - v1.value); } // Pushes triangles in the given cube to verts and faces void parseVolumeCube(IsoVert corners[8], const uint32_t x, const uint32_t y, const float threshold, const uvec3& gridSize, std::vector<Vertex>* verts) { // TODO: This is borked after conversion to sdf? // Get index for cube variation uint8_t cubeI = 0; if (corners[0].value < threshold) cubeI |= 1; if (corners[1].value < threshold) cubeI |= 2; if (corners[2].value < threshold) cubeI |= 4; if (corners[3].value < threshold) cubeI |= 8; if (corners[4].value < threshold) cubeI |= 16; if (corners[5].value < threshold) cubeI |= 32; if (corners[6].value < threshold) cubeI |= 64; if (corners[7].value < threshold) cubeI |= 128; // Cube is entirely in or out of the surface if (cubeI == 0) return; // Lerp edge intersections int edges = EDGE_TABLE[cubeI]; vec3 intersections[12]; if(edges & 1) intersections[0] = lerpI(corners[0], corners[1], threshold, verts); if(edges & 2) intersections[1] = lerpI(corners[1], corners[2], threshold, verts); if(edges & 4) intersections[2] = lerpI(corners[2], corners[3], threshold, verts); if(edges & 8) intersections[3] = lerpI(corners[3], corners[0], threshold, verts); if(edges & 16) intersections[4] = lerpI(corners[4], corners[5], threshold, verts); if(edges & 32) intersections[5] = lerpI(corners[5], corners[6], threshold, verts); if(edges & 64) intersections[6] = lerpI(corners[6], corners[7], threshold, verts); if(edges & 128) intersections[7] = lerpI(corners[7], corners[4], threshold, verts); if(edges & 256) intersections[8] = lerpI(corners[0], corners[4], threshold, verts); if(edges & 512) intersections[9] = lerpI(corners[1], corners[5], threshold, verts); if(edges & 1024) intersections[10] = lerpI(corners[2], corners[6], threshold, verts); if(edges & 2048) intersections[11] = lerpI(corners[3], corners[7], threshold, verts); for (int i = 0; TRI_TABLE[cubeI][i] != -1; i += 3) { const vec3& p0 = intersections[TRI_TABLE[cubeI][i]]; const vec3& p1 = intersections[TRI_TABLE[cubeI][i + 1]]; const vec3& p2 = intersections[TRI_TABLE[cubeI][i + 2]]; vec3 normal = normalize(cross(p2 - p0, p1 - p0)); verts->push_back({p0, normal}); verts->push_back({p1, normal}); verts->push_back({p2, normal}); } } } Marched::Marched(std::function<float(const vec3& pos, const float time)> sdf): _vao(0), _vbo(0), _vertCount(0), _sdf(sdf) { // Generate arrays glGenVertexArrays(1, &_vao); glGenBuffers(1, &_vbo); } Marched::~Marched() { glDeleteVertexArrays(1, &_vao); glDeleteBuffers(1, &_vbo); glDeleteBuffers(1, &_ibo); } Marched::Marched(Marched&& other) : _vao(other._vao), _vbo(other._vbo), _vertCount(other._vertCount) { other._vao = 0; other._vbo = 0; other._vertCount = 0; } void Marched::render() const { glBindVertexArray(_vao); glDrawArrays(GL_TRIANGLES, 0, _vertCount); glBindVertexArray(0); } void Marched::update(const uvec3& res, const vec3& min, const vec3& max, const float time) { // Sample the isosurface const uvec3 gridSize(res + uvec3(1)); std::vector<IsoVert> grid(gridSize.x * gridSize.y * gridSize.z); const vec3 step = (max - min) / vec3(res); #pragma omp parallel for for (int k = 0; k <= res.z; ++k) { const float z = min.z + step.z * k; const size_t layer = k * gridSize.y * gridSize.x; for (int j = 0; j <= res.y; ++j) { const float y = min.y + step.y * j; const size_t row = j * gridSize.x; for (int i = 0; i <= res.x; ++i) { const float x = min.x + step.x * i; const vec3 pos(x, y, z); grid[layer + row + i] = {pos, _sdf(pos, time)}; } } } std::vector<std::vector<Vertex>> ompVerts(omp_get_max_threads()); #pragma omp parallel for for (int k = 0; k < res.z; ++k) { const size_t threadID = omp_get_thread_num(); const size_t layer0 = k * gridSize.y * gridSize.x; const size_t layer1 = (k + 1) * gridSize.y * gridSize.x; // Go through the layer for (uint32_t j = 0; j < res.y - 1; ++j) { const size_t row0 = j * gridSize.x; const size_t row1 = (j + 1) * gridSize.x; for (uint32_t i = 0; i < res.x - 1; ++i) { // Push cube verts to vector IsoVert cVerts[8] = { grid[layer0 + row0 + i], grid[layer0 + row0 + i + 1], grid[layer0 + row1 + i + 1], grid[layer0 + row1 + i], grid[layer1 + row0 + i], grid[layer1 + row0 + i + 1], grid[layer1 + row1 + i + 1], grid[layer1 + row1 + i] }; parseVolumeCube(cVerts, i, j, -0.5f, gridSize, &ompVerts[threadID]); } } } std::vector<Vertex> verts; for (auto& ov : ompVerts) verts.insert(verts.end(), ov.begin(), ov.end()); for (auto& v : verts) v.normal = normalize(v.normal); // Update gpu mesh glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*verts.size(), verts.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal)); glBindVertexArray(0); _vertCount = verts.size(); }
53.491597
154
0.373184
[ "mesh", "geometry", "render", "vector" ]
ca60f08b649d631ef71fb0ffe9b4e63ba1c9354f
6,065
cpp
C++
baselines/deepq/experiments/atari/knn_cuda_fixmem/src/knn.cpp
MouseHu/emdqn
ba907e959f21dd0b5a17117accccae9c82a79a3b
[ "MIT" ]
null
null
null
baselines/deepq/experiments/atari/knn_cuda_fixmem/src/knn.cpp
MouseHu/emdqn
ba907e959f21dd0b5a17117accccae9c82a79a3b
[ "MIT" ]
null
null
null
baselines/deepq/experiments/atari/knn_cuda_fixmem/src/knn.cpp
MouseHu/emdqn
ba907e959f21dd0b5a17117accccae9c82a79a3b
[ "MIT" ]
1
2021-04-26T13:55:47.000Z
2021-04-26T13:55:47.000Z
// Python #include <boost/python.hpp> #include <numpy/ndarrayobject.h> #include "knn.h" #include <cstdio> using namespace boost::python; int address_count =0; struct KNNAddress theAddress[20]={{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}}; // For extracting features from a 4-D blob feature map. object extract_feature(PyObject* activation_, PyObject* coords_) { PyArrayObject* activation_py = (PyArrayObject*) activation_; PyArrayObject* coords_py = (PyArrayObject*) coords_; int n_batch = activation_py->dimensions[0]; int n_channel = activation_py->dimensions[1]; int height = activation_py->dimensions[2]; int width = activation_py->dimensions[3]; int n_max_coord = coords_py->dimensions[1]; int dim_coord = coords_py->dimensions[2]; float* activation = new float[n_batch * n_channel * height * width]; float* coords = new float[n_batch * n_max_coord * dim_coord]; float* extracted_activation = new float[n_batch * n_channel * n_max_coord];; // Copy python objects for(int n = 0; n < n_batch; n++){ for (int c = 0; c < n_channel; c++){ for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { activation[((n * n_channel + c) * height + i) * width + j] = *(float*)PyArray_GETPTR4(activation_py, n, c, i, j); } } } } for(int n = 0; n < n_batch; n++){ for(int i = 0; i < n_max_coord; i++) { for(int j = 0; j < dim_coord; j++) { coords[(n * n_max_coord + i) * dim_coord + j] = *(float*)PyArray_GETPTR3(coords_py, n, i, j); } } } extract_cuda(activation, n_batch, n_channel, height, width, coords, n_max_coord, dim_coord, extracted_activation); npy_intp dims[3] = {n_batch, n_channel, n_max_coord}; PyObject* py_obj = PyArray_SimpleNewFromData(3, dims, NPY_FLOAT, extracted_activation); handle<> handle(py_obj); numeric::array arr(handle); free(activation); free(coords); return arr.copy(); } object knn_fix_ref_conditional(object address_num,PyObject* query_points_, PyObject* musk_,int k,int cur_capacity) { PyArrayObject* query_points = (PyArrayObject*) query_points_; PyArrayObject* musk = (PyArrayObject*) musk_; int n_query = query_points->dimensions[0]; int dim = query_points->dimensions[1]; int address_num_c = extract<int>(address_num); float* query_points_c = new float[n_query * dim]; bool* musk_c = new bool[cur_capacity]; float* dist = new float[n_query * k]; int* ind = new int[n_query * k]; for(int i = 0; i < n_query; i++) { for(int j = 0; j < dim; j++) { query_points_c[j + i*dim] = *(float*)PyArray_GETPTR2(query_points, i, j); } } for(int j = 0; j < cur_capacity; j++) { musk_c[j] = *(float*)PyArray_GETPTR1(query_points, j); } knn_cuda_fix_ref_conditional(address_num_c,dist, ind,query_points_c, musk_c,n_query, k,cur_capacity,dim); npy_intp dims[2] = {k, n_query}; PyObject* py_obj_dist = PyArray_SimpleNewFromData(2, dims, NPY_FLOAT, dist); PyObject* py_obj_ind = PyArray_SimpleNewFromData(2, dims, NPY_INT, ind); handle<> handle_dist(py_obj_dist); handle<> handle_ind(py_obj_ind); numeric::array arr_dist(handle_dist); numeric::array arr_ind(handle_ind); free(query_points_c); return make_tuple(arr_dist.copy(), arr_ind.copy()); } // CUDA K-NN wrapper // Takes features and retuns the distances and indices of the k-nearest // neighboring features. object knn_fix_ref(object address_num,PyObject* query_points_, int k,int cur_capacity) { PyArrayObject* query_points = (PyArrayObject*) query_points_; int n_query = query_points->dimensions[0]; int dim = query_points->dimensions[1]; int address_num_c = extract<int>(address_num); float* query_points_c = new float[n_query * dim]; float* dist = new float[n_query * k]; int* ind = new int[n_query * k]; for(int i = 0; i < n_query; i++) { for(int j = 0; j < dim; j++) { query_points_c[j + i*dim] = *(float*)PyArray_GETPTR2(query_points, i, j); } } knn_cuda_fix_ref(address_num_c,dist, ind,query_points_c, n_query, k,cur_capacity,dim); npy_intp dims[2] = {k, n_query}; PyObject* py_obj_dist = PyArray_SimpleNewFromData(2, dims, NPY_FLOAT, dist); PyObject* py_obj_ind = PyArray_SimpleNewFromData(2, dims, NPY_INT, ind); handle<> handle_dist(py_obj_dist); handle<> handle_ind(py_obj_ind); numeric::array arr_dist(handle_dist); numeric::array arr_ind(handle_ind); free(query_points_c); return make_tuple(arr_dist.copy(), arr_ind.copy()); } int allocate(object size,object dims,object query_max,object k) { int size_c = extract<int>(size); int k_c = extract<int>(k); int dims_c = extract<int>(dims); int query_max_c = extract<int>(query_max); allocate_cuda(address_count,size_c,dims_c,query_max_c,k_c); address_count+=1; printf("allocate finished.\n"); return address_count-1; } void add(object address_num,object index,PyObject* ref_points_) { //printf("after here 0\n"); int index_c = extract<int>(index); int address_num_c = extract<int>(address_num); // KNNAddress pointer_c = ArraytoAddress(pointer); //printf("after here 1\n"); PyArrayObject* ref_points = (PyArrayObject*) ref_points_; // printf("after here 2\n"); int dim = ref_points->dimensions[0]; // printf("add dims:%d\n",dim); float* ref_points_c = new float[dim]; // printf("add dims:%d\n",dim); for(int j = 0; j < dim; j++) { ref_points_c[j] = *(float*)PyArray_GETPTR1(ref_points, j); } // printf("before add cuda\n"); add_cuda(address_num_c,index_c,ref_points_c,dim); // printf("after add cuda\n"); free(ref_points_c); } BOOST_PYTHON_MODULE(knn) { import_array(); numeric::array::set_module_and_type("numpy", "ndarray"); def("knn", knn_fix_ref); def("knn_conditional", knn_fix_ref_conditional); def("allocate", allocate); def("add", add); def("extract", extract_feature); }
31.102564
115
0.663314
[ "object" ]
ca6132337eb287eeb9ec2e1543ddf7732812c830
1,168
cpp
C++
Source/Renderer/SkyboxRenderer.cpp
Hopson97/Slonda-Man
169f95b8db9f1cb694ab459973f98287e5979ab6
[ "MIT" ]
7
2021-03-11T14:29:49.000Z
2021-11-14T20:31:09.000Z
Source/Renderer/SkyboxRenderer.cpp
Hopson97/Slonda-Man
169f95b8db9f1cb694ab459973f98287e5979ab6
[ "MIT" ]
null
null
null
Source/Renderer/SkyboxRenderer.cpp
Hopson97/Slonda-Man
169f95b8db9f1cb694ab459973f98287e5979ab6
[ "MIT" ]
null
null
null
#include "SkyboxRenderer.h" #include "../GLLib/GLFunctions.h" #include "../Model/Mesh.h" #include "../Camera.h" #include "../Model/Generator.h" SkyboxRenderer::SkyboxRenderer() : m_skyShader ("Skybox", "Skybox") { m_skyBoxCube.create({Cube::generateVertexPositions(300), {}, {}, Cube::generateIndices()}); m_skyTexture.loadFromFiles({"skyside", "skyside", "sky", "skyside", "skyside", "skyside"}); m_locationView = m_skyShader.getUniformLocation("viewMatrix"); m_locationProj = m_skyShader.getUniformLocation("projectionMatrix"); } void SkyboxRenderer::render(const Camera& camera) { GL::disable(GL::Cap::CullFace); m_skyShader.useProgram(); m_skyBoxCube.bindVAO(); m_skyTexture.bind(); loadUnifroms(camera); GL::drawElements(m_skyBoxCube.getIndicesCount()); GL::enable(GL::Cap::CullFace); } void SkyboxRenderer::loadUnifroms(const Camera& camera) { glm::mat4 view = camera.getViewMatrix(); view[3][0] = 0; view[3][1] = 0; view[3][2] = 0; GL::loadUniform(m_locationView, view); GL::loadUniform(m_locationProj, camera.getProjMatrix()); }
24.333333
95
0.655822
[ "mesh", "render", "model" ]
ca61c1f92e7dc3c384afdcadc974085028c29455
171
cpp
C++
6-array/6-2-vectorSTD/6-2_3_memFunc_front.cpp
tanle8/cdope
2218cb2ece25b2d7bd47c3f06384302c300957f3
[ "MIT" ]
1
2018-04-04T13:43:28.000Z
2018-04-04T13:43:28.000Z
6-array/6-2-vectorSTD/6-2_3_memFunc_front.cpp
tanle8/cdope
2218cb2ece25b2d7bd47c3f06384302c300957f3
[ "MIT" ]
null
null
null
6-array/6-2-vectorSTD/6-2_3_memFunc_front.cpp
tanle8/cdope
2218cb2ece25b2d7bd47c3f06384302c300957f3
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { vector<int> marks = {50, 45, 47, 65, 80}; cout << marks.front() << endl; return 0; }
14.25
45
0.590643
[ "vector" ]
ca6391d830529247f4727984437e83b97b8efdc9
234
cpp
C++
src/objects/RedPiece.cpp
Amirhosein-GPR/checkers
4e4eb1ec23e2f34a663b8b59b07babd03c7354ad
[ "MIT" ]
null
null
null
src/objects/RedPiece.cpp
Amirhosein-GPR/checkers
4e4eb1ec23e2f34a663b8b59b07babd03c7354ad
[ "MIT" ]
null
null
null
src/objects/RedPiece.cpp
Amirhosein-GPR/checkers
4e4eb1ec23e2f34a663b8b59b07babd03c7354ad
[ "MIT" ]
null
null
null
#include "objects/RedPiece.hpp" RedPiece::RedPiece(Vector position, SDL_Renderer *renderer, TTF_Font *font) : Piece(position, renderer, font) { SDL_Rect *RedPieceClip = new SDL_Rect{0, 0, 32, 32}; this->clip = RedPieceClip; }
33.428571
109
0.722222
[ "vector" ]
ca689047d70755656bb3dc7c77420b8b32d45e0c
56,081
cpp
C++
tmc3/geometry_octree_decoder.cpp
kento-Y/mpeg-pcc-tmc13
bff871d2a6d85568420d0c059b21bfedfb107687
[ "BSD-3-Clause" ]
110
2019-07-03T08:15:18.000Z
2022-03-23T07:43:45.000Z
tmc3/geometry_octree_decoder.cpp
kento-Y/mpeg-pcc-tmc13
bff871d2a6d85568420d0c059b21bfedfb107687
[ "BSD-3-Clause" ]
null
null
null
tmc3/geometry_octree_decoder.cpp
kento-Y/mpeg-pcc-tmc13
bff871d2a6d85568420d0c059b21bfedfb107687
[ "BSD-3-Clause" ]
44
2019-07-18T12:20:38.000Z
2022-03-18T14:29:43.000Z
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "geometry.h" #include "DualLutCoder.h" #include "OctreeNeighMap.h" #include "geometry_octree.h" #include "geometry_intra_pred.h" #include "io_hls.h" #include "tables.h" #include "quantization.h" namespace pcc { //============================================================================ class GeometryOctreeDecoder : protected GeometryOctreeContexts { public: GeometryOctreeDecoder( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, const GeometryOctreeContexts& ctxMem, EntropyDecoder* arithmeticDecoder); GeometryOctreeDecoder(const GeometryOctreeDecoder&) = default; GeometryOctreeDecoder(GeometryOctreeDecoder&&) = default; GeometryOctreeDecoder& operator=(const GeometryOctreeDecoder&) = default; GeometryOctreeDecoder& operator=(GeometryOctreeDecoder&&) = default; void beginOctreeLevel(const Vec3<int>& planarDepth); int decodePositionLeafNumPoints(); int decodeOccupancyNeighZ( int mappedOccIsPredicted, int mappedOccPrediction, int mappedOccAdjGt0, int mappedOccAdjGt1, int mappedOccAdjUnocc, int mappedPlanarMaskX, int mappedFixedMaskX0, bool planarPossibleX, int mappedPlanarMaskY, int mappedFixedMaskY0, bool planarPossibleY, int mappedPlanarMaskZ, int mappedFixedMaskZ0, bool planarPossibleZ); int decodeOccupancyNeighNZ( int neighPattern, int mappedOccIsPredicted, int mappedOccPrediction, int mappedOccAdjGt0, int mappedOccAdjGt1, int mappedOccAdjUnocc, int mappedPlanarMaskX, int mappedFixedMaskX0, bool planarPossibleX, int mappedPlanarMaskY, int mappedFixedMaskY0, bool planarPossibleY, int mappedPlanarMaskZ, int mappedFixedMaskZ0, bool planarPossibleZ); int decodeOccupancyBitwise( int neighPattern, int mappedOccIsPredicted, int mappedOccPrediction, int mappedOccAdjGt0, int mappedOccAdjGt1, int mappedOccAdjUnocc, int mappedPlanarMaskX, int mappedFixedMaskX0, bool planarPossibleX, int mappedPlanarMaskY, int mappedFixedMaskY0, bool planarPossibleY, int mappedPlanarMaskZ, int mappedFixedMaskZ0, bool planarPossibleZ); int decodeOccupancyBytewise(int neighPattern); int decodePlanarMode( OctreeNodePlanar& planar, int planeZ, int dist, int adjPlanes, int planeId, int contextAngle); void determinePlanarMode( bool adjacent_child_contextualization_enabled_flag, int planeId, OctreeNodePlanar& child, OctreePlanarBuffer::Row* planeBuffer, int coord1, int coord2, int coord3, int posInParent, const GeometryNeighPattern& gnp, uint8_t siblingOccupancy, int planarRate[3], int contextAngle); void determinePlanarMode( bool adjacent_child_contextualization_enabled_flag, const bool planarEligible[3], int posInParent, const GeometryNeighPattern& gnp, PCCOctree3Node& child, OctreeNodePlanar& planar, int contextAngle, int contextAnglePhiX, int contextAnglePhiY); uint32_t decodeOccupancy( const GeometryNeighPattern& gnp, int occupancyIsPredicted, int occupancyPrediction, int planarMaskX, int planarMaskY, int planarMaskZ, bool planarPossibleX, bool planarPossibleY, bool planarPossibleZ); Vec3<int32_t> decodePointPosition( const Vec3<int>& nodeSizeLog2, Vec3<int32_t>& deltaPlanar); void decodeOrdered2ptPrefix( Vec3<bool> directIdcm, Vec3<int>& nodeSizeLog2AfterUnordered, Vec3<int32_t> deltaUnordered[2]); Vec3<int32_t> decodePointPositionAngular( const OctreeAngPosScaler& quant, const Vec3<int>& nodeSizeLog2Rem, const Vec3<int>& angularOrigin, const int* zLaser, const int* thetaLaser, int laserIdx, const Vec3<int>& nodePos, Vec3<int> posXyz, Vec3<int> delta); bool decodeNodeQpOffsetsPresent(); int decodeQpOffset(); bool decodeIsIdcm(); template<class OutputIt> int decodeDirectPosition( bool geom_unique_points_flag, bool joint_2pt_idcm_enabled_flag, bool geom_angular_mode_enabled_flag, const Vec3<int>& nodeSizeLog2, const Vec3<int>& posQuantBitMasks, const PCCOctree3Node& node, const OctreeNodePlanar& planar, const Vec3<int>& headPos, const int* zLaser, const int* thetaLaser, int numLasers, OutputIt outputPoints); int decodeThetaRes(); const GeometryOctreeContexts& getCtx() const { return *this; } public: // selects between the bitwise and bytewise occupancy coders bool _useBitwiseOccupancyCoder; const uint8_t* _neighPattern64toR1; EntropyDecoder* _arithmeticDecoder; // Planar state OctreePlanarState _planar; // Azimuthal buffer std::vector<int> _phiBuffer; // azimuthal elementary shifts AzimuthalPhiZi _phiZi; }; //============================================================================ GeometryOctreeDecoder::GeometryOctreeDecoder( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, const GeometryOctreeContexts& ctxtMem, EntropyDecoder* arithmeticDecoder) : GeometryOctreeContexts(ctxtMem) , _useBitwiseOccupancyCoder(gps.bitwise_occupancy_coding_flag) , _neighPattern64toR1(neighPattern64toR1(gps)) , _arithmeticDecoder(arithmeticDecoder) , _planar(gps) , _phiBuffer(gps.numLasers(), 0x80000000) , _phiZi(gps.numLasers(), gps.angularNumPhiPerTurn) { if (!_useBitwiseOccupancyCoder && !gbh.entropy_continuation_flag) { for (int i = 0; i < 10; i++) _bytewiseOccupancyCoder[i].init(kDualLutOccupancyCoderInit[i]); } } //============================================================================ void GeometryOctreeDecoder::beginOctreeLevel(const Vec3<int>& planarDepth) { for (int i = 0; i < 10; i++) { _bytewiseOccupancyCoder[i].resetLut(); } _planar.initPlanes(planarDepth); } //============================================================================ // Decode the number of points in a leaf node of the octree. int GeometryOctreeDecoder::decodePositionLeafNumPoints() { int val = _arithmeticDecoder->decode(_ctxDupPointCntGt0); if (val) val += _arithmeticDecoder->decodeExpGolomb(0, _ctxDupPointCntEgl); return val + 1; } //============================================================================ int GeometryOctreeDecoder::decodePlanarMode( OctreeNodePlanar& planar, int planeZ, int dist, int adjPlanes, int planeId, int contextAngle) { const int mask0 = (1 << planeId); const int mask1[3] = {6, 5, 3}; // decode planar mode bool isPlanar = _arithmeticDecoder->decode(_ctxPlanarMode[planeId]); planar.planarMode |= isPlanar ? mask0 : 0; if (!isPlanar) { planar.planarPossible &= mask1[planeId]; return -1; } // decode the plane index // encode the plane index int planeBit; if (contextAngle == -1) { // angular mode off static const int kAdjPlaneCtx[4] = {0, 1, 2, 0}; int planePosCtx = kAdjPlaneCtx[adjPlanes]; if (planeZ < 0) { planeBit = _arithmeticDecoder->decode(_ctxPlanarPlaneLastIndexZ[planePosCtx]); } else { int discreteDist = dist > (8 >> OctreePlanarBuffer::shiftAb); int lastIndexPlane2d = planeZ + (discreteDist << 1); planeBit = _arithmeticDecoder->decode( _ctxPlanarPlaneLastIndex[planeId][planePosCtx][lastIndexPlane2d]); } } else { // angular mode on if (planeId == 2) { // angular planeBit = _arithmeticDecoder->decode( _ctxPlanarPlaneLastIndexAngular[contextAngle]); } else { // azimuthal planeBit = _arithmeticDecoder->decode( _ctxPlanarPlaneLastIndexAngularPhi[contextAngle]); } } planar.planePosBits |= (planeBit << planeId); return planeBit; } //============================================================================ void GeometryOctreeDecoder::determinePlanarMode( bool adjacent_child_contextualization_enabled_flag, int planeId, OctreeNodePlanar& planar, OctreePlanarBuffer::Row* planeBuffer, int coord1, int coord2, int coord3, int posInParent, const GeometryNeighPattern& gnp, uint8_t siblingOccupancy, int planarRate[3], int contextAngle) { const int kPlanarChildThreshold = 63; const int kAdjNeighIdxFromPlanePos[3][2] = {1, 0, 2, 3, 4, 5}; const int planeSelector = 1 << planeId; static const uint8_t KAdjNeighIdxMask[3][2] = {0x0f, 0xf0, 0x33, 0xcc, 0x55, 0xaa}; OctreePlanarBuffer::Elmt* row; int rowLen = OctreePlanarBuffer::rowSize; int closestPlanarFlag; int closestDist; int maxCoord; if (!planeBuffer) { // angular: buffer disabled closestPlanarFlag = -1; closestDist = 0; } else { coord1 = (coord1 & OctreePlanarBuffer::maskAb) >> OctreePlanarBuffer::shiftAb; coord2 = (coord2 & OctreePlanarBuffer::maskAb) >> OctreePlanarBuffer::shiftAb; coord3 = coord3 & OctreePlanarBuffer::maskC; row = planeBuffer[coord3]; maxCoord = std::max(coord1, coord2); closestDist = std::abs(maxCoord - int(row[rowLen - 1].pos)); int idxMinDist = rowLen - 1; // push closest point front row[rowLen - 1] = row[idxMinDist]; closestPlanarFlag = row[idxMinDist].planeIdx; } // The relative plane position (0|1) along the planeId axis. int pos = !(KAdjNeighIdxMask[planeId][0] & (1 << posInParent)); // Determine which adjacent planes are occupied // The low plane is at position axis - 1 bool lowAdjPlaneOccupied = adjacent_child_contextualization_enabled_flag ? KAdjNeighIdxMask[planeId][1] & gnp.adjNeighOcc[planeId] : (gnp.neighPattern >> kAdjNeighIdxFromPlanePos[planeId][0]) & 1; // The high adjacent plane is at position axis + 1 bool highAdjPlaneOccupied = !pos ? KAdjNeighIdxMask[planeId][1] & siblingOccupancy : (gnp.neighPattern >> kAdjNeighIdxFromPlanePos[planeId][1]) & 1; int adjPlanes = (highAdjPlaneOccupied << 1) | lowAdjPlaneOccupied; int planeBit = decodePlanarMode( planar, closestPlanarFlag, closestDist, adjPlanes, planeId, contextAngle); bool isPlanar = (planar.planarMode & planeSelector); planarRate[planeId] = (255 * planarRate[planeId] + (isPlanar ? 256 * 8 : 0) + 128) >> 8; if (planeBuffer) row[rowLen - 1] = {unsigned(maxCoord), planeBit}; } //============================================================================ void GeometryOctreeDecoder::determinePlanarMode( bool adjacent_child_contextualization_enabled_flag, const bool planarEligible[3], int posInParent, const GeometryNeighPattern& gnp, PCCOctree3Node& child, OctreeNodePlanar& planar, int contextAngle, int contextAnglePhiX, int contextAnglePhiY) { int xx = child.pos[0]; int yy = child.pos[1]; int zz = child.pos[2]; auto& planeBuffer = _planar._planarBuffer; // planar x if (planarEligible[0]) { determinePlanarMode( adjacent_child_contextualization_enabled_flag, 0, planar, planeBuffer.getBuffer(0), yy, zz, xx, posInParent, gnp, child.siblingOccupancy, _planar._rate.data(), contextAnglePhiX); } // planar y if (planarEligible[1]) { determinePlanarMode( adjacent_child_contextualization_enabled_flag, 1, planar, planeBuffer.getBuffer(1), xx, zz, yy, posInParent, gnp, child.siblingOccupancy, _planar._rate.data(), contextAnglePhiY); } // planar z if (planarEligible[2]) { determinePlanarMode( adjacent_child_contextualization_enabled_flag, 2, planar, planeBuffer.getBuffer(2), xx, yy, zz, posInParent, gnp, child.siblingOccupancy, _planar._rate.data(), contextAngle); } } //--------------------------------------------------------------------------- // decode occupancy bits (neighPattern10 == 0 case) int GeometryOctreeDecoder::decodeOccupancyNeighZ( int mappedOccIsPredicted, int mappedOccPrediction, int mappedOccAdjGt0, int mappedOccAdjGt1, int mappedOccAdjUnocc, int mappedPlanarMaskX, int mappedFixedMaskX0, bool planarPossibleX, int mappedPlanarMaskY, int mappedFixedMaskY0, bool planarPossibleY, int mappedPlanarMaskZ, int mappedFixedMaskZ0, bool planarPossibleZ) { int numOccupiedAcc = 0; int occupancy = 0; int maxPerPlaneX = 4 - (mappedPlanarMaskX ? 2 : 1); int maxPerPlaneY = 4 - (mappedPlanarMaskY ? 2 : 1); int maxPerPlaneZ = 4 - (mappedPlanarMaskZ ? 2 : 1); bool sure_planarityX = mappedPlanarMaskX || !planarPossibleX; bool sure_planarityY = mappedPlanarMaskY || !planarPossibleY; bool sure_planarityZ = mappedPlanarMaskZ || !planarPossibleZ; int maskedOccupancy = mappedPlanarMaskX | mappedPlanarMaskY | mappedPlanarMaskZ; int coded0X[2] = {0, 0}; int coded0Y[2] = {0, 0}; int coded0Z[2] = {0, 0}; if (maskedOccupancy) { for (int i = 0; i < 8; i++) { if ((maskedOccupancy >> i) & 1) { coded0X[(mappedFixedMaskX0 >> i) & 1]++; coded0Y[(mappedFixedMaskY0 >> i) & 1]++; coded0Z[(mappedFixedMaskZ0 >> i) & 1]++; } } } for (int i = 0; i < 8; i++) { int bit = 0; int bitIdx = kOccBitCodingOrder[i]; if ((maskedOccupancy >> bitIdx) & 1) continue; int bitAdjGt0 = (mappedOccAdjGt0 >> bitIdx) & 1; int bitAdjGt1 = (mappedOccAdjGt1 >> bitIdx) & 1; int bitAdjUnocc = (mappedOccAdjUnocc >> bitIdx) & 1; int numAdj = bitAdjGt0 + bitAdjGt1; int idxAdj = bitAdjUnocc + 2 * numAdj; if (i > 4) { static const int8_t kCtxIdxAdjReduc567[6] = {0, 0, 1, 2, 3, 3}; idxAdj = kCtxIdxAdjReduc567[idxAdj]; } int ctxIdxMapIdx = 3 * idxAdj; if (!maskedOccupancy) { int bitIsPredicted = (mappedOccIsPredicted >> bitIdx) & 1; int bitPrediction = (mappedOccPrediction >> bitIdx) & 1; ctxIdxMapIdx = 3 * idxAdj + bitIsPredicted + bitPrediction; } // NB: There must be at least two occupied child nodes // -- avoid coding the occupancy bit if it is implied. int mask0X = (mappedFixedMaskX0 >> bitIdx) & 1; bool bitIsOneX = (sure_planarityX && coded0X[mask0X] >= maxPerPlaneX) || (coded0X[0] + coded0X[1] >= 6); int mask0Y = (mappedFixedMaskY0 >> bitIdx) & 1; bool bitIsOneY = (sure_planarityY && coded0Y[mask0Y] >= maxPerPlaneY) || (coded0Y[0] + coded0Y[1] >= 6); int mask0Z = (mappedFixedMaskZ0 >> bitIdx) & 1; bool bitIsOneZ = (sure_planarityZ && coded0Z[mask0Z] >= maxPerPlaneZ) || (coded0Z[0] + coded0Z[1] >= 6); // masking for planar is here if (bitIsOneX || bitIsOneY || bitIsOneZ) { bit = 1; } else { auto& ctxIdxMap = _ctxIdxMaps[ctxIdxMapIdx]; int ctxIdx = ctxIdxMap[i][numOccupiedAcc]; bit = _arithmeticDecoder->decode(_ctxOccupancy[ctxIdx]); ctxIdxMap.evolve(bit, &ctxIdxMap[i][numOccupiedAcc]); if (!bit) { coded0X[mask0X]++; coded0Y[mask0Y]++; coded0Z[mask0Z]++; } } numOccupiedAcc += bit; occupancy |= bit << kOccBitCodingOrder[i]; } return occupancy; } //--------------------------------------------------------------------------- // decode occupancy bits (neighPattern10 != 0 case) int GeometryOctreeDecoder::decodeOccupancyNeighNZ( int neighPattern, int mappedOccIsPredicted, int mappedOccPrediction, int mappedOccAdjGt0, int mappedOccAdjGt1, int mappedOccAdjUnocc, int mappedPlanarMaskX, int mappedFixedMaskX0, bool planarPossibleX, int mappedPlanarMaskY, int mappedFixedMaskY0, bool planarPossibleY, int mappedPlanarMaskZ, int mappedFixedMaskZ0, bool planarPossibleZ) { // code occupancy using the neighbour configuration context // with reduction from 64 states to 9 (or 6). int neighPatternR1 = _neighPattern64toR1[neighPattern]; // int neighPattern9 = kNeighPattern64to9[neighPattern]; int neighPattern5 = kNeighPattern9to5[neighPatternR1]; int neighPattern3 = kNeighPattern9to3[neighPatternR1]; // int neighPattern7 = kNeighPattern10to7[neighPattern10]; // int neighPattern5 = kNeighPattern7to5[neighPattern7]; int occupancy = 0; int partialOccupancy = 0; bool sure_planarityX = mappedPlanarMaskX || !planarPossibleX; bool sure_planarityY = mappedPlanarMaskY || !planarPossibleY; bool sure_planarityZ = mappedPlanarMaskZ || !planarPossibleZ; int maskedOccupancy = mappedPlanarMaskX | mappedPlanarMaskY | mappedPlanarMaskZ; int coded0X[2] = {0, 0}; int coded0Y[2] = {0, 0}; int coded0Z[2] = {0, 0}; if (maskedOccupancy) { for (int i = 0; i < 8; i++) { if ((maskedOccupancy >> i) & 1) { coded0X[(mappedFixedMaskX0 >> i) & 1]++; coded0Y[(mappedFixedMaskY0 >> i) & 1]++; coded0Z[(mappedFixedMaskZ0 >> i) & 1]++; } } } // NB: it is impossible for pattern to be 0 (handled in Z case). // NB: offsets are added since ctxIdxMap is shared between Z and NZ cases. for (int i = 0; i < 8; i++) { // NB: if firt 7 bits are 0, then the last is implicitly 1. int bit = 0; int bitIdx = kOccBitCodingOrder[i]; if ((maskedOccupancy >> bitIdx) & 1) continue; int idx; if (i < 4) { idx = ((neighPatternR1 - 1) << i) + partialOccupancy + i + 1; } else if (i < 6) { idx = ((neighPattern5 - 1) << i) + partialOccupancy + i + 1; } else if (i == 6) { idx = ((neighPattern3 - 1) << i) + partialOccupancy + i + 1; } else if (i == 7) { idx = partialOccupancy + i + 1; } else { // work around clang -Wsometimes-uninitialized fault break; } int bitAdjGt0 = (mappedOccAdjGt0 >> bitIdx) & 1; int bitAdjGt1 = (mappedOccAdjGt1 >> bitIdx) & 1; int bitAdjUnocc = (mappedOccAdjUnocc >> bitIdx) & 1; int numAdj = bitAdjGt0 + bitAdjGt1; int idxAdj = bitAdjUnocc + 2 * numAdj; if (i > 4) { static const int8_t kCtxIdxAdjReduc567[6] = {0, 0, 1, 2, 3, 3}; idxAdj = kCtxIdxAdjReduc567[idxAdj]; } int ctxIdxMapIdx = 3 * idxAdj; if (!maskedOccupancy) { // !planar int bitIsPredicted = (mappedOccIsPredicted >> bitIdx) & 1; int bitPrediction = (mappedOccPrediction >> bitIdx) & 1; ctxIdxMapIdx = 3 * idxAdj + bitIsPredicted + bitPrediction; } // NB: if firt 7 bits are 0, then the last is implicitly 1. // masking for planar is here int mask0X = (mappedFixedMaskX0 >> bitIdx) & 1; bool bitIsOneX = (sure_planarityX && coded0X[mask0X] >= 3) || (coded0X[0] + coded0X[1] >= 7); int mask0Y = (mappedFixedMaskY0 >> bitIdx) & 1; bool bitIsOneY = (sure_planarityY && coded0Y[mask0Y] >= 3) || (coded0Y[0] + coded0Y[1] >= 7); int mask0Z = (mappedFixedMaskZ0 >> bitIdx) & 1; bool bitIsOneZ = (sure_planarityZ && coded0Z[mask0Z] >= 3) || (coded0Z[0] + coded0Z[1] >= 7); if (bitIsOneX || bitIsOneY || bitIsOneZ) { bit = 1; } else { auto& ctxIdxMap = _ctxIdxMaps[ctxIdxMapIdx]; int ctxIdx = ctxIdxMap[i][idx]; bit = _arithmeticDecoder->decode(_ctxOccupancy[ctxIdx]); ctxIdxMap.evolve(bit, &ctxIdxMap[i][idx]); if (!bit) { coded0X[mask0X]++; coded0Y[mask0Y]++; coded0Z[mask0Z]++; } } partialOccupancy |= bit << i; occupancy |= bit << kOccBitCodingOrder[i]; } return occupancy; } //------------------------------------------------------------------------- int GeometryOctreeDecoder::decodeOccupancyBitwise( int neighPattern, int mappedOccIsPredicted, int mappedOccPrediction, int mappedOccAdjGt0, int mappedOccAdjGt1, int mappedOccAdjUnocc, int mappedPlanarMaskX, int mappedFixedMaskX0, bool planarPossibleX, int mappedPlanarMaskY, int mappedFixedMaskY0, bool planarPossibleY, int mappedPlanarMaskZ, int mappedFixedMaskZ0, bool planarPossibleZ) { if (neighPattern == 0) { return decodeOccupancyNeighZ( mappedOccIsPredicted, mappedOccPrediction, mappedOccAdjGt0, mappedOccAdjGt1, mappedOccAdjUnocc, mappedPlanarMaskX, mappedFixedMaskX0, planarPossibleX, mappedPlanarMaskY, mappedFixedMaskY0, planarPossibleY, mappedPlanarMaskZ, mappedFixedMaskZ0, planarPossibleZ); } return decodeOccupancyNeighNZ( neighPattern, mappedOccIsPredicted, mappedOccPrediction, mappedOccAdjGt0, mappedOccAdjGt1, mappedOccAdjUnocc, mappedPlanarMaskX, mappedFixedMaskX0, planarPossibleX, mappedPlanarMaskY, mappedFixedMaskY0, planarPossibleY, mappedPlanarMaskZ, mappedFixedMaskZ0, planarPossibleZ); } //------------------------------------------------------------------------- int GeometryOctreeDecoder::decodeOccupancyBytewise(int neighPattern) { // code occupancy using the neighbour configuration context // with reduction from 64 states to 10 (or 6). int neighPatternR1 = _neighPattern64toR1[neighPattern]; auto& bytewiseCoder = _bytewiseOccupancyCoder[neighPatternR1]; return bytewiseCoder.decode(_arithmeticDecoder); } //------------------------------------------------------------------------- // decode node occupancy bits // uint32_t GeometryOctreeDecoder::decodeOccupancy( const GeometryNeighPattern& gnp, int occupancyIsPred, int occupancyPred, int planarMaskX, int planarMaskY, int planarMaskZ, bool planarPossibleX, bool planarPossibleY, bool planarPossibleZ) { // decode occupancy pattern uint32_t occupancy; // single child and we know its position if (planarMaskX && planarMaskY && planarMaskZ) { uint32_t cnt = (planarMaskZ & 1); cnt |= (planarMaskY & 1) << 1; cnt |= (planarMaskX & 1) << 2; occupancy = 1 << cnt; return occupancy; } // neighbour empty and only one point => decode index, not pattern if (gnp.neighPattern == 0) { bool singleChild = false; if (planarPossibleX && planarPossibleY && planarPossibleZ) { singleChild = _arithmeticDecoder->decode(_ctxSingleChild) == 1; } if (singleChild) { uint32_t cnt; if (!planarMaskZ) cnt = _arithmeticDecoder->decode(); else cnt = (planarMaskZ & 1); if (!planarMaskY) cnt |= _arithmeticDecoder->decode() << 1; else cnt |= (planarMaskY & 1) << 1; if (!planarMaskX) cnt |= _arithmeticDecoder->decode() << 2; else cnt |= (planarMaskX & 1) << 2; occupancy = 1 << cnt; return occupancy; } } // at least two child nodes occupied and two planars => we know the occupancy if (gnp.neighPattern == 0) { if (planarMaskX && planarMaskY) { uint32_t cnt = ((planarMaskX & 1) << 2) | ((planarMaskY & 1) << 1); occupancy = (1 << cnt) | (1 << (cnt + 1)); return occupancy; } if (planarMaskY && planarMaskZ) { uint32_t cnt = ((planarMaskY & 1) << 1) | (planarMaskZ & 1); occupancy = (1 << cnt) | (1 << (cnt + 4)); return occupancy; } if (planarMaskX && planarMaskZ) { uint32_t cnt = ((planarMaskX & 1) << 2) | (planarMaskZ & 1); occupancy = (1 << cnt) | (1 << (cnt + 2)); return occupancy; } } auto neighPattern = gnp.neighPattern; auto mapOccIsP = mapGeometryOccupancy(occupancyIsPred, neighPattern); auto mapOccP = mapGeometryOccupancy(occupancyPred, neighPattern); auto mapAdjGt0 = mapGeometryOccupancy(gnp.adjacencyGt0, neighPattern); auto mapAdjGt1 = mapGeometryOccupancy(gnp.adjacencyGt1, neighPattern); auto mapAdjUnocc = mapGeometryOccupancy(gnp.adjacencyUnocc, neighPattern); auto mapPlanarMaskX = mapGeometryOccupancy(planarMaskX, neighPattern); auto mapPlanarMaskY = mapGeometryOccupancy(planarMaskY, neighPattern); auto mapPlanarMaskZ = mapGeometryOccupancy(planarMaskZ, neighPattern); auto mapFixedMaskX0 = mapGeometryOccupancy(0xf0, neighPattern); auto mapFixedMaskY0 = mapGeometryOccupancy(0xcc, neighPattern); auto mapFixedMaskZ0 = mapGeometryOccupancy(0xaa, neighPattern); uint32_t mappedOccupancy; if (_useBitwiseOccupancyCoder) mappedOccupancy = decodeOccupancyBitwise( neighPattern, mapOccIsP, mapOccP, mapAdjGt0, mapAdjGt1, mapAdjUnocc, mapPlanarMaskX, mapFixedMaskX0, planarPossibleX, mapPlanarMaskY, mapFixedMaskY0, planarPossibleY, mapPlanarMaskZ, mapFixedMaskZ0, planarPossibleZ); else mappedOccupancy = decodeOccupancyBytewise(neighPattern); return mapGeometryOccupancyInv(mappedOccupancy, neighPattern); } //------------------------------------------------------------------------- bool GeometryOctreeDecoder::decodeNodeQpOffsetsPresent() { return _arithmeticDecoder->decode(); } //------------------------------------------------------------------------- int GeometryOctreeDecoder::decodeQpOffset() { if (!_arithmeticDecoder->decode(_ctxQpOffsetAbsGt0)) return 0; int dqp = _arithmeticDecoder->decodeExpGolomb(0, _ctxQpOffsetAbsEgl) + 1; int dqp_sign = _arithmeticDecoder->decode(_ctxQpOffsetSign); return dqp_sign ? -dqp : dqp; } //------------------------------------------------------------------------- // Decode a position of a point in a given volume. Vec3<int32_t> GeometryOctreeDecoder::decodePointPosition( const Vec3<int>& nodeSizeLog2, Vec3<int32_t>& deltaPlanar) { Vec3<int32_t> delta = deltaPlanar; for (int k = 0; k < 3; k++) { if (nodeSizeLog2[k] <= 0) continue; for (int i = nodeSizeLog2[k]; i > 0; i--) { delta[k] <<= 1; delta[k] |= _arithmeticDecoder->decode(); } } return delta; } //------------------------------------------------------------------------- // Decode part of the position of two unordred points point in a given volume. void GeometryOctreeDecoder::decodeOrdered2ptPrefix( Vec3<bool> directIdcm, Vec3<int>& nodeSizeLog2, Vec3<int32_t> pointPrefix[2]) { if (nodeSizeLog2[0] >= 1 && directIdcm[0]) { int ctxIdx = 0; bool sameBit = true; while (nodeSizeLog2[0] && sameBit) { pointPrefix[0][0] <<= 1; pointPrefix[1][0] <<= 1; nodeSizeLog2[0]--; sameBit = _arithmeticDecoder->decode(_ctxSameBitHighx[ctxIdx]); ctxIdx = std::min(4, ctxIdx + 1); if (sameBit) { int bit = _arithmeticDecoder->decode(); pointPrefix[0][0] |= bit; pointPrefix[1][0] |= bit; } else { pointPrefix[1][0] |= 1; } } } if (nodeSizeLog2[1] >= 1 && directIdcm[1]) { int ctxIdx = 0; bool sameBit = true; bool sameX = !directIdcm[0] || pointPrefix[0][0] == pointPrefix[1][0]; while (nodeSizeLog2[1] && sameBit) { pointPrefix[0][1] <<= 1; pointPrefix[1][1] <<= 1; nodeSizeLog2[1]--; sameBit = _arithmeticDecoder->decode(_ctxSameBitHighy[ctxIdx]); ctxIdx = std::min(4, ctxIdx + 1); int bit = 0; if (!(sameX && !sameBit)) bit = _arithmeticDecoder->decode(); pointPrefix[0][1] |= bit; pointPrefix[1][1] |= sameBit ? bit : !bit; } } if (nodeSizeLog2[2] >= 1 && directIdcm[2]) { int ctxIdx = 0; bool sameBit = true; bool sameXy = (!directIdcm[0] || pointPrefix[0][0] == pointPrefix[1][0]) && (!directIdcm[1] || pointPrefix[0][1] == pointPrefix[1][1]); while (nodeSizeLog2[2] && sameBit) { pointPrefix[0][2] <<= 1; pointPrefix[1][2] <<= 1; nodeSizeLog2[2]--; sameBit = _arithmeticDecoder->decode(_ctxSameBitHighz[ctxIdx]); ctxIdx = std::min(4, ctxIdx + 1); int bit = 0; if (!(sameXy && !sameBit)) bit = _arithmeticDecoder->decode(); pointPrefix[0][2] |= bit; pointPrefix[1][2] |= sameBit ? bit : !bit; } } } //------------------------------------------------------------------------- // Decode a position of a point in a given volume, using elevation angle prior Vec3<int32_t> GeometryOctreeDecoder::decodePointPositionAngular( const OctreeAngPosScaler& quant, const Vec3<int>& nodeSizeLog2Rem, const Vec3<int>& angularOrigin, const int* zLaser, const int* thetaLaser, int laserIdx, const Vec3<int>& nodePos, Vec3<int> posXyz, Vec3<int> delta) { // -- PHI -- // code x or y directly and compute phi of node bool directAxis = std::abs(posXyz[0]) <= std::abs(posXyz[1]); for (int i = nodeSizeLog2Rem[directAxis]; i > 0; i--) { delta[directAxis] <<= 1; delta[directAxis] |= _arithmeticDecoder->decode(); } posXyz += quant.scaleEns(delta << nodeSizeLog2Rem); posXyz[directAxis] = quant.scaleEns(directAxis, nodePos[directAxis] + delta[directAxis]) - angularOrigin[directAxis]; // laser residual laserIdx += decodeThetaRes(); // find predictor int phiNode = iatan2(posXyz[1], posXyz[0]); int predPhi = _phiBuffer[laserIdx]; if (predPhi == 0x80000000) predPhi = phiNode; // elementary shift predictor int nShift = ((predPhi - phiNode) * _phiZi.invDelta(laserIdx) + (1 << 29)) >> 30; predPhi -= _phiZi.delta(laserIdx) * nShift; // azimuthal code x or y const int phiAxis = !directAxis; for (int mask = (1 << nodeSizeLog2Rem[phiAxis]) >> 1; mask; mask >>= 1) { // angles left and right int scaledMask = quant.scaleEns(phiAxis, mask); int phiL = phiNode; int phiR = directAxis ? iatan2(posXyz[1], posXyz[0] + scaledMask) : iatan2(posXyz[1] + scaledMask, posXyz[0]); // ctx azimutal int angleL = phiL - predPhi; int angleR = phiR - predPhi; int contextAnglePhi = (angleL >= 0 && angleR >= 0) || (angleL < 0 && angleR < 0) ? 2 : 0; angleL = std::abs(angleL); angleR = std::abs(angleR); if (angleL > angleR) { contextAnglePhi++; std::swap(angleL, angleR); } if (angleR > (angleL << 1)) contextAnglePhi += 4; // entropy coding auto& ctx = _ctxPlanarPlaneLastIndexAngularPhiIDCM[contextAnglePhi]; bool bit = _arithmeticDecoder->decode(ctx); delta[phiAxis] <<= 1; if (bit) { delta[phiAxis] |= 1; posXyz[phiAxis] += scaledMask; phiNode = phiR; predPhi = _phiBuffer[laserIdx]; if (predPhi == 0x80000000) predPhi = phiNode; // elementary shift predictor int nShift = ((predPhi - phiNode) * _phiZi.invDelta(laserIdx) + (1 << 29)) >> 30; predPhi -= _phiZi.delta(laserIdx) * nShift; } } // update buffer phi _phiBuffer[laserIdx] = phiNode; // -- THETA -- int maskz = (1 << nodeSizeLog2Rem[2]) >> 1; if (!maskz) return delta; // Since x and y are known, // r is known too and does not depend on the bit for z uint64_t xLidar = (int64_t(posXyz[0]) << 8) - 128; uint64_t yLidar = (int64_t(posXyz[1]) << 8) - 128; uint64_t r2 = xLidar * xLidar + yLidar * yLidar; int64_t rInv = irsqrt(r2); // code bits for z using angular. Eligility is implicit. Laser is known. int64_t hr = zLaser[laserIdx] * rInv; int fixedThetaLaser = thetaLaser[laserIdx] + int(hr >= 0 ? -(hr >> 17) : ((-hr) >> 17)); int zShift = (rInv * quant.scaleEns(2, 1 << nodeSizeLog2Rem[2])) >> 18; for (int bitIdxZ = nodeSizeLog2Rem[2]; bitIdxZ > 0; bitIdxZ--, maskz >>= 1, zShift >>= 1) { // determine non-corrected theta int scaledMaskZ = quant.scaleEns(2, maskz); int64_t zLidar = ((posXyz[2] + scaledMaskZ) << 1) - 1; int64_t theta = zLidar * rInv; int theta32 = theta >= 0 ? theta >> 15 : -((-theta) >> 15); int thetaLaserDelta = fixedThetaLaser - theta32; int thetaLaserDeltaBot = thetaLaserDelta + zShift; int thetaLaserDeltaTop = thetaLaserDelta - zShift; int contextAngle = thetaLaserDelta >= 0 ? 0 : 1; if (thetaLaserDeltaTop >= 0) contextAngle += 2; else if (thetaLaserDeltaBot < 0) contextAngle += 2; auto& ctx = _ctxPlanarPlaneLastIndexAngularIdcm[contextAngle]; delta[2] <<= 1; delta[2] |= _arithmeticDecoder->decode(ctx); if (delta[2] & 1) posXyz[2] += scaledMaskZ; } return delta; } //------------------------------------------------------------------------- bool GeometryOctreeDecoder::decodeIsIdcm() { return _arithmeticDecoder->decode(_ctxBlockSkipTh); } //------------------------------------------------------------------------- // Direct coding of position of points in node (early tree termination). // Decoded points are written to @outputPoints // Returns the number of points emitted. template<class OutputIt> int GeometryOctreeDecoder::decodeDirectPosition( bool geom_unique_points_flag, bool joint_2pt_idcm_enabled_flag, bool geom_angular_mode_enabled_flag, const Vec3<int>& nodeSizeLog2, const Vec3<int>& posQuantBitMask, const PCCOctree3Node& node, const OctreeNodePlanar& planar, const Vec3<int>& angularOrigin, const int* zLaser, const int* thetaLaser, int numLasers, OutputIt outputPoints) { int numPoints = 1; bool numPointsGt1 = _arithmeticDecoder->decode(_ctxNumIdcmPointsGt1); numPoints += numPointsGt1; int numDuplicatePoints = 0; if (!geom_unique_points_flag && !numPointsGt1) { numDuplicatePoints = _arithmeticDecoder->decode(_ctxDupPointCntGt0); if (numDuplicatePoints) { numDuplicatePoints += _arithmeticDecoder->decode(_ctxDupPointCntGt1); if (numDuplicatePoints == 2) numDuplicatePoints += _arithmeticDecoder->decodeExpGolomb(0, _ctxDupPointCntEgl); } } // nodeSizeLog2Rem indicates the number of bits left to decode // the first bit may be inferred from the planar information Vec3<int32_t> deltaPlanar{0, 0, 0}; Vec3<int> nodeSizeLog2Rem = nodeSizeLog2; for (int k = 0; k < 3; k++) if (nodeSizeLog2Rem[k] > 0 && (planar.planarMode & (1 << k))) { deltaPlanar[k] |= (planar.planePosBits & (1 << k) ? 1 : 0); nodeSizeLog2Rem[k]--; } // quantised partial positions must be scaled for angular coding // nb, the decoded position remains quantised. OctreeAngPosScaler quant(node.qp, posQuantBitMask); // Indicates which components are directly coded Vec3<bool> directIdcm = true; // Position of the node relative to the angular origin point_t posNodeLidar; if (geom_angular_mode_enabled_flag) { posNodeLidar = quant.scaleEns(node.pos << nodeSizeLog2) - angularOrigin; bool directAxis = std::abs(posNodeLidar[0]) <= std::abs(posNodeLidar[1]); directIdcm = false; directIdcm[directAxis] = true; } // decode (ordred) two points Vec3<int32_t> deltaPos[2] = {deltaPlanar, deltaPlanar}; if (numPoints == 2 && joint_2pt_idcm_enabled_flag) decodeOrdered2ptPrefix(directIdcm, nodeSizeLog2Rem, deltaPos); int laserIdx; if (geom_angular_mode_enabled_flag) { auto delta = (deltaPos[0] << nodeSizeLog2Rem); delta += (1 << nodeSizeLog2Rem) >> 1; delta = quant.scaleEns(delta); laserIdx = findLaser(posNodeLidar + delta, thetaLaser, numLasers); } Vec3<int32_t> pos; for (int i = 0; i < numPoints; i++) { if (geom_angular_mode_enabled_flag) *(outputPoints++) = pos = decodePointPositionAngular( quant, nodeSizeLog2Rem, angularOrigin, zLaser, thetaLaser, laserIdx, node.pos << nodeSizeLog2, posNodeLidar, deltaPos[i]); else *(outputPoints++) = pos = decodePointPosition(nodeSizeLog2Rem, deltaPos[i]); } for (int i = 0; i < numDuplicatePoints; i++) *(outputPoints++) = pos; return numPoints + numDuplicatePoints; } //------------------------------------------------------------------------- int GeometryOctreeDecoder::decodeThetaRes() { if (!_arithmeticDecoder->decode(_ctxThetaRes[0])) return 0; int absVal = 1; absVal += _arithmeticDecoder->decode(_ctxThetaRes[1]); if (absVal > 1) absVal += _arithmeticDecoder->decode(_ctxThetaRes[2]); if (absVal == 3) absVal += _arithmeticDecoder->decodeExpGolomb(1, _ctxThetaResExp); bool sign = _arithmeticDecoder->decode(_ctxThetaResSign); return sign ? -absVal : absVal; } //------------------------------------------------------------------------- // Helper to inverse quantise positions Vec3<int32_t> invQuantPosition(int qp, Vec3<uint32_t> quantMasks, const Vec3<int32_t>& pos) { // pos represents the position within the coded tree as follows: // |pppppqqqqqq|00 // - p = unquantised bit // - q = quantised bit // - 0 = bits that were not coded (MSBs of q) // The reconstruction is: // |ppppp00qqqqqq| <- just prior to scaling // |pppppssssssss| < after scaling (s = scale(q)) QuantizerGeom quantizer(qp); int shiftBits = QuantizerGeom::qpShift(qp); Vec3<int32_t> recon; for (int k = 0; k < 3; k++) { int lowPart = pos[k] & (quantMasks[k] >> shiftBits); int highPart = pos[k] ^ lowPart; int lowPartScaled = PCCClip(quantizer.scale(lowPart), 0, quantMasks[k]); recon[k] = (highPart << shiftBits) | lowPartScaled; } return recon; } //------------------------------------------------------------------------- void decodeGeometryOctree( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, int skipLastLayers, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, EntropyDecoder& arithmeticDecoder, pcc::ringbuf<PCCOctree3Node>* nodesRemaining) { // init main fifo // -- worst case size is the last level containing every input poit // and each point being isolated in the previous level. // NB: some trisoup configurations can generate fewer points than // octree nodes. Blindly trusting the number of points to guide // the ringbuffer size is problematic. // todo(df): derive buffer size from level limit size_t ringBufferSize = gbh.footer.geom_num_points_minus1 + 1; if (gbh.trisoupNodeSizeLog2(gps)) ringBufferSize = 1100000; pcc::ringbuf<PCCOctree3Node> fifo(ringBufferSize + 1); // push the first node fifo.emplace_back(); PCCOctree3Node& node00 = fifo.back(); node00.start = uint32_t(0); node00.end = uint32_t(0); node00.pos = int32_t(0); node00.numSiblingsPlus1 = 8; node00.siblingOccupancy = 0; node00.qp = 0; node00.idcmEligible = 0; size_t processedPointCount = 0; std::vector<uint32_t> values; // rotating mask used to enable idcm uint32_t idcmEnableMaskInit = mkIdcmEnableMask(gps); // Lidar angles for planar prediction const int numLasers = gps.numLasers(); const int* thetaLaser = gps.angularTheta.data(); const int* zLaser = gps.angularZ.data(); // Lidar position relative to slice origin auto angularOrigin = gbh.geomAngularOrigin(gps); int deltaAngle = 128 << 18; for (int i = 0; i < numLasers - 1; i++) { int d = std::abs(thetaLaser[i] - thetaLaser[i + 1]); if (deltaAngle > d) { deltaAngle = d; } } MortonMap3D occupancyAtlas; if (gps.neighbour_avail_boundary_log2_minus1) { occupancyAtlas.resize( gps.adjacent_child_contextualization_enabled_flag, gps.neighbour_avail_boundary_log2_minus1 + 1); occupancyAtlas.clear(); } Vec3<uint32_t> posQuantBitMasks = 0xffffffff; int idcmQp = 0; int sliceQp = gbh.sliceQp(gps); int nodeQpOffsetsSignalled = !gps.geom_scaling_enabled_flag; // generate the list of the node size for each level in the tree // - starts with the smallest node and works up std::vector<Vec3<int>> lvlNodeSizeLog2{gbh.trisoupNodeSizeLog2(gps)}; for (auto split : inReverse(gbh.tree_lvl_coded_axis_list)) { Vec3<int> splitStv = {!!(split & 4), !!(split & 2), !!(split & 1)}; lvlNodeSizeLog2.push_back(lvlNodeSizeLog2.back() + splitStv); } std::reverse(lvlNodeSizeLog2.begin(), lvlNodeSizeLog2.end()); // Derived parameter used by trisoup. gbh.maxRootNodeDimLog2 = lvlNodeSizeLog2[0].max(); // the termination depth of the octree phase // NB: minNodeSizeLog2 is only non-zero for partial decoding (not trisoup) int maxDepth = lvlNodeSizeLog2.size() - skipLastLayers - 1; // append a dummy entry to the list so that depth+2 access is always valid lvlNodeSizeLog2.emplace_back(lvlNodeSizeLog2.back()); // NB: this needs to be after the root node size is determined to // allocate the planar buffer GeometryOctreeDecoder decoder(gps, gbh, ctxtMem, &arithmeticDecoder); // saved state for use with parallel bistream coding. // the saved state is restored at the start of each parallel octree level std::unique_ptr<GeometryOctreeDecoder> savedState; // The number of nodes to wait before updating the planar rate. // This is to match the prior behaviour where planar is updated once // per coded occupancy. int nodesBeforePlanarUpdate = 1; for (int depth = 0; depth < maxDepth; depth++) { // setup at the start of each level auto fifoCurrLvlEnd = fifo.end(); int numNodesNextLvl = 0; Vec3<int32_t> occupancyAtlasOrigin = 0xffffffff; // derive per-level node size related parameters auto nodeSizeLog2 = lvlNodeSizeLog2[depth]; auto childSizeLog2 = lvlNodeSizeLog2[depth + 1]; // represents the largest dimension of the current node int nodeMaxDimLog2 = nodeSizeLog2.max(); // if one dimension is not split, atlasShift[k] = 0 int codedAxesPrevLvl = depth ? gbh.tree_lvl_coded_axis_list[depth - 1] : 7; int codedAxesCurLvl = gbh.tree_lvl_coded_axis_list[depth]; // Determine if this is the level where node QPs are sent bool nodeQpOffsetsPresent = !nodeQpOffsetsSignalled && decoder.decodeNodeQpOffsetsPresent(); // record the node size when quantisation is signalled -- all subsequnt // coded occupancy bits are quantised // after the qp offset, idcm nodes do not receive special treatment if (nodeQpOffsetsPresent) { nodeQpOffsetsSignalled = true; idcmQp = 0; posQuantBitMasks = Vec3<uint32_t>((1 << nodeSizeLog2) - 1); } // Idcm quantisation applies to child nodes before per node qps if (!nodeQpOffsetsSignalled) { // If planar is enabled, the planar bits are not quantised (since // the planar mode is determined before quantisation) auto quantNodeSizeLog2 = nodeSizeLog2; if (gps.geom_planar_mode_enabled_flag) quantNodeSizeLog2 -= 1; for (int k = 0; k < 3; k++) quantNodeSizeLog2[k] = std::max(0, quantNodeSizeLog2[k]); // limit the idcmQp such that it cannot overquantise the node auto minNs = quantNodeSizeLog2.min(); idcmQp = gps.geom_base_qp + gps.geom_idcm_qp_offset; idcmQp <<= gps.geom_qp_multiplier_log2; idcmQp = std::min(idcmQp, minNs * 8); posQuantBitMasks = Vec3<uint32_t>((1 << quantNodeSizeLog2) - 1); } // save context state for parallel coding if (depth == maxDepth - 1 - gbh.geom_stream_cnt_minus1) if (gbh.geom_stream_cnt_minus1) savedState.reset(new GeometryOctreeDecoder(decoder)); // a new entropy stream starts one level after the context state is saved. // restore the saved state and flush the arithmetic decoder if (depth > maxDepth - 1 - gbh.geom_stream_cnt_minus1) { decoder = *savedState; arithmeticDecoder.flushAndRestart(); } // reset the idcm eligibility mask at the start of each level to // support multiple streams auto idcmEnableMask = rotateRight(idcmEnableMaskInit, depth); auto planarDepth = lvlNodeSizeLog2[0] - nodeSizeLog2; decoder.beginOctreeLevel(planarDepth); // process all nodes within a single level for (; fifo.begin() != fifoCurrLvlEnd; fifo.pop_front()) { PCCOctree3Node& node0 = fifo.front(); if (nodeQpOffsetsPresent) { node0.qp = sliceQp; node0.qp += decoder.decodeQpOffset() << gps.geom_qp_multiplier_log2; } int shiftBits = QuantizerGeom::qpShift(node0.qp); auto effectiveNodeSizeLog2 = nodeSizeLog2 - shiftBits; auto effectiveChildSizeLog2 = childSizeLog2 - shiftBits; // make quantisation work with qtbt and planar. auto codedAxesCurNode = codedAxesCurLvl; if (shiftBits != 0) { for (int k = 0; k < 3; k++) { if (effectiveChildSizeLog2[k] < 0) codedAxesCurNode &= ~(4 >> k); } } GeometryNeighPattern gnp{}; // The position of the node in the parent's occupancy map int posInParent = 0; posInParent |= (node0.pos[0] & 1) << 2; posInParent |= (node0.pos[1] & 1) << 1; posInParent |= (node0.pos[2] & 1) << 0; posInParent &= codedAxesPrevLvl; if (gps.neighbour_avail_boundary_log2_minus1) { updateGeometryOccupancyAtlas( node0.pos, codedAxesPrevLvl, fifo, fifoCurrLvlEnd, &occupancyAtlas, &occupancyAtlasOrigin); gnp = makeGeometryNeighPattern( gps.adjacent_child_contextualization_enabled_flag, node0.pos, codedAxesPrevLvl, codedAxesCurLvl, occupancyAtlas); } else { gnp.neighPattern = neighPatternFromOccupancy(posInParent, node0.siblingOccupancy); } int contextAngle = -1; int contextAnglePhiX = -1; int contextAnglePhiY = -1; if (gps.geom_angular_mode_enabled_flag) { contextAngle = determineContextAngleForPlanar( node0, nodeSizeLog2, angularOrigin, zLaser, thetaLaser, numLasers, deltaAngle, decoder._phiZi, decoder._phiBuffer.data(), &contextAnglePhiX, &contextAnglePhiY, posQuantBitMasks); } if (gps.geom_planar_mode_enabled_flag) { // update the plane rate depending on the occupancy and local density auto occupancy = node0.siblingOccupancy; auto numOccupied = node0.numSiblingsPlus1; if (!nodesBeforePlanarUpdate--) { decoder._planar.updateRate(occupancy, numOccupied); nodesBeforePlanarUpdate = numOccupied - 1; } } OctreeNodePlanar planar; if (!isLeafNode(effectiveNodeSizeLog2)) { // planar eligibility bool planarEligible[3] = {false, false, false}; if (gps.geom_planar_mode_enabled_flag) { decoder._planar.isEligible(planarEligible); if (gps.geom_angular_mode_enabled_flag) { if (contextAngle != -1) planarEligible[2] = true; planarEligible[0] = (contextAnglePhiX != -1); planarEligible[1] = (contextAnglePhiY != -1); } for (int k = 0; k < 3; k++) planarEligible[k] &= (codedAxesCurNode >> (2 - k)) & 1; } decoder.determinePlanarMode( gps.adjacent_child_contextualization_enabled_flag, planarEligible, posInParent, gnp, node0, planar, contextAngle, contextAnglePhiX, contextAnglePhiY); } // At the scaling depth, it is possible for a node that has previously // been marked as being eligible for idcm to be fully quantised due // to the choice of QP. There is therefore nothing to code with idcm. if (isLeafNode(effectiveNodeSizeLog2)) node0.idcmEligible = false; if (node0.idcmEligible) { bool isDirectMode = decoder.decodeIsIdcm(); if (isDirectMode) { auto idcmSize = effectiveNodeSizeLog2; if (idcmQp) { node0.qp = idcmQp; idcmSize = nodeSizeLog2 - QuantizerGeom::qpShift(idcmQp); } int numPoints = decoder.decodeDirectPosition( gps.geom_unique_points_flag, gps.joint_2pt_idcm_enabled_flag, gps.geom_angular_mode_enabled_flag, idcmSize, posQuantBitMasks, node0, planar, angularOrigin, zLaser, thetaLaser, numLasers, &pointCloud[processedPointCount]); for (int j = 0; j < numPoints; j++) { auto& point = pointCloud[processedPointCount++]; for (int k = 0; k < 3; k++) point[k] += rotateLeft(node0.pos[k], idcmSize[k]); point = invQuantPosition(node0.qp, posQuantBitMasks, point); } // NB: no further siblings to decode by definition of IDCM if (gps.inferred_direct_coding_mode <= 1) assert(node0.numSiblingsPlus1 == 1); // This node has no children, ensure that future nodes avoid // accessing stale child occupancy data. if (gps.adjacent_child_contextualization_enabled_flag) updateGeometryOccupancyAtlasOccChild( node0.pos, 0, &occupancyAtlas); continue; } } uint8_t occupancy = 1; if (!isLeafNode(effectiveNodeSizeLog2)) { // planar mode for current node // mask to be used for the occupancy coding // (bit =1 => occupancy bit not coded due to not belonging to the plane) int planarMask[3] = {0, 0, 0}; maskPlanar(planar, planarMask, codedAxesCurNode); // generate intra prediction bool intraPredUsed = !(planarMask[0] | planarMask[1] | planarMask[2]); int occupancyIsPredicted = 0; int occupancyPrediction = 0; if ( nodeMaxDimLog2 < gps.intra_pred_max_node_size_log2 && gps.neighbour_avail_boundary_log2_minus1 > 0 && intraPredUsed) { predictGeometryOccupancyIntra( occupancyAtlas, node0.pos, codedAxesPrevLvl, &occupancyIsPredicted, &occupancyPrediction); } occupancy = decoder.decodeOccupancy( gnp, occupancyIsPredicted, occupancyPrediction, planarMask[0], planarMask[1], planarMask[2], planar.planarPossible & 1, planar.planarPossible & 2, planar.planarPossible & 4); } assert(occupancy > 0); // update atlas for child neighbours // NB: the child occupancy atlas must be updated even if the current // node has no occupancy coded in order to clear any stale state in // the atlas. if (gps.adjacent_child_contextualization_enabled_flag) updateGeometryOccupancyAtlasOccChild( node0.pos, occupancy, &occupancyAtlas); // population count of occupancy for IDCM int numOccupied = popcnt(occupancy); // nodeSizeLog2 > 1: for each child: // - determine elegibility for IDCM // - directly decode point positions if IDCM allowed and selected // - otherwise, insert split children into fifo while updating neighbour state for (int i = 0; i < 8; i++) { uint32_t mask = 1 << i; if (!(occupancy & mask)) { // child is empty: skip continue; } int x = !!(i & 4); int y = !!(i & 2); int z = !!(i & 1); // point counts for leaf nodes are coded immediately upon // encountering the leaf node. if (isLeafNode(effectiveChildSizeLog2)) { int numPoints = 1; if (!gps.geom_unique_points_flag) { numPoints = decoder.decodePositionLeafNumPoints(); } // the final bits from the leaf: Vec3<int32_t> point{(node0.pos[0] << !!(codedAxesCurLvl & 4)) + x, (node0.pos[1] << !!(codedAxesCurLvl & 2)) + y, (node0.pos[2] << !!(codedAxesCurLvl & 1)) + z}; // remove any padding bits that were not coded for (int k = 0; k < 3; k++) point[k] = rotateLeft(point[k], effectiveChildSizeLog2[k]); point = invQuantPosition(node0.qp, posQuantBitMasks, point); for (int i = 0; i < numPoints; ++i) pointCloud[processedPointCount++] = point; // do not recurse into leaf nodes continue; } // create & enqueue new child. fifo.emplace_back(); auto& child = fifo.back(); child.qp = node0.qp; // only shift position if an occupancy bit was coded for the axis child.pos[0] = (node0.pos[0] << !!(codedAxesCurLvl & 4)) + x; child.pos[1] = (node0.pos[1] << !!(codedAxesCurLvl & 2)) + y; child.pos[2] = (node0.pos[2] << !!(codedAxesCurLvl & 1)) + z; child.numSiblingsPlus1 = numOccupied; child.siblingOccupancy = occupancy; child.laserIndex = node0.laserIndex; child.idcmEligible = isDirectModeEligible( gps.inferred_direct_coding_mode, nodeMaxDimLog2, gnp.neighPattern, node0, child); if (child.idcmEligible) { child.idcmEligible &= idcmEnableMask & 1; idcmEnableMask = rotateRight(idcmEnableMask, 1); } numNodesNextLvl++; } } // Check that one level hasn't produced too many nodes // todo(df): this check is too weak to spot overflowing the fifo assert(numNodesNextLvl <= ringBufferSize); } // save the context state for re-use by a future slice if required ctxtMem = decoder.getCtx(); // NB: the point cloud needs to be resized if partially decoded // OR: if geometry quantisation has changed the number of points pointCloud.resize(processedPointCount); // return partial coding result // - add missing levels to node positions and inverse quantise if (nodesRemaining) { auto nodeSizeLog2 = lvlNodeSizeLog2[maxDepth]; for (auto& node : fifo) { node.pos <<= nodeSizeLog2 - QuantizerGeom::qpShift(node.qp); node.pos = invQuantPosition(node.qp, posQuantBitMasks, node.pos); } *nodesRemaining = std::move(fifo); return; } } //------------------------------------------------------------------------- void decodeGeometryOctree( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, EntropyDecoder& arithmeticDecoder) { decodeGeometryOctree( gps, gbh, 0, pointCloud, ctxtMem, arithmeticDecoder, nullptr); } //------------------------------------------------------------------------- void decodeGeometryOctreeScalable( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, int minGeomNodeSizeLog2, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, EntropyDecoder& arithmeticDecoder) { pcc::ringbuf<PCCOctree3Node> nodes; decodeGeometryOctree( gps, gbh, minGeomNodeSizeLog2, pointCloud, ctxtMem, arithmeticDecoder, &nodes); if (minGeomNodeSizeLog2 > 0) { size_t size = pointCloud.removeDuplicatePointInQuantizedPoint(minGeomNodeSizeLog2); pointCloud.resize(size + nodes.size()); size_t processedPointCount = size; if (minGeomNodeSizeLog2 > 1) { uint32_t mask = uint32_t(-1) << minGeomNodeSizeLog2; for (auto node0 : nodes) { for (int k = 0; k < 3; k++) node0.pos[k] &= mask; node0.pos += 1 << (minGeomNodeSizeLog2 - 1); pointCloud[processedPointCount++] = node0.pos; } } else { for (auto node0 : nodes) pointCloud[processedPointCount++] = node0.pos; } } } //============================================================================ } // namespace pcc
32.834309
85
0.650737
[ "geometry", "vector" ]
ca71ac37739181882bc517ca62439fecabe89886
4,934
cc
C++
mediapipe/calculators/util/landmarks_to_detection_calculator.cc
daren996/mediapipe
87531da11494f374fe95c2bd724da7f0fc795185
[ "Apache-2.0" ]
10
2019-11-04T01:37:47.000Z
2021-06-21T03:33:24.000Z
mediapipe/calculators/util/landmarks_to_detection_calculator.cc
daren996/mediapipe
87531da11494f374fe95c2bd724da7f0fc795185
[ "Apache-2.0" ]
3
2020-06-04T13:17:46.000Z
2021-09-14T15:28:23.000Z
mediapipe/calculators/util/landmarks_to_detection_calculator.cc
daren996/mediapipe
87531da11494f374fe95c2bd724da7f0fc795185
[ "Apache-2.0" ]
6
2019-11-21T02:16:23.000Z
2020-04-05T16:19:59.000Z
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include "mediapipe/calculators/util/landmarks_to_detection_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/port/ret_check.h" namespace mediapipe { namespace { constexpr char kDetectionTag[] = "DETECTION"; constexpr char kNormalizedLandmarksTag[] = "NORM_LANDMARKS"; Detection ConvertLandmarksToDetection( const std::vector<NormalizedLandmark>& landmarks) { Detection detection; LocationData* location_data = detection.mutable_location_data(); float x_min = std::numeric_limits<float>::max(); float x_max = std::numeric_limits<float>::min(); float y_min = std::numeric_limits<float>::max(); float y_max = std::numeric_limits<float>::min(); for (const auto& landmark : landmarks) { x_min = std::min(x_min, landmark.x()); x_max = std::max(x_max, landmark.x()); y_min = std::min(y_min, landmark.y()); y_max = std::max(y_max, landmark.y()); auto keypoint = location_data->add_relative_keypoints(); keypoint->set_x(landmark.x()); keypoint->set_y(landmark.y()); } location_data->set_format(LocationData::RELATIVE_BOUNDING_BOX); LocationData::RelativeBoundingBox* relative_bbox = location_data->mutable_relative_bounding_box(); relative_bbox->set_xmin(x_min); relative_bbox->set_ymin(y_min); relative_bbox->set_width(x_max - x_min); relative_bbox->set_height(y_max - y_min); return detection; } } // namespace // Converts NormalizedLandmark to Detection proto. A relative bounding box will // be created containing all landmarks exactly. A calculator option is provided // to specify a subset of landmarks for creating the detection. // // Input: // NOMR_LANDMARKS: A vector of NormalizedLandmark. // // Output: // DETECTION: A Detection proto. // // Example config: // node { // calculator: "LandmarksToDetectionCalculator" // input_stream: "NORM_LANDMARKS:landmarks" // output_stream: "DETECTIONS:detections" // } class LandmarksToDetectionCalculator : public CalculatorBase { public: static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Open(CalculatorContext* cc) override; ::mediapipe::Status Process(CalculatorContext* cc) override; private: ::mediapipe::LandmarksToDetectionCalculatorOptions options_; }; REGISTER_CALCULATOR(LandmarksToDetectionCalculator); ::mediapipe::Status LandmarksToDetectionCalculator::GetContract( CalculatorContract* cc) { RET_CHECK(cc->Inputs().HasTag(kNormalizedLandmarksTag)); RET_CHECK(cc->Outputs().HasTag(kDetectionTag)); // TODO: Also support converting Landmark to Detection. cc->Inputs() .Tag(kNormalizedLandmarksTag) .Set<std::vector<NormalizedLandmark>>(); cc->Outputs().Tag(kDetectionTag).Set<Detection>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status LandmarksToDetectionCalculator::Open( CalculatorContext* cc) { cc->SetOffset(TimestampDiff(0)); options_ = cc->Options<::mediapipe::LandmarksToDetectionCalculatorOptions>(); return ::mediapipe::OkStatus(); } ::mediapipe::Status LandmarksToDetectionCalculator::Process( CalculatorContext* cc) { const auto& landmarks = cc->Inputs() .Tag(kNormalizedLandmarksTag) .Get<std::vector<NormalizedLandmark>>(); RET_CHECK_GT(landmarks.size(), 0) << "Input landmark vector is empty."; auto detection = absl::make_unique<Detection>(); if (options_.selected_landmark_indices_size()) { std::vector<NormalizedLandmark> subset_landmarks( options_.selected_landmark_indices_size()); for (int i = 0; i < subset_landmarks.size(); ++i) { RET_CHECK_LT(options_.selected_landmark_indices(i), landmarks.size()) << "Index of landmark subset is out of range."; subset_landmarks[i] = landmarks[options_.selected_landmark_indices(i)]; } *detection = ConvertLandmarksToDetection(subset_landmarks); } else { *detection = ConvertLandmarksToDetection(landmarks); } cc->Outputs() .Tag(kDetectionTag) .Add(detection.release(), cc->InputTimestamp()); return ::mediapipe::OkStatus(); } } // namespace mediapipe
34.746479
79
0.730847
[ "vector" ]
ca776d47ae56cb50c85222323eb14eca9beeb4bc
9,042
cc
C++
PhysicsTools/NanoAOD/plugins/VertexTableProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
PhysicsTools/NanoAOD/plugins/VertexTableProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
PhysicsTools/NanoAOD/plugins/VertexTableProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// -*- C++ -*- // // Package: PhysicsTools/NanoAOD // Class: VertexTableProducer // /**\class VertexTableProducer VertexTableProducer.cc PhysicsTools/VertexTableProducer/plugins/VertexTableProducer.cc Description: [one line class summary] Implementation: [Notes on implementation] */ // // Original Author: Andrea Rizzi // Created: Mon, 28 Aug 2017 09:26:39 GMT // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/StreamID.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/Candidate/interface/VertexCompositePtrCandidate.h" #include "CommonTools/Utils/interface/StringCutObjectSelector.h" #include "DataFormats/NanoAOD/interface/FlatTable.h" #include "RecoVertex/VertexTools/interface/VertexDistance3D.h" #include "RecoVertex/VertexTools/interface/VertexDistanceXY.h" #include "RecoVertex/VertexPrimitives/interface/ConvertToFromReco.h" #include "RecoVertex/VertexPrimitives/interface/VertexState.h" #include "DataFormats/Common/interface/ValueMap.h" // // class declaration // class VertexTableProducer : public edm::stream::EDProducer<> { public: explicit VertexTableProducer(const edm::ParameterSet&); ~VertexTableProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void beginStream(edm::StreamID) override; void produce(edm::Event&, const edm::EventSetup&) override; void endStream() override; //virtual void beginRun(edm::Run const&, edm::EventSetup const&) override; //virtual void endRun(edm::Run const&, edm::EventSetup const&) override; //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; // ----------member data --------------------------- const edm::EDGetTokenT<std::vector<reco::Vertex>> pvs_; const edm::EDGetTokenT<edm::ValueMap<float>> pvsScore_; const edm::EDGetTokenT<edm::View<reco::VertexCompositePtrCandidate>> svs_; const StringCutObjectSelector<reco::Candidate> svCut_; const StringCutObjectSelector<reco::Vertex> goodPvCut_; const std::string goodPvCutString_; const std::string pvName_; const std::string svName_; const std::string svDoc_; const double dlenMin_, dlenSigMin_; }; // // constructors and destructor // VertexTableProducer::VertexTableProducer(const edm::ParameterSet& params) : pvs_(consumes<std::vector<reco::Vertex>>(params.getParameter<edm::InputTag>("pvSrc"))), pvsScore_(consumes<edm::ValueMap<float>>(params.getParameter<edm::InputTag>("pvSrc"))), svs_(consumes<edm::View<reco::VertexCompositePtrCandidate>>(params.getParameter<edm::InputTag>("svSrc"))), svCut_(params.getParameter<std::string>("svCut"), true), goodPvCut_(params.getParameter<std::string>("goodPvCut"), true), goodPvCutString_(params.getParameter<std::string>("goodPvCut")), pvName_(params.getParameter<std::string>("pvName")), svName_(params.getParameter<std::string>("svName")), svDoc_(params.getParameter<std::string>("svDoc")), dlenMin_(params.getParameter<double>("dlenMin")), dlenSigMin_(params.getParameter<double>("dlenSigMin")) { produces<nanoaod::FlatTable>("pv"); produces<nanoaod::FlatTable>("otherPVs"); produces<nanoaod::FlatTable>("svs"); produces<edm::PtrVector<reco::Candidate>>(); } VertexTableProducer::~VertexTableProducer() { // do anything here that needs to be done at destruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called to produce the data ------------ void VertexTableProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; edm::Handle<edm::ValueMap<float>> pvsScoreIn; edm::Handle<std::vector<reco::Vertex>> pvsIn; iEvent.getByToken(pvs_, pvsIn); iEvent.getByToken(pvsScore_, pvsScoreIn); auto pvTable = std::make_unique<nanoaod::FlatTable>(1, pvName_, true); pvTable->addColumnValue<float>("ndof", (*pvsIn)[0].ndof(), "main primary vertex number of degree of freedom", 8); pvTable->addColumnValue<float>("x", (*pvsIn)[0].position().x(), "main primary vertex position x coordinate", 10); pvTable->addColumnValue<float>("y", (*pvsIn)[0].position().y(), "main primary vertex position y coordinate", 10); pvTable->addColumnValue<float>("z", (*pvsIn)[0].position().z(), "main primary vertex position z coordinate", 16); pvTable->addColumnValue<float>("chi2", (*pvsIn)[0].normalizedChi2(), "main primary vertex reduced chi2", 8); int goodPVs = 0; for (const auto& pv : *pvsIn) if (goodPvCut_(pv)) goodPVs++; pvTable->addColumnValue<int>("npvs", pvsIn->size(), "total number of reconstructed primary vertices"); pvTable->addColumnValue<int>( "npvsGood", goodPVs, "number of good reconstructed primary vertices. selection:" + goodPvCutString_); pvTable->addColumnValue<float>( "score", pvsScoreIn->get(pvsIn.id(), 0), "main primary vertex score, i.e. sum pt2 of clustered objects", 8); auto otherPVsTable = std::make_unique<nanoaod::FlatTable>((*pvsIn).size() > 4 ? 3 : (*pvsIn).size() - 1, "Other" + pvName_, false); std::vector<float> pvsz; for (size_t i = 1; i < (*pvsIn).size() && i < 4; i++) pvsz.push_back((*pvsIn)[i - 1].position().z()); otherPVsTable->addColumn<float>("z", pvsz, "Z position of other primary vertices, excluding the main PV", 8); edm::Handle<edm::View<reco::VertexCompositePtrCandidate>> svsIn; iEvent.getByToken(svs_, svsIn); auto selCandSv = std::make_unique<PtrVector<reco::Candidate>>(); std::vector<float> dlen, dlenSig, pAngle, dxy, dxySig; std::vector<int> charge; VertexDistance3D vdist; VertexDistanceXY vdistXY; size_t i = 0; const auto& PV0 = pvsIn->front(); for (const auto& sv : *svsIn) { if (svCut_(sv)) { Measurement1D dl = vdist.distance(PV0, VertexState(RecoVertex::convertPos(sv.position()), RecoVertex::convertError(sv.error()))); if (dl.value() > dlenMin_ and dl.significance() > dlenSigMin_) { dlen.push_back(dl.value()); dlenSig.push_back(dl.significance()); edm::Ptr<reco::Candidate> c = svsIn->ptrAt(i); selCandSv->push_back(c); double dx = (PV0.x() - sv.vx()), dy = (PV0.y() - sv.vy()), dz = (PV0.z() - sv.vz()); double pdotv = (dx * sv.px() + dy * sv.py() + dz * sv.pz()) / sv.p() / sqrt(dx * dx + dy * dy + dz * dz); pAngle.push_back(std::acos(pdotv)); Measurement1D d2d = vdistXY.distance( PV0, VertexState(RecoVertex::convertPos(sv.position()), RecoVertex::convertError(sv.error()))); dxy.push_back(d2d.value()); dxySig.push_back(d2d.significance()); int sum_charge = 0; for (unsigned int id = 0; id < sv.numberOfDaughters(); ++id) { const reco::Candidate* daughter = sv.daughter(id); sum_charge += daughter->charge(); } charge.push_back(sum_charge); } } i++; } auto svsTable = std::make_unique<nanoaod::FlatTable>(selCandSv->size(), svName_, false); // For SV we fill from here only stuff that cannot be created with the SimpleFlatTableProducer svsTable->addColumn<float>("dlen", dlen, "decay length in cm", 10); svsTable->addColumn<float>("dlenSig", dlenSig, "decay length significance", 10); svsTable->addColumn<float>("dxy", dxy, "2D decay length in cm", 10); svsTable->addColumn<float>("dxySig", dxySig, "2D decay length significance", 10); svsTable->addColumn<float>("pAngle", pAngle, "pointing angle, i.e. acos(p_SV * (SV - PV)) ", 10); svsTable->addColumn<int>("charge", charge, "sum of the charge of the SV tracks", 10); iEvent.put(std::move(pvTable), "pv"); iEvent.put(std::move(otherPVsTable), "otherPVs"); iEvent.put(std::move(svsTable), "svs"); iEvent.put(std::move(selCandSv)); } // ------------ method called once each stream before processing any runs, lumis or events ------------ void VertexTableProducer::beginStream(edm::StreamID) {} // ------------ method called once each stream after processing all runs, lumis and events ------------ void VertexTableProducer::endStream() {} // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ void VertexTableProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { //The following says we do not know what parameters are allowed so do no validation // Please change this to state exactly what you do use, even if it is no parameters edm::ParameterSetDescription desc; desc.setUnknown(); descriptions.addDefault(desc); } //define this as a plug-in DEFINE_FWK_MODULE(VertexTableProducer);
42.650943
120
0.698297
[ "vector" ]
ca7a7299c0a6e0f22467efd4fa5cace8628a1978
12,831
cpp
C++
Mysql/storage/ndb/test/run-test/db.cpp
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
1
2015-12-24T16:44:50.000Z
2015-12-24T16:44:50.000Z
Mysql/storage/ndb/test/run-test/db.cpp
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
1
2015-12-24T18:23:56.000Z
2015-12-24T18:24:26.000Z
Mysql/storage/ndb/test/run-test/db.cpp
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "atrt.hpp" #include <NdbSleep.h> static bool populate_db(atrt_config&, atrt_process*); static bool setup_repl(atrt_config&); static bool run_query(atrt_process* proc, const char * query) { MYSQL* mysql = &proc->m_mysql; g_logger.debug("'%s@%s' - Running query '%s'", proc->m_cluster->m_name.c_str(), proc->m_host->m_hostname.c_str(), query); if (mysql_query(mysql, query)) { g_logger.error("'%s@%s' - Failed to run query '%s' %d:%s", proc->m_cluster->m_name.c_str(), proc->m_host->m_hostname.c_str(), query, mysql_errno(mysql), mysql_error(mysql)); return false; } return true; } static const char* create_sql[] = { "create database atrt", "use atrt", "create table host (" " id int primary key," " name varchar(255)," " port int unsigned," " unique(name, port)" ") engine = myisam;", "create table cluster (" " id int primary key," " name varchar(255)," " unique(name)" " ) engine = myisam;", "create table process (" " id int primary key," " host_id int not null," " cluster_id int not null," " node_id int not null," " type enum ('ndbd', 'ndbapi', 'ndb_mgmd', 'mysqld', 'mysql') not null," " state enum ('starting', 'started', 'stopping', 'stopped') not null" " ) engine = myisam;", "create table options (" " id int primary key," " process_id int not null," " name varchar(255) not null," " value varchar(255) not null" " ) engine = myisam;", "create table repl (" " id int auto_increment primary key," " master_id int not null," " slave_id int not null" " ) engine = myisam;", "create table command (" " id int auto_increment primary key," " state enum ('new', 'running', 'done') not null default 'new'," " cmd int not null," " process_id int not null," " process_args varchar(255) default NULL" " ) engine = myisam;", 0}; bool setup_db(atrt_config& config) { /** * Install atrt db */ atrt_process* atrt_client = 0; { atrt_cluster* cluster = 0; for (unsigned i = 0; i<config.m_clusters.size(); i++) { if (strcmp(config.m_clusters[i]->m_name.c_str(), ".atrt") == 0) { cluster = config.m_clusters[i]; for (unsigned i = 0; i<cluster->m_processes.size(); i++) { if (cluster->m_processes[i]->m_type == atrt_process::AP_CLIENT) { atrt_client = cluster->m_processes[i]; break; } } break; } } } /** * connect to all mysqld's */ #ifndef _WIN32 for (size_t i = 0; i<config.m_processes.size(); i++) { atrt_process * proc = config.m_processes[i]; if (proc->m_type == atrt_process::AP_MYSQLD) { if (!connect_mysqld(* config.m_processes[i])) return false; } } if (atrt_client) { atrt_process* atrt_mysqld = atrt_client->m_mysqld; require(atrt_mysqld); // Run the commands to create the db for (int i = 0; create_sql[i]; i++) { const char* query = create_sql[i]; if (!run_query(atrt_mysqld, query)) return false; } if (!populate_db(config, atrt_mysqld)) return false; } /** * setup replication */ if (setup_repl(config) != true) return false; #endif return true; } static const char* find(atrt_process* proc, const char * key) { const char * res = 0; if (proc->m_options.m_loaded.get(key, &res)) return res; proc->m_options.m_generated.get(key, &res); return res; } bool connect_mysqld(atrt_process& proc) { if ( !mysql_init(&proc.m_mysql)) { g_logger.error("Failed to init mysql"); return false; } const char * port = find(&proc, "--port="); const char * socket = find(&proc, "--socket="); if (port == 0 && socket == 0) { g_logger.error("Neither socket nor port specified...cant connect to mysql"); return false; } for (size_t i = 0; i<20; i++) { if (port) { mysql_protocol_type val = MYSQL_PROTOCOL_TCP; mysql_options(&proc.m_mysql, MYSQL_OPT_PROTOCOL, &val); } if (mysql_real_connect(&proc.m_mysql, proc.m_host->m_hostname.c_str(), "root", "", "test", port ? atoi(port) : 0, socket, 0)) { return true; } g_logger.info("Retrying connect to %s:%u 3s", proc.m_host->m_hostname.c_str(),atoi(port)); NdbSleep_SecSleep(3); } g_logger.error("Failed to connect to mysqld err: >%s< >%s:%u:%s<", mysql_error(&proc.m_mysql), proc.m_host->m_hostname.c_str(), port ? atoi(port) : 0, socket ? socket : "<null>"); return false; } bool disconnect_mysqld(atrt_process& proc) { mysql_close(&proc.m_mysql); return true; } void BINDI(MYSQL_BIND& bind, int * i) { bind.buffer_type= MYSQL_TYPE_LONG; bind.buffer= (char*)i; bind.is_unsigned= 0; bind.is_null= 0; } void BINDS(MYSQL_BIND& bind, const char * s, unsigned long * len) { bind.buffer_type= MYSQL_TYPE_STRING; bind.buffer= (char*)s; bind.buffer_length= * len = (unsigned long)strlen(s); bind.length= len; bind.is_null= 0; } template <typename T> int find(T* obj, Vector<T*>& arr) { for (unsigned i = 0; i<arr.size(); i++) if (arr[i] == obj) return (int)i; abort(); return -1; } static bool populate_options(MYSQL* mysql, MYSQL_STMT* stmt, int* option_id, int process_id, Properties* p) { int kk = *option_id; Properties::Iterator it(p); const char * name = it.first(); for (; name; name = it.next()) { int optid = kk; int proc_id = process_id; unsigned long l0, l1; const char * value; p->get(name, &value); MYSQL_BIND bind2[4]; bzero(bind2, sizeof(bind2)); BINDI(bind2[0], &optid); BINDI(bind2[1], &proc_id); BINDS(bind2[2], name, &l0); BINDS(bind2[3], value, &l1); if (mysql_stmt_bind_param(stmt, bind2)) { g_logger.error("Failed to bind: %s", mysql_error(mysql)); return false; } if (mysql_stmt_execute(stmt)) { g_logger.error("0 Failed to execute: %s", mysql_error(mysql)); return false; } kk++; } *option_id = kk; return true; } static bool populate_db(atrt_config& config, atrt_process* mysqld) { { const char * sql = "INSERT INTO host (id, name, port) values (?, ?, ?)"; MYSQL_STMT * stmt = mysql_stmt_init(&mysqld->m_mysql); if (mysql_stmt_prepare(stmt, sql, (unsigned long)strlen(sql))) { g_logger.error("Failed to prepare: %s", mysql_error(&mysqld->m_mysql)); return false; } for (unsigned i = 0; i<config.m_hosts.size(); i++) { unsigned long l0; MYSQL_BIND bind[3]; bzero(bind, sizeof(bind)); int id = (int)i; int port = config.m_hosts[i]->m_cpcd->getPort(); BINDI(bind[0], &id); BINDS(bind[1], config.m_hosts[i]->m_hostname.c_str(), &l0); BINDI(bind[2], &port); if (mysql_stmt_bind_param(stmt, bind)) { g_logger.error("Failed to bind: %s", mysql_error(&mysqld->m_mysql)); return false; } if (mysql_stmt_execute(stmt)) { g_logger.error("1 Failed to execute: %s", mysql_error(&mysqld->m_mysql)); return false; } } mysql_stmt_close(stmt); } { const char * sql = "INSERT INTO cluster (id, name) values (?, ?)"; MYSQL_STMT * stmt = mysql_stmt_init(&mysqld->m_mysql); if (mysql_stmt_prepare(stmt, sql, (unsigned long)strlen(sql))) { g_logger.error("Failed to prepare: %s", mysql_error(&mysqld->m_mysql)); return false; } for (unsigned i = 0; i<config.m_clusters.size(); i++) { unsigned long l0; MYSQL_BIND bind[2]; bzero(bind, sizeof(bind)); int id = (int)i; BINDI(bind[0], &id); BINDS(bind[1], config.m_clusters[i]->m_name.c_str(), &l0); if (mysql_stmt_bind_param(stmt, bind)) { g_logger.error("Failed to bind: %s", mysql_error(&mysqld->m_mysql)); return false; } if (mysql_stmt_execute(stmt)) { g_logger.error("2 Failed to execute: %s", mysql_error(&mysqld->m_mysql)); return false; } } mysql_stmt_close(stmt); } { const char * sql = "INSERT INTO process (id, host_id, cluster_id, type, state, node_id) values (?,?,?,?,?,?)"; const char * sqlopt = "INSERT INTO options (id, process_id, name, value) values (?,?,?,?)"; MYSQL_STMT * stmt = mysql_stmt_init(&mysqld->m_mysql); if (mysql_stmt_prepare(stmt, sql, (unsigned long)strlen(sql))) { g_logger.error("Failed to prepare: %s", mysql_error(&mysqld->m_mysql)); return false; } MYSQL_STMT * stmtopt = mysql_stmt_init(&mysqld->m_mysql); if (mysql_stmt_prepare(stmtopt, sqlopt, (unsigned long)strlen(sqlopt))) { g_logger.error("Failed to prepare: %s", mysql_error(&mysqld->m_mysql)); return false; } int option_id = 0; for (unsigned i = 0; i<config.m_processes.size(); i++) { unsigned long l0, l1; MYSQL_BIND bind[6]; bzero(bind, sizeof(bind)); int id = (int)i; atrt_process* proc = config.m_processes[i]; int host_id = find(proc->m_host, config.m_hosts); int cluster_id = find(proc->m_cluster, config.m_clusters); int node_id= proc->m_nodeid; const char * type = 0; const char * state = "started"; switch(proc->m_type){ case atrt_process::AP_NDBD: type = "ndbd"; break; case atrt_process::AP_NDB_API: type = "ndbapi"; state = "stopped";break; case atrt_process::AP_NDB_MGMD: type = "ndb_mgmd"; break; case atrt_process::AP_MYSQLD: type = "mysqld"; break; case atrt_process::AP_CLIENT: type = "mysql"; state = "stopped";break; default: abort(); } BINDI(bind[0], &id); BINDI(bind[1], &host_id); BINDI(bind[2], &cluster_id); BINDS(bind[3], type, &l0); BINDS(bind[4], state, &l1); BINDI(bind[5], &node_id); if (mysql_stmt_bind_param(stmt, bind)) { g_logger.error("Failed to bind: %s", mysql_error(&mysqld->m_mysql)); return false; } if (mysql_stmt_execute(stmt)) { g_logger.error("3 Failed to execute: %s", mysql_error(&mysqld->m_mysql)); return false; } if (populate_options(&mysqld->m_mysql, stmtopt, &option_id, id, &proc->m_options.m_loaded) == false) return false; if (populate_options(&mysqld->m_mysql, stmtopt, &option_id, id, &proc->m_cluster->m_options.m_loaded) == false) return false; } mysql_stmt_close(stmt); mysql_stmt_close(stmtopt); } return true; } static bool setup_repl(atrt_process* dst, atrt_process* src) { if (!run_query(src, "STOP SLAVE")) { g_logger.error("Failed to stop slave: %s", mysql_error(&src->m_mysql)); return false; } if (!run_query(src, "RESET SLAVE")) { g_logger.error("Failed to reset slave: %s", mysql_error(&src->m_mysql)); return false; } BaseString tmp; tmp.assfmt("CHANGE MASTER TO " " MASTER_HOST='%s', " " MASTER_PORT=%u ", dst->m_host->m_hostname.c_str(), atoi(find(dst, "--port="))); if (!run_query(src, tmp.c_str())) { g_logger.error("Failed to setup repl from %s to %s: %s", src->m_host->m_hostname.c_str(), dst->m_host->m_hostname.c_str(), mysql_error(&src->m_mysql)); return false; } if (!run_query(src, "START SLAVE")) { g_logger.error("Failed to start slave: %s", mysql_error(&src->m_mysql)); return false; } g_logger.info("Replication from %s(%s) to %s(%s) setup", src->m_host->m_hostname.c_str(), src->m_cluster->m_name.c_str(), dst->m_host->m_hostname.c_str(), dst->m_cluster->m_name.c_str()); return true; } bool setup_repl(atrt_config& config) { for (unsigned i = 0; i<config.m_processes.size(); i++) { atrt_process * dst = config.m_processes[i]; if (dst->m_rep_src) { if (setup_repl(dst->m_rep_src, dst) != true) return false; } } return true; } template int find(atrt_host* obj, Vector<atrt_host*>& arr); template int find(atrt_cluster* obj, Vector<atrt_cluster*>& arr);
24.77027
97
0.615307
[ "vector" ]
ca7d62bc84578a3c27a0644177d746d9d5f98e97
8,351
cpp
C++
CSCI-104/hw2/hw2-test/lliststr_gtest.cpp
liyang990803/CSCI-103
6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a
[ "MIT" ]
null
null
null
CSCI-104/hw2/hw2-test/lliststr_gtest.cpp
liyang990803/CSCI-103
6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a
[ "MIT" ]
null
null
null
CSCI-104/hw2/hw2-test/lliststr_gtest.cpp
liyang990803/CSCI-103
6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a
[ "MIT" ]
1
2018-03-23T04:19:24.000Z
2018-03-23T04:19:24.000Z
/* CS 104: Homework 2 Problem 7 gtest_LListStr.cpp Contains unit tests for checking student's implementations of a doubly linked list that tracks integers. */ #include <iostream> #include <cstdlib> #include <string> #include <vector> #include "gtest/gtest.h" #include "../lliststr.h" class LListStrTest : public testing::Test { protected: LListStrTest() { } ~LListStrTest() { } virtual void SetUp() { mLListStr = new LListStr(); srand(10442); } virtual void TearDown() { delete mLListStr; } LListStr *mLListStr; }; int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } TEST_F(LListStrTest, Test1_InitiallyEmpty) { EXPECT_TRUE(mLListStr->empty()); } TEST_F(LListStrTest, Test2_InitiallySizeZero) { EXPECT_EQ(mLListStr->size(), 0); } TEST_F(LListStrTest, Test3_EmptyInsertLess) { mLListStr->insert(-1, "a"); EXPECT_TRUE(mLListStr->empty()); EXPECT_EQ(mLListStr->size(), 0); } TEST_F(LListStrTest, Test4_EmptyInsertGreater) { mLListStr->insert(1, "10"); EXPECT_TRUE(mLListStr->empty()); EXPECT_EQ(mLListStr->size(), 0); } TEST_F(LListStrTest, Test5_EmptyGetLess) { EXPECT_EQ(mLListStr->get(-1), ""); } TEST_F(LListStrTest, Test6_EmptyGetGreater) { EXPECT_EQ(mLListStr->get(1), ""); } TEST_F(LListStrTest, Test7_EmptyRemoveLess) { mLListStr->remove(-1); EXPECT_TRUE(mLListStr->empty()); EXPECT_EQ(mLListStr->size(), 0); } TEST_F(LListStrTest, Test8_EmptyRemoveGreater) { mLListStr->remove(1); EXPECT_TRUE(mLListStr->empty()); EXPECT_EQ(mLListStr->size(), 0); } TEST_F(LListStrTest, Test9_SingleInsertNotEmpty) { mLListStr->insert(0, "10"); EXPECT_FALSE(mLListStr->empty()); } TEST_F(LListStrTest, Test10_SingleInsertSize) { mLListStr->insert(0, "10"); EXPECT_EQ(mLListStr->size(), 1); } TEST_F(LListStrTest, Test11_SingleInsertThenRemoveEmpty) { mLListStr->insert(0, "10"); mLListStr->remove(0); EXPECT_TRUE(mLListStr->empty()); } TEST_F(LListStrTest, Test12_SingleInsertThenRemoveSize) { mLListStr->insert(0, "10"); mLListStr->remove(0); EXPECT_EQ(mLListStr->size(), 0); } TEST_F(LListStrTest, Test13_MultipleInsertHeadCheckOrder) { const int NUMBER_OF_ELEMENTS = 10; for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->insert(0, std::to_string(i)); EXPECT_EQ(mLListStr->size(), i + 1); } for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { EXPECT_EQ(mLListStr->get(i), std::to_string(NUMBER_OF_ELEMENTS - i - 1)); } } TEST_F(LListStrTest, Test14_MultipleInsertTailCheckOrder) { const int NUMBER_OF_ELEMENTS = 10; for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->insert(mLListStr->size(), std::to_string(i)); EXPECT_EQ(mLListStr->size(), i + 1); } for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { EXPECT_EQ(mLListStr->get(i), std::to_string(i)); } } TEST_F(LListStrTest, Test15_MultipleInsertMiddleCheckOrder) { const int NUMBER_OF_ELEMENTS = 10; for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->insert(mLListStr->size() / 2, std::to_string(i)); EXPECT_EQ(mLListStr->size(), i + 1); } EXPECT_EQ(mLListStr->get(0), "1"); EXPECT_EQ(mLListStr->get(1), "3"); EXPECT_EQ(mLListStr->get(2), "5"); EXPECT_EQ(mLListStr->get(3), "7"); EXPECT_EQ(mLListStr->get(4), "9"); EXPECT_EQ(mLListStr->get(5), "8"); EXPECT_EQ(mLListStr->get(6), "6"); EXPECT_EQ(mLListStr->get(7), "4"); EXPECT_EQ(mLListStr->get(8), "2"); EXPECT_EQ(mLListStr->get(9), "0"); } TEST_F(LListStrTest, Test16_MultipleInsertRandomThenRemoveRandom) { const int NUMBER_OF_ELEMENTS = 10; std::vector<std::string> actual; mLListStr->insert(0, "0"); actual.insert(actual.begin(), "0"); for(int i = 1; i < NUMBER_OF_ELEMENTS; ++i) { int index = rand() % mLListStr->size(); mLListStr->insert(index, std::to_string(i)); actual.insert(actual.begin() + index, std::to_string(i)); EXPECT_EQ(mLListStr->size(), i + 1); } for(unsigned int i = 0; i < actual.size(); ++i) { EXPECT_EQ(mLListStr->get(i), actual[i]); } int size = mLListStr->size(); while(mLListStr->size() != 1) { mLListStr->remove(rand() % (mLListStr->size() - 1)); EXPECT_EQ(mLListStr->size(), --size); } } TEST_F(LListStrTest, Test17_EmptySetLess) { mLListStr->set(-1, "a"); EXPECT_EQ(mLListStr->size(), 0); EXPECT_TRUE(mLListStr->empty()); } TEST_F(LListStrTest, Test18_EmptySetGreater) { mLListStr->set(1, "a"); EXPECT_EQ(mLListStr->size(), 0); EXPECT_TRUE(mLListStr->empty()); } TEST_F(LListStrTest, Test19_SingleSet) { mLListStr->insert(0, "10"); mLListStr->set(0, "1"); EXPECT_EQ(mLListStr->size(), 1); EXPECT_FALSE(mLListStr->empty()); EXPECT_EQ(mLListStr->get(0), "1"); } TEST_F(LListStrTest, Test20_SingleSetRemove) { mLListStr->insert(0, "10"); mLListStr->set(0, "1"); mLListStr->remove(0); EXPECT_EQ(mLListStr->size(), 0); EXPECT_TRUE(mLListStr->empty()); } TEST_F(LListStrTest, Test21_MultipleSetHeadCheckOrder) { const int NUMBER_OF_ELEMENTS = 10; for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->insert(0, std::to_string(i)); EXPECT_EQ(mLListStr->size(), i + 1); } for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->set(0, std::to_string(NUMBER_OF_ELEMENTS - 1 - i)); EXPECT_EQ(mLListStr->get(0), std::to_string(NUMBER_OF_ELEMENTS - 1 - i)); mLListStr->remove(0); } } TEST_F(LListStrTest, Test22_MultipleSetTailCheckOrder) { const int NUMBER_OF_ELEMENTS = 10; for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->insert(0, std::to_string(i)); EXPECT_EQ(mLListStr->size(), i + 1); } for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->set(NUMBER_OF_ELEMENTS - 1 - i, std::to_string(i)); EXPECT_EQ(mLListStr->get(NUMBER_OF_ELEMENTS - 1 - i), std::to_string(i)); mLListStr->remove(NUMBER_OF_ELEMENTS - 1 - i); } } TEST_F(LListStrTest, Test23_MultipleSetMiddleCheckOrder) { const int NUMBER_OF_ELEMENTS = 10; for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->insert(i, std::to_string(i)); EXPECT_EQ(mLListStr->size(), i + 1); } for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { if(i % 2 == 0) { mLListStr->set(i, "a"); EXPECT_EQ(mLListStr->get(i), "a"); } else { EXPECT_EQ(mLListStr->get(i), std::to_string(i)); } } } TEST_F(LListStrTest, Test24_InsertRemoveInsert) { const int NUMBER_OF_ELEMENTS = 10; for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->insert(0, std::to_string(i)); } for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->remove(0); } std::vector<std::string> actual; for(int i = 10; i < NUMBER_OF_ELEMENTS + 10; ++i) { mLListStr->insert(0, std::to_string(i)); actual.insert(actual.begin(), std::to_string(i)); } for(unsigned int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { EXPECT_EQ(mLListStr->get(i), actual[i]); } EXPECT_EQ(mLListStr->size(), actual.size()); EXPECT_EQ(mLListStr->empty(), actual.empty()); } TEST_F(LListStrTest, Test25_LargeInputStressTest) { const int NUMBER_OF_ELEMENTS = 10000; std::vector<std::string> actual; mLListStr->insert(0, "42"); actual.insert(actual.begin(), "42"); for(int i = 1; i < NUMBER_OF_ELEMENTS; ++i) { int index = rand() % actual.size(); mLListStr->insert(index, std::to_string(i)); actual.insert(actual.begin() + index, std::to_string(i)); } for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { int index = rand() % actual.size(); mLListStr->set(index, std::to_string(i)); actual[index] = std::to_string(i); } for(unsigned int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { EXPECT_EQ(mLListStr->get(i), actual[i]); } EXPECT_EQ(mLListStr->size(), actual.size()); EXPECT_EQ(mLListStr->empty(), actual.empty()); for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { mLListStr->remove(0); actual.erase(actual.begin()); } mLListStr->insert(0, "42"); actual.insert(actual.begin(), "42"); for(int i = 1; i < NUMBER_OF_ELEMENTS; ++i) { int index = rand() % actual.size(); mLListStr->insert(index, std::to_string(i)); actual.insert(actual.begin() + index, std::to_string(i)); } for(int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { int index = rand() % actual.size(); mLListStr->set(index, std::to_string(i)); actual[index] = std::to_string(i); } for(unsigned int i = 0; i < NUMBER_OF_ELEMENTS; ++i) { EXPECT_EQ(mLListStr->get(i), actual[i]); } EXPECT_EQ(mLListStr->size(), actual.size()); EXPECT_EQ(mLListStr->empty(), actual.empty()); }
21.467866
75
0.672375
[ "vector" ]
ca7daf0faa70db96c8fc22efbabd025da797ef44
20,337
cc
C++
plugins/experimental/prefetch/fetch.cc
liangzhaorong/trafficserver
80d6440c1879d80d5f3dc0e3dcdc5de38d1e7ea1
[ "Apache-2.0" ]
2
2020-12-05T03:28:25.000Z
2021-07-10T06:03:57.000Z
plugins/experimental/prefetch/fetch.cc
liangzhaorong/trafficserver
80d6440c1879d80d5f3dc0e3dcdc5de38d1e7ea1
[ "Apache-2.0" ]
null
null
null
plugins/experimental/prefetch/fetch.cc
liangzhaorong/trafficserver
80d6440c1879d80d5f3dc0e3dcdc5de38d1e7ea1
[ "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. */ /** * @file bg_fetch.cpp * @brief Background fetch related classes (header file). */ #include <arpa/inet.h> #include <sys/types.h> #include <netinet/in.h> #include <netinet/ip.h> #include <string.h> #include <sys/socket.h> #include <inttypes.h> #include "ts/ts.h" /* ATS API */ #include "fetch.h" #include "headers.h" const char * getPrefetchMetricsNames(int metric) { switch (metric) { case FETCH_ACTIVE: return "fetch.active"; break; case FETCH_COMPLETED: return "fetch.completed"; break; case FETCH_ERRORS: return "fetch.errors"; break; case FETCH_TIMEOOUTS: return "fetch.timeouts"; break; case FETCH_THROTTLED: return "fetch.throttled"; break; case FETCH_ALREADY_CACHED: return "fetch.already_cached"; break; case FETCH_TOTAL: return "fetch.total"; break; case FETCH_UNIQUE_YES: return "fetch.unique.yes"; break; case FETCH_UNIQUE_NO: return "fetch.unique.no"; break; case FETCH_MATCH_YES: return "fetch.match.yes"; break; case FETCH_MATCH_NO: return "fetch.match.no"; break; case FETCH_POLICY_YES: return "fetch.policy.yes"; break; case FETCH_POLICY_NO: return "fetch.policy.no"; break; case FETCH_POLICY_SIZE: return "fetch.policy.size"; break; case FETCH_POLICY_MAXSIZE: return "fetch.policy.maxsize"; break; default: return "unknown"; break; } } static bool createStat(const String &prefix, const String &space, const char *module, const char *statName, TSRecordDataType statType, int &statId) { String name(prefix); name.append(".").append(space); if (nullptr != module) { name.append(".").append(module); } name.append(".").append(statName); if (TSStatFindName(name.c_str(), &statId) == TS_ERROR) { statId = TSStatCreate(name.c_str(), TS_RECORDDATATYPE_INT, TS_STAT_NON_PERSISTENT, TS_STAT_SYNC_SUM); if (statId == TS_ERROR) { PrefetchError("failed to register '%s'", name.c_str()); return false; } TSStatIntSet(statId, 0); } PrefetchDebug("created metric '%s (id:%d)'", name.c_str(), statId); return true; } BgFetchState::BgFetchState() : _policy(nullptr), _unique(nullptr), _concurrentFetches(0), _concurrentFetchesMax(0), _log(nullptr) { _policyLock = TSMutexCreate(); if (nullptr == _policyLock) { PrefetchError("failed to initialize lock"); } else { PrefetchDebug("initialized lock"); } _lock = TSMutexCreate(); if (nullptr == _lock) { PrefetchError("failed to initialize lock"); } else { PrefetchDebug("initialized lock"); } } BgFetchState::~BgFetchState() { TSMutexLock(_policyLock); delete _policy; TSMutexUnlock(_policyLock); TSMutexLock(_lock); delete _unique; TSMutexUnlock(_lock); TSMutexDestroy(_policyLock); TSMutexDestroy(_lock); TSTextLogObjectFlush(_log); TSTextLogObjectDestroy(_log); } static bool initializePolicy(FetchPolicy *&policy, const char *policyName) { bool status = true; if (nullptr == policy) { policy = FetchPolicy::getInstance(policyName); if (nullptr == policy) { PrefetchError("failed to initialize the %s policy", policyName); status = false; } } else { PrefetchDebug("state already initialized"); } return status; } bool initializeMetrics(PrefetchMetricInfo metrics[], const PrefetchConfig &config) { bool status = true; for (int i = FETCH_ACTIVE; i < FETCHES_MAX_METRICS; i++) { if (-1 == metrics[i].id) { status = createStat(config.getMetricsPrefix(), config.getNameSpace(), nullptr, getPrefetchMetricsNames(i), metrics[i].type, metrics[i].id); } else { PrefetchDebug("metric %s already initialized", getPrefetchMetricsNames(i)); } } return status; } bool initializeLog(TSTextLogObject &log, const PrefetchConfig &config) { bool status = true; if (!config.getLogName().empty()) { if (nullptr == log) { TSReturnCode error = TSTextLogObjectCreate(config.getLogName().c_str(), TS_LOG_MODE_ADD_TIMESTAMP, &log); if (error != TS_SUCCESS) { PrefetchError("failed to create log file"); status = false; } else { PrefetchDebug("initialized log file '%s'", config.getLogName().c_str()); } } else { PrefetchDebug("log file '%s' already initialized", config.getLogName().c_str()); } } else { PrefetchDebug("skip creating log file"); } return status; } bool BgFetchState::init(const PrefetchConfig &config) { int status = true; /* Is throttling configured, 0 - don't throttle */ _concurrentFetchesMax = config.getFetchMax(); /* Initialize the state */ TSMutexLock(_lock); /* Initialize 'simple' policy used to avoid concurrent fetches of the same object */ status &= initializePolicy(_unique, "simple"); /* Initialize the fetch metrics */ status &= initializeMetrics(_metrics, config); /* Initialize the "pre-fetch" log */ status &= initializeLog(_log, config); TSMutexUnlock(_lock); /* Initialize fetching policy */ TSMutexLock(_policyLock); if (!config.getFetchPolicy().empty() && 0 != config.getFetchPolicy().compare("simple")) { status &= initializePolicy(_policy, config.getFetchPolicy().c_str()); if (nullptr != _policy) { setMetric(FETCH_POLICY_MAXSIZE, _policy->getMaxSize()); } } else { PrefetchDebug("Policy not specified or 'simple' policy chosen (skipping)"); } TSMutexUnlock(_policyLock); return status; } bool BgFetchState::acquire(const String &url) { bool permitted = true; if (nullptr != _policy) { TSMutexLock(_policyLock); permitted = _policy->acquire(url); TSMutexUnlock(_policyLock); } if (permitted) { incrementMetric(FETCH_POLICY_YES); } else { incrementMetric(FETCH_POLICY_NO); } if (nullptr != _policy) { setMetric(FETCH_POLICY_SIZE, _policy->getSize()); } return permitted; } bool BgFetchState::release(const String &url) { bool ret = true; if (nullptr != _policy) { TSMutexLock(_policyLock); ret &= _policy->release(url); TSMutexUnlock(_policyLock); } if (nullptr != _policy) { setMetric(FETCH_POLICY_SIZE, _policy->getSize()); } return ret; } bool BgFetchState::uniqueAcquire(const String &url) { bool permitted = true; bool throttled = false; size_t cachedCounter = 0; TSMutexLock(_lock); if (0 == _concurrentFetchesMax || _concurrentFetches < _concurrentFetchesMax) { permitted = _unique->acquire(url); if (permitted) { cachedCounter = ++_concurrentFetches; } } else { throttled = true; } TSMutexUnlock(_lock); /* Update the metrics, no need to lock? */ if (throttled) { incrementMetric(FETCH_THROTTLED); } if (permitted && !throttled) { incrementMetric(FETCH_UNIQUE_YES); incrementMetric(FETCH_TOTAL); setMetric(FETCH_ACTIVE, cachedCounter); } else { incrementMetric(FETCH_UNIQUE_NO); } return permitted; } bool BgFetchState::uniqueRelease(const String &url) { bool permitted = true; ssize_t cachedCounter = 0; TSMutexLock(_lock); cachedCounter = --_concurrentFetches; permitted = _unique->release(url); TSMutexUnlock(_lock); TSAssert(cachedCounter < 0); /* Update the metrics, no need to lock? */ if (permitted) { setMetric(FETCH_ACTIVE, cachedCounter); } return permitted; } void BgFetchState::incrementMetric(PrefetchMetric m) { if (-1 != _metrics[m].id) { TSStatIntIncrement(_metrics[m].id, 1); } } void BgFetchState::setMetric(PrefetchMetric m, size_t value) { if (-1 != _metrics[m].id) { TSStatIntSet(_metrics[m].id, value); } } inline TSTextLogObject BgFetchState::getLog() { return _log; } BgFetchStates *BgFetchStates::_prefetchStates = nullptr; BgFetch::BgFetch(BgFetchState *state, const PrefetchConfig &config, bool lock) : _headerLoc(TS_NULL_MLOC), _urlLoc(TS_NULL_MLOC), vc(nullptr), req_io_buf(nullptr), resp_io_buf(nullptr), req_io_buf_reader(nullptr), resp_io_buf_reader(nullptr), r_vio(nullptr), w_vio(nullptr), _bytes(0), _cont(nullptr), _state(state), _config(config), _askPermission(lock), _startTime(0) { _mbuf = TSMBufferCreate(); memset(&client_ip, 0, sizeof(client_ip)); } BgFetch::~BgFetch() { TSHandleMLocRelease(_mbuf, TS_NULL_MLOC, _headerLoc); TSHandleMLocRelease(_mbuf, TS_NULL_MLOC, _urlLoc); TSMBufferDestroy(_mbuf); if (vc) { PrefetchError("Destroyed BgFetch while VC was alive"); TSVConnClose(vc); vc = nullptr; } if (nullptr != _cont) { if (_askPermission) { _state->release(_cachekey); _state->uniqueRelease(_cachekey); } TSContDestroy(_cont); _cont = nullptr; TSIOBufferReaderFree(req_io_buf_reader); TSIOBufferDestroy(req_io_buf); TSIOBufferReaderFree(resp_io_buf_reader); TSIOBufferDestroy(resp_io_buf); } } bool BgFetch::schedule(BgFetchState *state, const PrefetchConfig &config, bool askPermission, TSMBuffer requestBuffer, TSMLoc requestHeaderLoc, TSHttpTxn txnp, const char *path, size_t pathLen, const String &cachekey) { bool ret = false; BgFetch *fetch = new BgFetch(state, config, askPermission); if (fetch->init(requestBuffer, requestHeaderLoc, txnp, path, pathLen, cachekey)) { fetch->schedule(); ret = true; } else { delete fetch; } return ret; } bool BgFetch::saveIp(TSHttpTxn txnp) { struct sockaddr const *ip = TSHttpTxnClientAddrGet(txnp); if (ip) { if (ip->sa_family == AF_INET) { memcpy(&client_ip, ip, sizeof(sockaddr_in)); } else if (ip->sa_family == AF_INET6) { memcpy(&client_ip, ip, sizeof(sockaddr_in6)); } else { PrefetchError("unknown address family %d", ip->sa_family); } } else { PrefetchError("failed to get client host info"); return false; } return true; } inline void BgFetch::addBytes(int64_t b) { _bytes += b; } /** * Initialize the background fetch */ bool BgFetch::init(TSMBuffer reqBuffer, TSMLoc reqHdrLoc, TSHttpTxn txnp, const char *fetchPath, size_t fetchPathLen, const String &cachekey) { TSAssert(TS_NULL_MLOC == _headerLoc); TSAssert(TS_NULL_MLOC == _urlLoc); if (_askPermission) { if (!_state->acquire(cachekey)) { PrefetchDebug("request is not fetchable"); return false; } if (!_state->uniqueAcquire(cachekey)) { PrefetchDebug("already fetching the object"); _state->release(cachekey); return false; } } _cachekey.assign(cachekey); /* Save the IP info */ if (!saveIp(txnp)) { return false; } /* Create HTTP header */ _headerLoc = TSHttpHdrCreate(_mbuf); /* Copy the headers to the new marshal buffer */ if (TS_SUCCESS != TSHttpHdrCopy(_mbuf, _headerLoc, reqBuffer, reqHdrLoc)) { PrefetchError("header copy failed"); } /* Copy the pristine request URL into fetch marshal buffer */ TSMLoc pristineUrlLoc; if (TS_SUCCESS == TSHttpTxnPristineUrlGet(txnp, &reqBuffer, &pristineUrlLoc)) { if (TS_SUCCESS != TSUrlClone(_mbuf, reqBuffer, pristineUrlLoc, &_urlLoc)) { PrefetchError("failed to clone URL"); TSHandleMLocRelease(reqBuffer, TS_NULL_MLOC, pristineUrlLoc); return false; } TSHandleMLocRelease(reqBuffer, TS_NULL_MLOC, pristineUrlLoc); } else { PrefetchError("failed to get pristine URL"); return false; } /* Save the path before changing */ int pathLen; const char *path = TSUrlPathGet(_mbuf, _urlLoc, &pathLen); if (nullptr == path) { PrefetchError("failed to get a URL path"); return false; } /* Now set or remove the prefetch API header */ const String &header = _config.getApiHeader(); if (_config.isFront()) { if (setHeader(_mbuf, _headerLoc, header.c_str(), (int)header.length(), path, pathLen)) { PrefetchDebug("set header '%.*s: %.*s'", (int)header.length(), header.c_str(), (int)fetchPathLen, fetchPath); } } else { if (removeHeader(_mbuf, _headerLoc, header.c_str(), header.length())) { PrefetchDebug("remove header '%.*s'", (int)header.length(), header.c_str()); } } /* Make sure we remove the RANGE header to avoid 416 "Request Range Not Satisfiable" response when * the current request is a RANGE request and its range turns out invalid for the "next" object */ if (removeHeader(_mbuf, _headerLoc, TS_MIME_FIELD_RANGE, TS_MIME_LEN_RANGE)) { PrefetchDebug("remove header '%.*s'", TS_MIME_LEN_RANGE, TS_MIME_FIELD_RANGE); } /* Overwrite the path if required */ if (nullptr != fetchPath && 0 != fetchPathLen) { if (TS_SUCCESS == TSUrlPathSet(_mbuf, _urlLoc, fetchPath, fetchPathLen)) { PrefetchDebug("setting URL path to %.*s", (int)fetchPathLen, fetchPath); } else { PrefetchError("failed to set a URL path %.*s", (int)fetchPathLen, fetchPath); } } /* Come up with the host name to be used in the fetch request */ const char *hostName = nullptr; int hostNameLen = 0; if (_config.getReplaceHost().empty()) { hostName = TSUrlHostGet(_mbuf, _urlLoc, &hostNameLen); } else { hostName = _config.getReplaceHost().c_str(); hostNameLen = _config.getReplaceHost().length(); } /* Set the URI host */ if (TS_SUCCESS == TSUrlHostSet(_mbuf, _urlLoc, hostName, hostNameLen)) { PrefetchDebug("setting URL host: %.*s", hostNameLen, hostName); } else { PrefetchError("failed to set URL host: %.*s", hostNameLen, hostName); } /* Set the host header */ if (setHeader(_mbuf, _headerLoc, TS_MIME_FIELD_HOST, TS_MIME_LEN_HOST, hostName, hostNameLen)) { PrefetchDebug("setting Host header: %.*s", hostNameLen, hostName); } else { PrefetchError("failed to set Host header: %.*s", hostNameLen, hostName); } /* Save the URL to be fetched with this fetch for debugging purposes, expensive TSUrlStringGet() * but really helpful when debugging multi-remap / host-replacement use cases */ int urlLen = 0; char *url = TSUrlStringGet(_mbuf, _urlLoc, &urlLen); if (nullptr != url) { _url.assign(url, urlLen); TSfree(static_cast<void *>(url)); } /* TODO: TBD is this the right place? */ if (TS_SUCCESS != TSHttpHdrUrlSet(_mbuf, _headerLoc, _urlLoc)) { return false; } /* Initialization is success */ return true; } /** * @brief Create, setup and schedule the background fetch continuation. */ void BgFetch::schedule() { TSAssert(nullptr == _cont); /* Setup the continuation */ _cont = TSContCreate(handler, TSMutexCreate()); TSContDataSet(_cont, static_cast<void *>(this)); /* Initialize the VIO (for the fetch) */ req_io_buf = TSIOBufferCreate(); req_io_buf_reader = TSIOBufferReaderAlloc(req_io_buf); resp_io_buf = TSIOBufferCreate(); resp_io_buf_reader = TSIOBufferReaderAlloc(resp_io_buf); /* Schedule */ PrefetchDebug("schedule fetch: %s", _url.c_str()); _startTime = TShrtime(); TSContSchedule(_cont, 0, TS_THREAD_POOL_NET); } /* Log format is: name-space bytes status url */ void BgFetch::logAndMetricUpdate(TSEvent event) const { const char *status; switch (event) { case TS_EVENT_VCONN_EOS: status = "EOS"; _state->incrementMetric(FETCH_COMPLETED); break; case TS_EVENT_VCONN_INACTIVITY_TIMEOUT: status = "TIMEOUT"; _state->incrementMetric(FETCH_TIMEOOUTS); break; case TS_EVENT_ERROR: _state->incrementMetric(FETCH_ERRORS); status = "ERROR"; break; case TS_EVENT_VCONN_READ_COMPLETE: _state->incrementMetric(FETCH_COMPLETED); status = "READ_COMP"; break; default: status = "UNKNOWN"; break; } if (TSIsDebugTagSet(PLUGIN_NAME "_log")) { TSHRTime now = TShrtime(); double elapsed = (double)(now - _startTime) / 1000000.0; PrefetchDebug("ns=%s bytes=%" PRId64 " time=%1.3lf status=%s url=%s key=%s", _config.getNameSpace().c_str(), _bytes, elapsed, status, _url.c_str(), _cachekey.c_str()); if (_state->getLog()) { TSTextLogObjectWrite(_state->getLog(), "ns=%s bytes=%" PRId64 " time=%1.3lf status=%s url=%s key=%s", _config.getNameSpace().c_str(), _bytes, elapsed, status, _url.c_str(), _cachekey.c_str()); } } } /** * @brief Continuation to perform a background fill of a URL. * * This is pretty expensive (memory allocations etc.) */ int BgFetch::handler(TSCont contp, TSEvent event, void * /* edata ATS_UNUSED */) { BgFetch *fetch = static_cast<BgFetch *>(TSContDataGet(contp)); int64_t avail; PrefetchDebug("event: %s (%d)", TSHttpEventNameLookup(event), event); switch (event) { case TS_EVENT_IMMEDIATE: case TS_EVENT_TIMEOUT: // Debug info for this particular bg fetch (put all debug in here please) if (TSIsDebugTagSet(PLUGIN_NAME)) { char buf[INET6_ADDRSTRLEN]; const sockaddr *sockaddress = (const sockaddr *)&fetch->client_ip; switch (sockaddress->sa_family) { case AF_INET: inet_ntop(AF_INET, &(((struct sockaddr_in *)sockaddress)->sin_addr), buf, INET_ADDRSTRLEN); PrefetchDebug("client IPv4 = %s", buf); break; case AF_INET6: inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sockaddress)->sin6_addr), buf, INET6_ADDRSTRLEN); PrefetchDebug("client IPv6 = %s", buf); break; default: TSError("[%s] Unknown address family %d", PLUGIN_NAME, sockaddress->sa_family); break; } PrefetchDebug("Starting background fetch."); dumpHeaders(fetch->_mbuf, fetch->_headerLoc); } // Setup the NetVC for background fetch TSAssert(nullptr == fetch->vc); if ((fetch->vc = TSHttpConnect((sockaddr *)&fetch->client_ip)) != nullptr) { TSHttpHdrPrint(fetch->_mbuf, fetch->_headerLoc, fetch->req_io_buf); // We never send a body with the request. ToDo: Do we ever need to support that ? TSIOBufferWrite(fetch->req_io_buf, "\r\n", 2); fetch->r_vio = TSVConnRead(fetch->vc, contp, fetch->resp_io_buf, INT64_MAX); fetch->w_vio = TSVConnWrite(fetch->vc, contp, fetch->req_io_buf_reader, TSIOBufferReaderAvail(fetch->req_io_buf_reader)); } else { delete fetch; PrefetchError("Failed to connect to internal process, major malfunction"); } break; case TS_EVENT_VCONN_WRITE_COMPLETE: // TSVConnShutdown(data->vc, 0, 1); // TSVIOReenable(data->w_vio); PrefetchDebug("write complete"); break; case TS_EVENT_VCONN_READ_READY: avail = TSIOBufferReaderAvail(fetch->resp_io_buf_reader); fetch->addBytes(avail); TSIOBufferReaderConsume(fetch->resp_io_buf_reader, avail); TSVIONDoneSet(fetch->r_vio, TSVIONDoneGet(fetch->r_vio) + avail); TSVIOReenable(fetch->r_vio); break; case TS_EVENT_VCONN_READ_COMPLETE: case TS_EVENT_VCONN_EOS: case TS_EVENT_VCONN_INACTIVITY_TIMEOUT: case TS_EVENT_ERROR: if (event == TS_EVENT_VCONN_INACTIVITY_TIMEOUT) { PrefetchDebug("encountered Inactivity Timeout"); TSVConnAbort(fetch->vc, TS_VC_CLOSE_ABORT); } else { TSVConnClose(fetch->vc); } PrefetchDebug("closing background transaction"); avail = TSIOBufferReaderAvail(fetch->resp_io_buf_reader); fetch->addBytes(avail); TSIOBufferReaderConsume(fetch->resp_io_buf_reader, avail); TSVIONDoneSet(fetch->r_vio, TSVIONDoneGet(fetch->r_vio) + avail); fetch->logAndMetricUpdate(event); /* Close, release and cleanup */ fetch->vc = nullptr; delete fetch; break; default: PrefetchDebug("unhandled event"); break; } return 0; }
27.482432
129
0.679648
[ "object" ]
ca8124657789b76f13d89464a4cdb2d4abfa0739
3,119
cpp
C++
src/GameEngineClasses/Game.cpp
dmariaa/game-engine
b26a58b7cdfcabbb6952f5df62248a8e9ce3476c
[ "MIT" ]
null
null
null
src/GameEngineClasses/Game.cpp
dmariaa/game-engine
b26a58b7cdfcabbb6952f5df62248a8e9ce3476c
[ "MIT" ]
null
null
null
src/GameEngineClasses/Game.cpp
dmariaa/game-engine
b26a58b7cdfcabbb6952f5df62248a8e9ce3476c
[ "MIT" ]
null
null
null
// // Game.cpp // src // // Created by David María Arribas on 17/10/17. // Copyright © 2017 David María Arribas. All rights reserved. // #include "Game.hpp" Game* Game::gameInstance = 0; Game::Game() : scene(new Scene()), keyboardHandler(new InputHandler()) {} void Game::init(int argc, char** argv) { gameInstance = this; lastUpdateTime = 0; initGlut(argc, argv); } void Game::start() { glutMainLoop(); } Scene* Game::getScene() { return this->scene; } InputHandler* Game::getInputHandler() { return this->keyboardHandler; } void Game::initScene(void (*initSceneCallback)(Scene *)) { scene->initScene(initSceneCallback); } void Game::initGlut(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); // glutInitWindowSize(800,600); // glutInitWindowPosition(100,100); windowId = glutCreateWindow("Hello wold :D"); glutFullScreen(); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glClearColor(0.0,0.0,0.0,0.0); glutDisplayFunc(display); glutIdleFunc(idle); glutReshapeFunc(reshape); glutKeyboardFunc(keyPressed); glutKeyboardUpFunc(keyReleased); glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF); glutMouseFunc(mouseClick); glutMotionFunc(mouseMove); } void Game::_display() { scene->render(); glFlush(); glutSwapBuffers(); } void Game::_keyPressed(unsigned char key,int x,int y) { this->keyboardHandler->keyPressed(key, x, y); } void Game::_keyReleased(unsigned char key,int x,int y) { this->keyboardHandler->keyReleased(key, x, y); } void Game::_mouseClick(int button, int state, int x, int y) { this->keyboardHandler->mouseClick(button, state, x, y); } void Game::_mouseMove(int x, int y) { this->keyboardHandler->mouseMove(x, y); } void Game::_idle() { if(lastUpdateTime==0) { lastUpdateTime = glutGet(GLUT_ELAPSED_TIME); return; } double currentTime = glutGet(GLUT_ELAPSED_TIME); float dt = float((currentTime - lastUpdateTime) / 1000.0f); lastUpdateTime = currentTime; scene->update(dt); glutPostRedisplay(); } void Game::_reshape(int width, int height) { glViewport(0 , 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f,(GLfloat)width/(GLfloat)height,1.0f,200.0f); glMatrixMode(GL_MODELVIEW); } void Game::setInstance(Game* instance){ gameInstance = instance; } void Game::display() { gameInstance->_display(); } void Game::idle() { gameInstance->_idle(); } void Game::reshape(int width, int height) { gameInstance->_reshape(width, height); } void Game::keyPressed(unsigned char key, int x, int y) { gameInstance->_keyPressed(key, x, y); } void Game::keyReleased(unsigned char key, int x, int y) { gameInstance->_keyReleased(key, x, y); } void Game::mouseMove(int x, int y) { gameInstance->_mouseMove(x, y); } void Game::mouseClick(int button, int state, int x, int y) { gameInstance->_mouseClick(button, state, x, y); }
22.601449
73
0.675216
[ "render" ]
ca83e1c595d1adf316b8324af9eef4056ac06e0e
6,052
cpp
C++
interface/src/ui/overlays/TextOverlay.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
interface/src/ui/overlays/TextOverlay.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
interface/src/ui/overlays/TextOverlay.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
// // TextOverlay.cpp // interface/src/ui/overlays // // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" #include <QGLWidget> #include <DependencyManager.h> #include <GeometryCache.h> #include <SharedUtil.h> #include <TextRenderer.h> #include "TextOverlay.h" TextOverlay::TextOverlay() : _backgroundColor(DEFAULT_BACKGROUND_COLOR), _backgroundAlpha(DEFAULT_BACKGROUND_ALPHA), _leftMargin(DEFAULT_MARGIN), _topMargin(DEFAULT_MARGIN), _fontSize(DEFAULT_FONTSIZE) { } TextOverlay::TextOverlay(const TextOverlay* textOverlay) : Overlay2D(textOverlay), _text(textOverlay->_text), _backgroundColor(textOverlay->_backgroundColor), _backgroundAlpha(textOverlay->_backgroundAlpha), _leftMargin(textOverlay->_leftMargin), _topMargin(textOverlay->_topMargin), _fontSize(textOverlay->_fontSize) { } TextOverlay::~TextOverlay() { } xColor TextOverlay::getBackgroundColor() { if (_colorPulse == 0.0f) { return _backgroundColor; } float pulseLevel = updatePulse(); xColor result = _backgroundColor; if (_colorPulse < 0.0f) { result.red *= (1.0f - pulseLevel); result.green *= (1.0f - pulseLevel); result.blue *= (1.0f - pulseLevel); } else { result.red *= pulseLevel; result.green *= pulseLevel; result.blue *= pulseLevel; } return result; } void TextOverlay::render(RenderArgs* args) { if (!_visible) { return; // do nothing if we're not visible } const float MAX_COLOR = 255.0f; xColor backgroundColor = getBackgroundColor(); glColor4f(backgroundColor.red / MAX_COLOR, backgroundColor.green / MAX_COLOR, backgroundColor.blue / MAX_COLOR, getBackgroundAlpha()); int left = _bounds.left(); int right = _bounds.right() + 1; int top = _bounds.top(); int bottom = _bounds.bottom() + 1; glm::vec2 topLeft(left, top); glm::vec2 bottomRight(right, bottom); DependencyManager::get<GeometryCache>()->renderQuad(topLeft, bottomRight); // Same font properties as textSize() TextRenderer* textRenderer = TextRenderer::getInstance(SANS_FONT_FAMILY, _fontSize, DEFAULT_FONT_WEIGHT); const int leftAdjust = -1; // required to make text render relative to left edge of bounds const int topAdjust = -2; // required to make text render relative to top edge of bounds int x = _bounds.left() + _leftMargin + leftAdjust; int y = _bounds.top() + _topMargin + topAdjust; glColor3f(_color.red / MAX_COLOR, _color.green / MAX_COLOR, _color.blue / MAX_COLOR); float alpha = getAlpha(); QStringList lines = _text.split("\n"); int lineOffset = 0; foreach(QString thisLine, lines) { if (lineOffset == 0) { lineOffset = textRenderer->calculateHeight(qPrintable(thisLine)); } lineOffset += textRenderer->draw(x, y + lineOffset, qPrintable(thisLine), alpha); const int lineGap = 2; lineOffset += lineGap; } } void TextOverlay::setProperties(const QScriptValue& properties) { Overlay2D::setProperties(properties); QScriptValue font = properties.property("font"); if (font.isObject()) { if (font.property("size").isValid()) { setFontSize(font.property("size").toInt32()); } } QScriptValue text = properties.property("text"); if (text.isValid()) { setText(text.toVariant().toString()); } QScriptValue backgroundColor = properties.property("backgroundColor"); if (backgroundColor.isValid()) { QScriptValue red = backgroundColor.property("red"); QScriptValue green = backgroundColor.property("green"); QScriptValue blue = backgroundColor.property("blue"); if (red.isValid() && green.isValid() && blue.isValid()) { _backgroundColor.red = red.toVariant().toInt(); _backgroundColor.green = green.toVariant().toInt(); _backgroundColor.blue = blue.toVariant().toInt(); } } if (properties.property("backgroundAlpha").isValid()) { _backgroundAlpha = properties.property("backgroundAlpha").toVariant().toFloat(); } if (properties.property("leftMargin").isValid()) { setLeftMargin(properties.property("leftMargin").toVariant().toInt()); } if (properties.property("topMargin").isValid()) { setTopMargin(properties.property("topMargin").toVariant().toInt()); } } TextOverlay* TextOverlay::createClone() const { return new TextOverlay(this); } QScriptValue TextOverlay::getProperty(const QString& property) { if (property == "font") { QScriptValue font = _scriptEngine->newObject(); font.setProperty("size", _fontSize); return font; } if (property == "text") { return _text; } if (property == "backgroundColor") { return xColorToScriptValue(_scriptEngine, _backgroundColor); } if (property == "backgroundAlpha") { return _backgroundAlpha; } if (property == "leftMargin") { return _leftMargin; } if (property == "topMargin") { return _topMargin; } return Overlay2D::getProperty(property); } QSizeF TextOverlay::textSize(const QString& text) const { QFont font(SANS_FONT_FAMILY, _fontSize, DEFAULT_FONT_WEIGHT); // Same font properties as render() QFontMetrics fontMetrics(font); const int TEXT_HEIGHT_ADJUST = -2; // Experimentally determined for the specified font QStringList lines = text.split(QRegExp("\r\n|\r|\n")); int width = 0; for (int i = 0; i < lines.count(); i += 1) { width = std::max(width, fontMetrics.width(qPrintable(lines[i]))); } int height = lines.count() * (fontMetrics.height() + TEXT_HEIGHT_ADJUST); return QSizeF(width, height); }
31.195876
116
0.663087
[ "render" ]
ca8c308506a8089e1db9886bd4d34bb20fe00138
1,624
cpp
C++
src/test-apps/fuzz/FuzzUtils.cpp
aiw-google/openweave-core
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
[ "Apache-2.0" ]
249
2017-09-18T17:48:34.000Z
2022-02-02T06:46:21.000Z
src/test-apps/fuzz/FuzzUtils.cpp
aiw-google/openweave-core
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
[ "Apache-2.0" ]
501
2017-11-10T11:25:32.000Z
2022-02-01T10:43:13.000Z
src/test-apps/fuzz/FuzzUtils.cpp
aiw-google/openweave-core
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
[ "Apache-2.0" ]
116
2017-09-20T07:06:55.000Z
2022-01-08T13:41:15.000Z
/* * * Copyright (c) 2018 Google LLC. * Copyright (c) 2013-2017 Nest Labs, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * This file implements a set of utilities for fuzzing tests */ #include "FuzzUtils.h" #include <stdio.h> #include <vector> #include "FuzzUtils.h" #include "ToolCommon.h" #include <Weave/Support/ErrorStr.h> #include <Weave/Profiles/security/WeaveSecurity.h> #include <Weave/Profiles/security/WeavePASE.h> #include <Weave/Support/RandUtils.h> using namespace nl::Weave::Profiles::Security; using namespace nl::Weave::Profiles::Security::PASE; using System::PacketBuffer; void saveCorpus(const uint8_t *inBuf, size_t size, char *fileName) { //Todo create better method of creating these. FILE* file = fopen(fileName, "wb+" ); fwrite(inBuf, 1, size, file ); fclose(file); } void printCorpus(const uint8_t *inBuf, size_t size) { for (size_t i = 0; i < size; i++) { if (i % 12 == 0) { printf("\n"); } printf("0x%02X, ", inBuf[i]); } printf("\n"); }
29
78
0.672414
[ "vector" ]
ca8e6c177f0eeb9bc347f1b86dadde29b28714ee
21,769
cpp
C++
Marlin/src/lcd/e3v2/marlinui/ui_common.cpp
violigon/3DPrinter-DE2LV
5c8960f07085cc11d232a52cb029aa92533287bd
[ "MIT" ]
null
null
null
Marlin/src/lcd/e3v2/marlinui/ui_common.cpp
violigon/3DPrinter-DE2LV
5c8960f07085cc11d232a52cb029aa92533287bd
[ "MIT" ]
null
null
null
Marlin/src/lcd/e3v2/marlinui/ui_common.cpp
violigon/3DPrinter-DE2LV
5c8960f07085cc11d232a52cb029aa92533287bd
[ "MIT" ]
null
null
null
/** * Marlin 3D Printer Firmware * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../../inc/MarlinConfigPre.h" #if IS_DWIN_MARLINUI #include "marlinui_dwin.h" #include "dwin_lcd.h" #include "dwin_string.h" //#include "../../lcdprint.h" #include "lcdprint_dwin.h" #include "../../fontutils.h" #include "../../../libs/numtostr.h" #include "../../marlinui.h" #include "../../../sd/cardreader.h" #include "../../../module/motion.h" #include "../../../module/temperature.h" #include "../../../module/printcounter.h" #if ENABLED(SDSUPPORT) #include "../../../libs/duration_t.h" #endif #if ENABLED(AUTO_BED_LEVELING_UBL) #include "../../../feature/bedlevel/bedlevel.h" #endif // DWIN printing specifies the font on each string operation // but we'll make the font modal for Marlin dwin_font_t dwin_font = { font8x16, 8, 16, Color_White, Color_Bg_Black, true }; void MarlinUI::set_font(const uint8_t font_nr) { if (font_nr != dwin_font.index) { dwin_font.index = font_nr; uint8_t w, h; switch (font_nr) { default: case font6x12: w = 6; h = 12; break; case font8x16: w = 8; h = 16; break; case font10x20: w = 10; h = 20; break; case font12x24: w = 12; h = 24; break; case font14x28: w = 14; h = 28; break; case font16x32: w = 16; h = 32; break; case font20x40: w = 20; h = 40; break; case font24x48: w = 24; h = 48; break; case font28x56: w = 28; h = 56; break; case font32x64: w = 32; h = 64; break; } dwin_font.width = w; dwin_font.height = h; // TODO: Array with dimensions, auto fit menu items, // update char width / height of the screen based on // new (fixed-width) font size. } } // This display is always detected bool MarlinUI::detected() { return true; } // Initialize or re-initialize the LCD void MarlinUI::init_lcd() { DWIN_Startup(); // Load the assets JPG (currently just the status screen 'icon') DWIN_JPG_CacheTo1(DWIN_MarlinUI_Assets); } // This LCD should clear where it will draw anew void MarlinUI::clear_lcd() { DWIN_ICON_AnimationControl(0x0000); // disable all icon animations DWIN_Frame_Clear(Color_Bg_Black); DWIN_UpdateLCD(); did_first_redraw = false; } #if ENABLED(SHOW_BOOTSCREEN) void MarlinUI::show_bootscreen() { clear_lcd(); dwin_string.set(F(SHORT_BUILD_VERSION)); #if ENABLED(DWIN_MARLINUI_PORTRAIT) #define LOGO_CENTER ((LCD_PIXEL_WIDTH) / 2) #define INFO_CENTER LOGO_CENTER #define VERSION_Y 330 DWIN_ICON_Show(BOOT_ICON, ICON_MarlinBoot, LOGO_CENTER - 266 / 2, 15); DWIN_ICON_Show(BOOT_ICON, ICON_OpenSource, LOGO_CENTER - 174 / 2, 280); DWIN_ICON_Show(BOOT_ICON, ICON_GitHubURL, LOGO_CENTER - 180 / 2, 420); DWIN_ICON_Show(BOOT_ICON, ICON_MarlinURL, LOGO_CENTER - 100 / 2, 440); DWIN_ICON_Show(BOOT_ICON, ICON_Copyright, LOGO_CENTER - 126 / 2, 460); #else #define LOGO_CENTER (280 / 2) #define INFO_CENTER ((LCD_PIXEL_WIDTH) - 200 / 2) #define VERSION_Y 84 DWIN_ICON_Show(BOOT_ICON, ICON_MarlinBoot, LOGO_CENTER - 266 / 2, 15); DWIN_ICON_Show(BOOT_ICON, ICON_OpenSource, INFO_CENTER - 174 / 2, 60); DWIN_ICON_Show(BOOT_ICON, ICON_GitHubURL, INFO_CENTER - 180 / 2, 130); DWIN_ICON_Show(BOOT_ICON, ICON_MarlinURL, INFO_CENTER - 100 / 2, 152); DWIN_ICON_Show(BOOT_ICON, ICON_Copyright, INFO_CENTER - 126 / 2, 200); #endif DWIN_Draw_String(false, font10x20, Color_Yellow, Color_Bg_Black, INFO_CENTER - (dwin_string.length() * 10) / 2, VERSION_Y, S(dwin_string.string())); DWIN_UpdateLCD(); } void MarlinUI::bootscreen_completion(const millis_t sofar) { if ((BOOTSCREEN_TIMEOUT) > sofar) safe_delay((BOOTSCREEN_TIMEOUT) - sofar); clear_lcd(); } #endif // The kill screen is displayed for unrecoverable conditions void MarlinUI::draw_kill_screen() { set_font(DWIN_FONT_ALERT); DWIN_Frame_Clear(Color_Bg_Black); dwin_font.fg = Color_Error_Red; dwin_font.solid = false; DWIN_Draw_Rectangle(1, Color_Bg_Window, 20, 20, LCD_PIXEL_WIDTH - 20, LCD_PIXEL_HEIGHT - 20); // make the frame a few pixels thick DWIN_Draw_Rectangle(0, Color_Yellow, 20, 20, LCD_PIXEL_WIDTH - 20, LCD_PIXEL_HEIGHT - 20); DWIN_Draw_Rectangle(0, Color_Yellow, 21, 21, LCD_PIXEL_WIDTH - 21, LCD_PIXEL_HEIGHT - 21); DWIN_Draw_Rectangle(0, Color_Yellow, 22, 22, LCD_PIXEL_WIDTH - 22, LCD_PIXEL_HEIGHT - 22); uint8_t cx = (LCD_PIXEL_WIDTH / dwin_font.width / 2), cy = (LCD_PIXEL_HEIGHT / dwin_font.height / 2); #if ENABLED(DWIN_MARLINUI_LANDSCAPE) cx += (96 / 2 / dwin_font.width); DWIN_ICON_Show(ICON, ICON_Halted, 40, (LCD_PIXEL_HEIGHT - 96) / 2); #else DWIN_ICON_Show(ICON, ICON_Halted, (LCD_PIXEL_WIDTH - 96) / 2, 40); #endif uint8_t slen = utf8_strlen(status_message); lcd_moveto(cx - (slen / 2), cy - 1); lcd_put_u8str(status_message); slen = utf8_strlen(S(GET_TEXT_F(MSG_HALTED))); lcd_moveto(cx - (slen / 2), cy); lcd_put_u8str_P((const char*)GET_TEXT_F(MSG_HALTED)); slen = utf8_strlen(S(GET_TEXT_F(MSG_HALTED))); lcd_moveto(cx - (slen / 2), cy + 1); lcd_put_u8str_P((const char*)GET_TEXT_F(MSG_HALTED)); } // // Status Message // void MarlinUI::draw_status_message(const bool blink) { set_font(DWIN_FONT_STAT); dwin_font.solid = true; dwin_font.fg = Color_White; dwin_font.bg = Color_Bg_Black; lcd_moveto_xy(0, LCD_PIXEL_HEIGHT - (STAT_FONT_HEIGHT) - 1); constexpr uint8_t max_status_chars = (LCD_PIXEL_WIDTH) / (STAT_FONT_WIDTH); auto status_changed = []{ static uint16_t old_hash = 0x0000; uint16_t hash = 0x0000; for (uint8_t i = 0; i < MAX_MESSAGE_LENGTH; i++) { const char c = ui.status_message[i]; if (!c) break; hash = ((hash << 1) | (hash >> 15)) ^ c; } const bool hash_changed = hash != old_hash; old_hash = hash; return hash_changed || !ui.did_first_redraw; }; #if ENABLED(STATUS_MESSAGE_SCROLLING) static bool last_blink = false; // Get the UTF8 character count of the string uint8_t slen = utf8_strlen(status_message); // If the string fits into the LCD, just print it and do not scroll it if (slen <= max_status_chars) { if (status_changed()) { // The string isn't scrolling and may not fill the screen lcd_put_u8str(status_message); // Fill the rest with spaces while (slen < max_status_chars) { lcd_put_wchar(' '); ++slen; } } } else { // String is larger than the available line space // Get a pointer to the next valid UTF8 character // and the string remaining length uint8_t rlen; const char *stat = status_and_len(rlen); lcd_put_u8str_max(stat, max_status_chars); // If the string doesn't completely fill the line... if (rlen < max_status_chars) { lcd_put_wchar('.'); // Always at 1+ spaces left, draw a dot uint8_t chars = max_status_chars - rlen; // Amount of space left in characters if (--chars) { // Draw a second dot if there's space lcd_put_wchar('.'); if (--chars) lcd_put_u8str_max(status_message, chars); // Print a second copy of the message } } if (last_blink != blink) { last_blink = blink; advance_status_scroll(); } } #else UNUSED(blink); if (status_changed()) { // Get the UTF8 character count of the string uint8_t slen = utf8_strlen(status_message); // Just print the string to the LCD lcd_put_u8str_max(status_message, max_status_chars); // Fill the rest with spaces if there are missing spaces while (slen < max_status_chars) { lcd_put_wchar(' '); ++slen; } } #endif } #if HAS_LCD_BRIGHTNESS void MarlinUI::_set_brightness() { DWIN_LCD_Brightness(backlight ? brightness : 0); } #endif #if HAS_LCD_MENU #include "../../menu/menu.h" #if ENABLED(ADVANCED_PAUSE_FEATURE) void MarlinUI::draw_hotend_status(const uint8_t row, const uint8_t extruder) { dwin_font.solid = false; dwin_font.fg = Color_White; dwin_string.set("E"); dwin_string.add('1' + extruder); dwin_string.add(' '); dwin_string.add(i16tostr3rj(thermalManager.degHotend(extruder))); dwin_string.add('/'); if (get_blink() || !thermalManager.heater_idle[thermalManager.idle_index_for_id(extruder)].timed_out) dwin_string.add(i16tostr3rj(thermalManager.degTargetHotend(extruder))); else dwin_string.add(PSTR(" ")); lcd_moveto(LCD_WIDTH - dwin_string.length(), row); lcd_put_dwin_string(); } #endif // Set the colors for a menu item based on whether it is selected static bool mark_as_selected(const uint8_t row, const bool sel, const bool is_static=false) { const dwin_coord_t y = row * (MENU_LINE_HEIGHT) + 1; if (y >= LCD_PIXEL_HEIGHT) return false; if (is_static && sel) DWIN_Draw_Box(1, Color_Bg_Heading, 0, y, LCD_PIXEL_WIDTH, MENU_LINE_HEIGHT - 1); else { #if ENABLED(MENU_HOLLOW_FRAME) DWIN_Draw_Box(1, Color_Bg_Black, 0, y, LCD_PIXEL_WIDTH, MENU_LINE_HEIGHT - 1); if (sel) DWIN_Draw_Box(0, Select_Color, 0, y, LCD_PIXEL_WIDTH, MENU_LINE_HEIGHT - 1); #else DWIN_Draw_Box(1, sel ? Select_Color : Color_Bg_Black, 0, y, LCD_PIXEL_WIDTH, MENU_LINE_HEIGHT - 1); #endif } return true; } // Draw a static line of text in the same idiom as a menu item void MenuItem_static::draw(const uint8_t row, PGM_P const pstr, const uint8_t style/*=SS_DEFAULT*/, const char * const vstr/*=nullptr*/) { // Call mark_as_selected to draw a bigger selection box // and draw the text without a background if (mark_as_selected(row, (bool)(style & SS_INVERT), true)) { ui.set_font(DWIN_FONT_MENU); dwin_font.solid = false; dwin_font.fg = Color_White; dwin_string.set(); const int8_t plen = pstr ? utf8_strlen_P(pstr) : 0, vlen = vstr ? utf8_strlen(vstr) : 0; if (style & SS_CENTER) { int8_t pad = (LCD_WIDTH - 1 - plen - vlen) / 2; while (--pad) dwin_string.add(' '); } if (plen) dwin_string.add((uint8_t*)pstr, itemIndex, (uint8_t*)itemString); if (vlen) dwin_string.add((uint8_t*)vstr); if (style & SS_CENTER) { int8_t pad = (LCD_WIDTH - 1 - plen - vlen) / 2; while (--pad) dwin_string.add(' '); } lcd_moveto(1, row); lcd_put_dwin_string(); } } // Draw a generic menu item void MenuItemBase::_draw(const bool sel, const uint8_t row, PGM_P const pstr, const char, const char post_char) { if (mark_as_selected(row, sel)) { ui.set_font(DWIN_FONT_MENU); dwin_font.solid = false; dwin_font.fg = Color_White; dwin_string.set(pstr, itemIndex, itemString); pixel_len_t n = LCD_WIDTH - 1 - dwin_string.length(); while (--n > 1) dwin_string.add(' '); dwin_string.add(post_char); lcd_moveto(1, row); lcd_put_dwin_string(); } } // // Draw a menu item with an editable value // void MenuEditItemBase::draw(const bool sel, const uint8_t row, PGM_P const pstr, const char* const data, const bool pgm) { if (mark_as_selected(row, sel)) { ui.set_font(DWIN_FONT_MENU); dwin_font.solid = false; dwin_font.fg = Color_White; const uint8_t vallen = (pgm ? utf8_strlen_P(data) : utf8_strlen(S(data))); dwin_string.set(pstr, itemIndex, itemString); if (vallen) dwin_string.add(':'); lcd_moveto(1, row); lcd_put_dwin_string(); if (vallen) { dwin_font.fg = Color_Yellow; dwin_string.set(data); lcd_moveto(LCD_WIDTH - vallen - 1, row); lcd_put_dwin_string(); } } } // // Draw an edit screen with label and current value // void MenuEditItemBase::draw_edit_screen(PGM_P const pstr, const char* const value/*=nullptr*/) { ui.encoder_direction_normal(); const dwin_coord_t labellen = utf8_strlen_P(pstr), vallen = utf8_strlen(value); dwin_string.set(); dwin_string.add((uint8_t*)pstr, itemIndex); if (vallen) dwin_string.add(':'); // If a value is included, add a colon // Assume the label is alpha-numeric (with a descender) const uint16_t row = (LCD_HEIGHT / 2) - 1; dwin_font.fg = Color_White; dwin_font.solid = true; lcd_moveto((LCD_WIDTH - labellen + !!vallen) / 2, row); lcd_put_dwin_string(); // If a value is included, print the value in larger text below the label if (vallen) { dwin_string.set(); dwin_string.add(value); const dwin_coord_t by = (row * MENU_LINE_HEIGHT) + MENU_FONT_HEIGHT + EXTRA_ROW_HEIGHT / 2; DWIN_Draw_String(true, font16x32, Color_Yellow, Color_Bg_Black, (LCD_PIXEL_WIDTH - vallen * 16) / 2, by, S(dwin_string.string())); extern screenFunc_t _manual_move_func_ptr; if (ui.currentScreen != _manual_move_func_ptr && !ui.external_control) { const dwin_coord_t slider_length = LCD_PIXEL_WIDTH - TERN(DWIN_MARLINUI_LANDSCAPE, 120, 20), slider_height = 16, slider_x = (LCD_PIXEL_WIDTH - slider_length) / 2, slider_y = by + 32 + 4, amount = ui.encoderPosition * slider_length / maxEditValue; DWIN_Draw_Rectangle(1, Color_Bg_Window, slider_x - 1, slider_y - 1, slider_x - 1 + slider_length + 2 - 1, slider_y - 1 + slider_height + 2 - 1); if (amount > 0) DWIN_Draw_Box(1, BarFill_Color, slider_x, slider_y, amount, slider_height); if (amount < slider_length) DWIN_Draw_Box(1, Color_Bg_Black, slider_x + amount, slider_y, slider_length - amount, slider_height); } } } inline void draw_boxed_string(const bool yesopt, PGM_P const pstr, const bool inv) { const uint8_t len = utf8_strlen_P(pstr), mar = TERN(DWIN_MARLINUI_PORTRAIT, 1, 4), col = yesopt ? LCD_WIDTH - mar - len : mar, row = (LCD_HEIGHT >= 8 ? LCD_HEIGHT / 2 + 3 : LCD_HEIGHT - 1); lcd_moveto(col, row); DWIN_Draw_Box(1, inv ? Select_Color : Color_Bg_Black, cursor.x - dwin_font.width, cursor.y + 1, dwin_font.width * (len + 2), dwin_font.height + 2); lcd_put_u8str_P(col, row, pstr); } void MenuItem_confirm::draw_select_screen( PGM_P const yes, PGM_P const no, const bool yesno, PGM_P const pref, const char * const string/*=nullptr*/, PGM_P const suff/*=nullptr*/ ) { ui.set_font(DWIN_FONT_MENU); dwin_font.solid = false; dwin_font.fg = Color_White; ui.draw_select_screen_prompt(pref, string, suff); draw_boxed_string(false, no, !yesno); draw_boxed_string(true, yes, yesno); } #if ENABLED(SDSUPPORT) void MenuItem_sdbase::draw(const bool sel, const uint8_t row, PGM_P const, CardReader &theCard, const bool isDir) { if (mark_as_selected(row, sel)) { dwin_string.set(); uint8_t maxlen = LCD_WIDTH - 1; if (isDir) { dwin_string.add(LCD_STR_FOLDER " "); maxlen -= 2; } dwin_string.add((uint8_t*)ui.scrolled_filename(theCard, maxlen, row, sel), maxlen); uint8_t n = maxlen - dwin_string.length(); while (n > 0) { dwin_string.add(' '); --n; } lcd_moveto(1, row); lcd_put_dwin_string(); } } #endif // SDSUPPORT #if ENABLED(AUTO_BED_LEVELING_UBL) /** * UBL LCD "radar" map data */ #define MAP_UPPER_LEFT_CORNER_X 5 // These probably should be moved to the .h file But for now, #define MAP_UPPER_LEFT_CORNER_Y 5 // it is easier to play with things having them here #define MAP_MAX_PIXELS_X 262 // 272 - 10 #define MAP_MAX_PIXELS_Y 262 void MarlinUI::ubl_plot(const uint8_t x_plot, const uint8_t y_plot) { // Scale the box pixels appropriately dwin_coord_t x_map_pixels = ((MAP_MAX_PIXELS_X - 4) / (GRID_MAX_POINTS_X)) * (GRID_MAX_POINTS_X), y_map_pixels = ((MAP_MAX_PIXELS_Y - 4) / (GRID_MAX_POINTS_Y)) * (GRID_MAX_POINTS_Y), pixels_per_x_mesh_pnt = x_map_pixels / (GRID_MAX_POINTS_X), pixels_per_y_mesh_pnt = y_map_pixels / (GRID_MAX_POINTS_Y), x_offset = MAP_UPPER_LEFT_CORNER_X + 1 + (MAP_MAX_PIXELS_X - x_map_pixels - 2) / 2, y_offset = MAP_UPPER_LEFT_CORNER_Y + 1 + (MAP_MAX_PIXELS_Y - y_map_pixels - 2) / 2; // Clear the Mesh Map // First draw the bigger box in White so we have a border around the mesh map box DWIN_Draw_Rectangle(1, Color_White, x_offset - 2, y_offset - 2, x_offset + 2 + x_map_pixels, y_offset + 2 + y_map_pixels); // Now actually clear the mesh map box DWIN_Draw_Rectangle(1, Color_Bg_Black, x_offset, y_offset, x_offset + x_map_pixels, y_offset + y_map_pixels); // Fill in the Specified Mesh Point const uint8_t y_plot_inv = (GRID_MAX_POINTS_Y - 1) - y_plot; // The origin is typically in the lower right corner. We need to // invert the Y to get it to plot in the right location. const dwin_coord_t by = y_offset + y_plot_inv * pixels_per_y_mesh_pnt; DWIN_Draw_Rectangle(1, Select_Color, x_offset + (x_plot * pixels_per_x_mesh_pnt), by, x_offset + (x_plot * pixels_per_x_mesh_pnt) + pixels_per_x_mesh_pnt, by + pixels_per_y_mesh_pnt ); // Display Mesh Point Locations const dwin_coord_t sx = x_offset + pixels_per_x_mesh_pnt / 2; dwin_coord_t y = y_offset + pixels_per_y_mesh_pnt / 2; for (uint8_t j = 0; j < GRID_MAX_POINTS_Y; j++, y += pixels_per_y_mesh_pnt) for (uint8_t i = 0, x = sx; i < GRID_MAX_POINTS_X; i++, x += pixels_per_x_mesh_pnt) DWIN_Draw_Point(Color_White, 1, 1, x, y); // Put Relevant Text on Display // Show X and Y positions at top of screen dwin_font.fg = Color_White; dwin_font.solid = true; const xy_pos_t pos = { ubl.mesh_index_to_xpos(x_plot), ubl.mesh_index_to_ypos(y_plot) }, lpos = pos.asLogical(); lcd_moveto( TERN(DWIN_MARLINUI_LANDSCAPE, ((x_offset + x_map_pixels) / MENU_FONT_WIDTH) + 2, 1), TERN(DWIN_MARLINUI_LANDSCAPE, 1, ((y_offset + y_map_pixels) / MENU_LINE_HEIGHT) + 1) ); lcd_put_u8str_P(X_LBL); lcd_put_u8str(ftostr52(lpos.x)); lcd_moveto( TERN(DWIN_MARLINUI_LANDSCAPE, ((x_offset + x_map_pixels) / MENU_FONT_WIDTH) + 2, 1), TERN(DWIN_MARLINUI_LANDSCAPE, 3, ((y_offset + y_map_pixels) / MENU_LINE_HEIGHT) + 2) ); lcd_put_u8str_P(Y_LBL); lcd_put_u8str(ftostr52(lpos.y)); // Print plot position dwin_string.set("("); dwin_string.add(i8tostr3rj(x_plot)); dwin_string.add(","); dwin_string.add(i8tostr3rj(y_plot)); dwin_string.add(")"); lcd_moveto( TERN(DWIN_MARLINUI_LANDSCAPE, ((x_offset + x_map_pixels) / MENU_FONT_WIDTH) + 2, LCD_WIDTH - dwin_string.length()), TERN(DWIN_MARLINUI_LANDSCAPE, LCD_HEIGHT - 2, ((y_offset + y_map_pixels) / MENU_LINE_HEIGHT) + 1) ); lcd_put_dwin_string(); // Show the location value dwin_string.set(Z_LBL); if (!isnan(Z_VALUES_ARR[x_plot][y_plot])) dwin_string.add(ftostr43sign(Z_VALUES_ARR[x_plot][y_plot])); else dwin_string.add(PSTR(" -----")); lcd_moveto( TERN(DWIN_MARLINUI_LANDSCAPE, ((x_offset + x_map_pixels) / MENU_FONT_WIDTH) + 2, LCD_WIDTH - dwin_string.length()), TERN(DWIN_MARLINUI_LANDSCAPE, LCD_HEIGHT - 1, ((y_offset + y_map_pixels) / MENU_LINE_HEIGHT) + 2) ); lcd_put_dwin_string(); } #endif // AUTO_BED_LEVELING_UBL #if ANY(BABYSTEP_ZPROBE_GFX_OVERLAY, MESH_EDIT_GFX_OVERLAY) void MarlinUI::zoffset_overlay(const int8_t dir) { const int rot_up = TERN(OVERLAY_GFX_REVERSE, ICON_RotateCCW, ICON_RotateCW), rot_down = TERN(OVERLAY_GFX_REVERSE, ICON_RotateCW, ICON_RotateCCW); const int nozzle = (LCD_PIXEL_WIDTH / 2) - 20; // Draw a representation of the nozzle DWIN_Draw_Box(1, Color_Bg_Black, nozzle + 3, 8, 48, 52); // 'clear' the area where the nozzle is drawn in case it was moved up/down DWIN_ICON_Show(ICON, ICON_HotendOff, nozzle + 3, 10 - dir); DWIN_ICON_Show(ICON, ICON_BedLine, nozzle, 10 + 36); // Draw cw/ccw indicator and up/down arrows const int arrow_y = LCD_PIXEL_HEIGHT / 2 - 24; DWIN_ICON_Show(ICON, ICON_DownArrow, 0, arrow_y - dir); DWIN_ICON_Show(ICON, rot_down, 48, arrow_y); DWIN_ICON_Show(ICON, ICON_UpArrow, LCD_PIXEL_WIDTH - 10 - (48*2), arrow_y - dir); DWIN_ICON_Show(ICON, rot_up, LCD_PIXEL_WIDTH - 10 - 48, arrow_y); } #endif // BABYSTEP_ZPROBE_GFX_OVERLAY || MESH_EDIT_GFX_OVERLAY #endif // HAS_LCD_MENU #endif // IS_DWIN_MARLINUI
36.771959
152
0.657081
[ "mesh", "3d", "solid" ]
ca8ef7207cb83e541e1f4c57c5af42faeda54bdb
7,169
cxx
C++
GRBtemplate/src/GRBtemplateManager.cxx
fermi-lat/celestialSources
aaa2a2275b767088c23fde64b407afdac3493208
[ "BSD-3-Clause" ]
null
null
null
GRBtemplate/src/GRBtemplateManager.cxx
fermi-lat/celestialSources
aaa2a2275b767088c23fde64b407afdac3493208
[ "BSD-3-Clause" ]
null
null
null
GRBtemplate/src/GRBtemplateManager.cxx
fermi-lat/celestialSources
aaa2a2275b767088c23fde64b407afdac3493208
[ "BSD-3-Clause" ]
1
2017-08-31T21:10:27.000Z
2017-08-31T21:10:27.000Z
/* * $Header$ */ #include "GRBtemplate/GRBtemplateManager.h" #include <cstdlib> #include <iostream> #include <stdexcept> #include <fstream> #include "flux/SpectrumFactory.h" #include "astro/EarthCoordinate.h" #include "astro/GPS.h" #include "astro/SkyDir.h" #include "astro/PointingTransform.h" #include "astro/JulianDate.h" #include "CLHEP/Vector/ThreeVector.h" #define DEBUG 0 ISpectrumFactory &GRBtemplateManagerFactory() { static SpectrumFactory<GRBtemplateManager> myFactory; return myFactory; } GRBtemplateManager::GRBtemplateManager(const std::string& params) : m_params(params) { using astro::GPS; m_rnd = new TRandom(); m_GenerateGBMOutputs = false; m_InputFileName = parseParamList(params,0); facilities::Util::expandEnvVar(&m_InputFileName); m_startTime = ::atof(parseParamList(params,1).c_str())+Spectrum::startTime(); m_MinPhotonEnergy = ::atof(parseParamList(params,2).c_str())*1.0e3; //MeV if(::atof(parseParamList(params,3).c_str())!=0) m_GenerateGBMOutputs = true; m_theta_fow = ::atof(parseParamList(params,4).c_str()); // m_par = new GRBtemplateParameters(); m_GRBnumber = (long) floor(65540+m_startTime); // facilities::Util::expandEnvVar(&m_InputFileName); m_theta = -1000000.0; //if(FOV>-90) std::cout<<"WARNING!! GRBtemplate: FOV = "<<FOV<<std::endl; m_theta_fow = 90.0 - m_theta_fow; while(m_theta < m_theta_fow - 2.0 || m_theta > m_theta_fow + 2.0) { double r1 = m_rnd->Uniform(); double r2 = m_rnd->Uniform(); m_l = 180.-360.*r1; m_b = ((180.0/M_PI)*acos(1.0-2.0*r2)-90.0); astro::SkyDir sky(m_l,m_b,astro::SkyDir::GALACTIC); CLHEP::Hep3Vector skydir=sky.dir(); try{ CLHEP::HepRotation rottoglast = GPS::instance()->transformToGlast(m_startTime,GPS::CELESTIAL); CLHEP::Hep3Vector scdir = rottoglast * skydir; m_ra = sky.ra(); m_dec = sky.dec(); double zenithCosTheta=cos(scdir.theta()); m_theta = 90. - scdir.theta()*180.0/M_PI; // theta=0 -> XY plane, theta=90 -> Z m_phi = scdir.phi()*180.0/M_PI; m_grbdeleted = false; m_grbocculted = (zenithCosTheta < -0.4); // this is hardcoded in FluxSource.cxx } catch(const std::exception &e) { m_grbdeleted=true; break; } m_GalDir=std::make_pair(m_l,m_b); } m_grbGenerated = false; ////////////////////////////////////////////////// } std::string GRBtemplateManager::GetGRBname() { ////DATE AND GRBNAME /// GRB are named as customary GRBOBSYYMMDDXXXX // The mission start and launch date are retrieved, // and the current burst's start time is added to them to form a Julian Date. // Note: the argument of the JulianDate constructor is in day. astro::JulianDate JD(astro::JulianDate::missionStart() + m_startTime/astro::JulianDate::secondsPerDay); int An,Me,Gio; m_Rest=((int) m_startTime % 86400) + m_startTime - floor(m_startTime); m_Frac=(m_Rest/86400.); int FracI=(int)(m_Frac*1000.0); double utc; JD.getGregorianDate(An,Me,Gio,utc); An-=2000; std::ostringstream ostr; if(An<10) { ostr<<"0"; ostr<<An; } else { ostr<<An; } if(Me<10) { ostr<<"0"; ostr<<Me; } else { ostr<<Me; } if(Gio<10) { ostr<<"0"; ostr<<Gio; } else { ostr<<Gio; } if (FracI<10) { ostr<<"00"; ostr<<FracI; } else if(FracI<100) { ostr<<"0"; ostr<<FracI; } else ostr<<FracI; std::string GRBname = ostr.str(); if(DEBUG) std::cout<<"GENERATE GRB TEMPLATE ("<<GRBname<<")"<<std::endl; //.................................................. // return GRBname; } GRBtemplateManager::~GRBtemplateManager() { delete m_rnd; DeleteGRB(); } void GRBtemplateManager::GenerateGRB() { if(m_grbdeleted) return; /////GRB GRNERATION//////////////////////////////// m_GRB = new GRBtemplateSim(m_InputFileName); m_spectrum = new SpectObj(m_GRB->MakeGRB(),0); m_spectrum->SetAreaDetector(EventSource::totalArea()); ////////////////////////////////////////////////// m_endTime = m_startTime + m_GRB->Tmax(); std::string GRBname = GetGRBname(); if(m_grbocculted) { std::cout<<"This GRB is occulted by the Earth"<<std::endl; } else if(m_GenerateGBMOutputs) { m_GRB->SaveGBMDefinition(GRBname,m_ra,m_dec,m_theta,m_phi,m_Rest); m_GRB->GetGBMFlux(GRBname); } TString name = "GRBTMP_"; name+=GRBname; name+="_PAR.txt"; /* std::ofstream os(name,std::ios::out); os<<m_startTime<<" "<<m_endTime<<" "<<m_l<<" "<<m_b<<" "<<m_theta<<" "<<m_phi<<" "<<m_fluence<<" "<<" "<<m_alpha<<" "<<m_beta<<std::endl; os.close(); */ std::cout<<"Template GRB"<<GRBname<<" t start "<<m_startTime<<", tend "<<m_endTime <<" l,b = "<<m_l<<", "<<m_b<<" elevation,phi(deg) = "<<m_theta<<", "<<m_phi<<std::endl; m_grbGenerated=true; } void GRBtemplateManager::DeleteGRB() { if(m_grbGenerated) { delete m_GRB; delete m_spectrum; } m_grbdeleted=true; } //return flux, given a time double GRBtemplateManager::flux(double time) const { if(DEBUG) std::cout<<"Flux at "<<time<<" "<<m_startTime<<" "<<m_grbGenerated<<std::endl; double flux= 0.0; if(m_grbdeleted) return flux; else if(time <= m_startTime || time > m_startTime+5000) { if(m_grbGenerated) const_cast<GRBtemplateManager*>(this)->DeleteGRB(); return flux; } else { if(!m_grbGenerated) const_cast<GRBtemplateManager*>(this)->GenerateGRB(); flux = m_spectrum->flux(time-m_startTime,m_MinPhotonEnergy); } if(DEBUG) std::cout<<"flux("<<time<<") = "<<flux<<std::endl; return flux; } double GRBtemplateManager::interval(double time) { if(DEBUG) std::cout<<"interval at "<<time<<std::endl; double inte; if(m_grbdeleted) { inte = 1e10; } else if(time < m_startTime) { inte = m_startTime - time; } else if(time<m_startTime + 5000) //Confidential limit { if(!m_grbGenerated) const_cast<GRBtemplateManager*>(this)->GenerateGRB(); inte = m_spectrum->interval(time - m_startTime,m_MinPhotonEnergy); } else { inte = 1e10; if(m_grbGenerated) const_cast<GRBtemplateManager*>(this)->DeleteGRB(); } if(DEBUG) std::cout<<"Interval("<<time<<") = "<<inte<<std::endl; return inte; } double GRBtemplateManager::energy(double time) { if(DEBUG) std::cout<<"energy at "<<time<<std::endl; double ene=0.1; if(m_grbGenerated && !m_grbdeleted) ene = m_spectrum->energy(time-m_startTime,m_MinPhotonEnergy)*1.0e-3; //MeV if(DEBUG) std::cout<<"energy("<<time<<") = "<<ene<<std::endl; return ene; } std::string GRBtemplateManager::parseParamList(std::string input, unsigned int index) { std::vector<std::string> output; unsigned long i=0; for(;!input.empty() && i!=std::string::npos;){ i=input.find_first_of(","); std::string f = input.substr(0,i); output.push_back(f); input= input.substr(i+1); } if(index>=(unsigned int)output.size()) return "0.0"; return output[index]; }
25.332155
141
0.615149
[ "vector" ]
ca907fc0e5127d08d6ea885dfbcb7a794619add6
19,012
cpp
C++
net/rras/cm/cmdl/vpndownload.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/rras/cm/cmdl/vpndownload.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/rras/cm/cmdl/vpndownload.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+---------------------------------------------------------------------------- // // File: vpndownload.cpp // // Module: CMDL32.EXE // // Synopsis: This file contains the code to handle the updating of VPN phonebooks. // // Copyright (c) 2000-2001 Microsoft Corporation // // Author: quintinb Created 11/03/00 // //+---------------------------------------------------------------------------- #include "cmdl.h" #include "gppswithalloc.cpp" #include "tunl_str.h" //+---------------------------------------------------------------------------- // // Function: DownloadVpnFileFromUrl // // Synopsis: This function is responsible for downloading a VPN file update // from the given URL and storing the retreived data in a temp file. // The full path to the temp file is passed back to the caller via // the ppszVpnUpdateFile variable. The var must be freed by the caller. // // Arguments: LPCTSTR pszVpnUpdateUrl - URL to update the vpn file from // LPTSTR* ppszVpnUpdateFile - pointer to hold the file name of the // updated VPN file downloaded from the server. // Used by the caller to copy the temp file // over the existing file. The memory allocated // for this string must be freed by the caller. // // Returns: DWORD - ERROR_SUCCESS if download was successful, error code otherwise // // History: quintinb Created 11/05/00 // //+---------------------------------------------------------------------------- DWORD DownloadVpnFileFromUrl(LPCTSTR pszVpnUpdateUrl, LPTSTR* ppszVpnUpdateFile) { DWORD dwError = ERROR_NOT_ENOUGH_MEMORY; BOOL bDeleteFileOnFailure = FALSE; HANDLE hFile = NULL; HINTERNET hInternet = NULL; HINTERNET hPage = NULL; DWORD dwSize = MAX_PATH; LPTSTR pszBuffer = NULL; BOOL bExitLoop = FALSE; if ((NULL == pszVpnUpdateUrl) || (TEXT('\0') == pszVpnUpdateUrl[0])) { dwError = ERROR_INVALID_PARAMETER; goto Cleanup; } CMTRACE1("DownloadVpnFileFromUrl: URL is %s", pszVpnUpdateUrl); // // First, let's create the file that we are going to download the updated file // too. This requires us to figure out what the temporary directory path is // and then create a uniquely named file in it. // do { CmFree(pszBuffer); pszBuffer = (LPTSTR)CmMalloc((dwSize + 1)*sizeof(TCHAR)); if (pszBuffer) { DWORD dwReturnedSize = GetTempPath (dwSize, pszBuffer); if (0 == dwReturnedSize) { // // An error occurred, lets report it and bail. // dwError = GetLastError(); CMASSERTMSG(FALSE, TEXT("DownloadVpnFileFromUrl -- GetTempPath returned an error.")); CMTRACE1(TEXT("DownloadVpnFileFromUrl -- GetTempPath failed, GLE = %d"), dwError); goto Cleanup; } else if (dwReturnedSize > dwSize) { // // Not big enough we will have to loop again. // dwSize = dwReturnedSize; if (1024*1024 < dwReturnedSize) { CMASSERTMSG(FALSE, TEXT("DownloadVpnFileFromUrl -- GetTempPath asked for more than 1MB of memory. Something is wrong, bailing.")); goto Cleanup; } } else { // // We got what we wanted, it's time to leave the loop // bExitLoop = TRUE; } } else { CMASSERTMSG(FALSE, TEXT("DownloadVpnFileFromUrl -- CmMalloc failed for pszBuffer.")); goto Cleanup; } } while(!bExitLoop); // // Okay, now we have the temp file path. Next let's get a temp file name in that directory. // *ppszVpnUpdateFile = (LPTSTR)CmMalloc((dwSize + 24)*sizeof(TCHAR)); // GetTempFileName doesn't provide sizing info, lame if (*ppszVpnUpdateFile) { dwSize = GetTempFileName(pszBuffer, TEXT("VPN"), 0, *ppszVpnUpdateFile); if ((0 == dwSize) || (TEXT('\0') == (*ppszVpnUpdateFile)[0])) { dwError = GetLastError(); CMASSERTMSG(FALSE, TEXT("DownloadVpnFileFromUrl -- GetTempFileName failed.")); goto Cleanup; } } else { CMASSERTMSG(FALSE, TEXT("DownloadVpnFileFromUrl -- CmMalloc failed for *ppszVpnUpdateFile")); goto Cleanup; } // // Free pszBuffer so we can use it to read in file data below // CmFree (pszBuffer); pszBuffer = NULL; // // Okay, we have a file name let's get a file handle to it that we can write too // hFile = CreateFile(*ppszVpnUpdateFile, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE != hFile) { // // We have created the file, let's make sure to delete it if we fail from here on out. // bDeleteFileOnFailure = TRUE; // // Initialize WININET // hInternet = InternetOpen(TEXT("Microsoft(R) Connection Manager Vpn File Update"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hInternet) { // // Supress auto-dial calls to CM from WININET now that we have a handle // SuppressInetAutoDial(hInternet); // // Make sure that WinInet isn't in offline mode // (VOID)SetInetStateConnected(hInternet); // // Open the URL // hPage = InternetOpenUrl(hInternet, pszVpnUpdateUrl, NULL, 0, 0, 0); if (hPage) { const DWORD c_dwBufferSize = 1024; // REVIEW: why did the original use 4096 on the stack, seems awfully large to me? pszBuffer = (LPTSTR)CmMalloc(c_dwBufferSize); if (pszBuffer) { bExitLoop = FALSE; do { if (InternetReadFile(hPage, pszBuffer, c_dwBufferSize, &dwSize)) { // // We got data, write it to the temp file // if (0 == dwSize) { // // We succeeded with a zero read size. That means we hit // end of file and are done. // dwError = ERROR_SUCCESS; bExitLoop = TRUE; } if (FALSE == WriteFile(hFile, pszBuffer, dwSize, &dwSize, NULL)) { dwError = GetLastError(); CMASSERTMSG(FALSE, TEXT("DownloadVpnFileFromUrl -- WriteFile failed.")); goto Cleanup; } } else { dwError = GetLastError(); goto Cleanup; } } while (!bExitLoop); // // now let's see if we have a valid file, or an "error" HTML page // if (0 == GetPrivateProfileSection(c_pszCmSectionVpnServers, pszBuffer, c_dwBufferSize, *ppszVpnUpdateFile)) { dwError = ERROR_INVALID_DATA; CMTRACE(TEXT("DownloadVpnFileFromUrl -- downloaded file does not seem to contain a VPN list.")); goto Cleanup; } } else { CMASSERTMSG(FALSE, TEXT("DownloadVpnFileFromUrl -- unable to allocate the file buffer")); goto Cleanup; } } else { dwError = GetLastError(); CMTRACE1(TEXT("DownloadVpnFileFromUrl -- InternetOpenUrl failed, GLE %d"), dwError); } } else { dwError = GetLastError(); CMTRACE1(TEXT("DownloadVpnFileFromUrl -- InternetOpen failed, GLE %d"), dwError); } } Cleanup: // // Close our handles // if (hPage) { InternetCloseHandle(hPage); } if (hInternet) { InternetCloseHandle(hInternet); } if (hFile) { CloseHandle(hFile); } // // Free up the buffer we alloc-ed // CmFree(pszBuffer); // // Finally cleanup the temp file and temp file name if we failed // if (ERROR_SUCCESS != dwError) { if (bDeleteFileOnFailure && *ppszVpnUpdateFile) { DeleteFile(*ppszVpnUpdateFile); } CmFree(*ppszVpnUpdateFile); *ppszVpnUpdateFile = NULL; CMTRACE(TEXT("DownloadVpnFileFromUrl -- VPN file download failed!")); } else { CMTRACE(TEXT("DownloadVpnFileFromUrl -- VPN file download succeeded!")); } return dwError; } //+---------------------------------------------------------------------------- // // Function: OverwriteVpnFileWithUpdate // // Synopsis: This function is responsible for copying the given new vpn file // over the given existing vpn file. The code first makes a backup // copy of the existing file just in case something goes wrong with the // data overwrite. If a problem exists then it copies the original back // over to ensure nothing got corrupted in the failed copy. // // Arguments: LPCTSTR pszExistingVpnFile - full path to the existing VPN file // LPCTSTR pszNewVpnFile - full path to the temp VPN file to overwrite // the existing file with. // // Returns: DWORD - ERROR_SUCCESS if update was successful, error code otherwise // // History: quintinb Created 11/03/00 // //+---------------------------------------------------------------------------- DWORD OverwriteVpnFileWithUpdate(LPCTSTR pszExistingVpnFile, LPCTSTR pszNewVpnFile) { if ((NULL == pszExistingVpnFile) || (NULL == pszNewVpnFile) || (TEXT('\0') == pszExistingVpnFile[0]) || (TEXT('\0') == pszNewVpnFile[0])) { CMASSERTMSG(FALSE, TEXT("OverwriteVpnFileWithUpdate -- invalid parameter passed.")); return FALSE; } DWORD dwError = ERROR_NOT_ENOUGH_MEMORY; // // We first want to make a backup copy of the original file // const TCHAR* const c_pszDotBak = TEXT(".bak"); DWORD dwSize = (lstrlen(pszExistingVpnFile) + lstrlen(c_pszDotBak) + 1)*sizeof(TCHAR); LPTSTR pszBackupFile = (LPTSTR)CmMalloc(dwSize); if (pszBackupFile) { wsprintf(pszBackupFile, TEXT("%s%s"), pszExistingVpnFile, c_pszDotBak); CMASSERTMSG(pszBackupFile[0], TEXT("OverwriteVpnFileWithUpdate -- wsprintf failed!")); if (CopyFile(pszExistingVpnFile, pszBackupFile, FALSE)) // FALSE == bFailIfExists { // // Now copy over the new file // if (CopyFile(pszNewVpnFile, pszExistingVpnFile, FALSE)) // FALSE == bFailIfExists { dwError = ERROR_SUCCESS; } else { dwError = GetLastError(); CMTRACE1(TEXT("OverwriteVpnFileWithUpdate -- CopyFile of the new file over the original file failed, GLE %s"), dwError); CMASSERTMSG(FALSE, TEXT("OverwriteVpnFileWithUpdate -- update of the original file failed, attempting to restore the original from backup.")); // // We need to restore the backup file // if (!CopyFile(pszBackupFile, pszExistingVpnFile, FALSE)) // FALSE == bFailIfExists { // NOTE we don't use dwError here, we want the original error to be logged CMTRACE1(TEXT("OverwriteVpnFileWithUpdate -- CopyFile to restore the saved backup file failed, GLE %s"), GetLastError()); CMASSERTMSG(FALSE, TEXT("OverwriteVpnFileWithUpdate -- restoration of backup failed!")); } } // // Delete the backup file // DeleteFile(pszBackupFile); } else { dwError = GetLastError(); CMTRACE1(TEXT("OverwriteVpnFileWithUpdate -- CopyFile of the original file to the backup file failed, GLE %s"), dwError); } } CmFree(pszBackupFile); if (ERROR_SUCCESS == dwError) { CMTRACE(TEXT("OverwriteVpnFileWithUpdate -- VPN file update succeeded!")); } else { CMTRACE(TEXT("OverwriteVpnFileWithUpdate -- VPN file update failed.")); } return dwError; } //+---------------------------------------------------------------------------- // // Function: UpdateVpnFileForProfile // // Synopsis: This function is called to download and update a VPN file with a // newly downloaded VPN update file. // // Arguments: LPCTSTR pszCmpPath - full path to the cmp file // CmLogFile * pLog - object to use for logging // // Returns: BOOL - TRUE if the download and update were successful. // // History: quintinb Created 11/03/00 // //+---------------------------------------------------------------------------- BOOL UpdateVpnFileForProfile(LPCTSTR pszCmpPath, LPCTSTR pszCmsPath, CmLogFile * pLog, BOOL bCheckConnection) { if ((NULL == pszCmpPath) || (TEXT('\0') == pszCmpPath[0])) { CMASSERTMSG(FALSE, TEXT("UpdateVpnFileForProfile in cmdl32.exe -- invalid pszCmpPath parameter.")); return FALSE; } BOOL bLogAtEnd = TRUE; BOOL bReturn = FALSE; DWORD dwError = ERROR_INVALID_PARAMETER; if (pszCmsPath && *pszCmsPath) { // // Let's check to see if we are connected unless the caller told us to skip the check // if (bCheckConnection) { LPTSTR pszConnectionName = GetPrivateProfileStringWithAlloc(c_pszCmSection, c_pszCmEntryServiceName, TEXT(""), pszCmsPath); if (pszConnectionName && *pszConnectionName) { if (FALSE == IsConnectionAlive(pszConnectionName)) { CMTRACE(TEXT("UpdateVpnFileForProfile -- not connected ... aborting.")); pLog->Log(VPN_DOWNLOAD_FAILURE, ERROR_NOT_CONNECTED, TEXT(""), TEXT("")); CmFree(pszConnectionName); return FALSE; } } CmFree(pszConnectionName); } // // Next get the VPN phonebook file name from the profile. // LPTSTR pszVpnFileName = GetPrivateProfileStringWithAlloc(c_pszCmSection, c_pszCmEntryTunnelFile, TEXT(""), pszCmsPath); if (pszVpnFileName && *pszVpnFileName) { LPTSTR pszVpnFile = CmBuildFullPathFromRelative(pszCmpPath, pszVpnFileName); if (pszVpnFile && *pszVpnFile) { // // Now get the URL to update the vpn file from // LPTSTR pszVpnUpdateUrl = GetPrivateProfileStringWithAlloc(c_pszCmSectionSettings, c_pszCmEntryVpnUpdateUrl, TEXT(""), pszVpnFile); if (pszVpnUpdateUrl && *pszVpnUpdateUrl) { // // Finally, we have a URL so let's download the updated VPN server list. // LPTSTR pszUpdatedVpnFile = NULL; dwError = DownloadVpnFileFromUrl(pszVpnUpdateUrl, &pszUpdatedVpnFile); bReturn = (ERROR_SUCCESS == dwError); bLogAtEnd = FALSE; // we're going to start logging items right now if (bReturn) { pLog->Log(VPN_DOWNLOAD_SUCCESS, pszVpnFile, pszVpnUpdateUrl); } else { pLog->Log(VPN_DOWNLOAD_FAILURE, dwError, pszVpnFile, pszVpnUpdateUrl); } if (bReturn && pszUpdatedVpnFile && *pszUpdatedVpnFile) { dwError = OverwriteVpnFileWithUpdate(pszVpnFile, pszUpdatedVpnFile); bReturn = (ERROR_SUCCESS == dwError); if (bReturn) { pLog->Log(VPN_UPDATE_SUCCESS, pszVpnFile); } else { pLog->Log(VPN_UPDATE_FAILURE, dwError, pszVpnFile); } } CmFree (pszUpdatedVpnFile); } else { dwError = GetLastError(); CMASSERTMSG(FALSE, TEXT("UpdateVpnFileForProfile in cmdl32.exe -- unable to get the URL to update the vpn file from...")); } CmFree(pszVpnUpdateUrl); } else { dwError = GetLastError(); CMASSERTMSG(FALSE, TEXT("UpdateVpnFileForProfile in cmdl32.exe -- unable to expand the path to the vpn file.")); } CmFree(pszVpnFile); } else { dwError = GetLastError(); CMASSERTMSG(FALSE, TEXT("UpdateVpnFileForProfile in cmdl32.exe -- unable to retrieve the vpn file name.")); } CmFree(pszVpnFileName); } if (bLogAtEnd) { pLog->Log(VPN_DOWNLOAD_FAILURE, dwError, TEXT("?"), TEXT("?")); } return bReturn; }
36.144487
159
0.492584
[ "object" ]
ca91e5112ff10a763c5297bfb18928b48e25c6f1
1,380
cpp
C++
Sources/Elastos/LibCore/src/elastosx/crypto/spec/PSource.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/src/elastosx/crypto/spec/PSource.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/src/elastosx/crypto/spec/PSource.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "PSource.h" namespace Elastosx { namespace Crypto { namespace Spec { CAR_INTERFACE_IMPL(PSource, Object, IPSource) PSource::PSource() : mPSrcName(String(NULL)) { } ECode PSource::constructor( /* [in] */ const String& pSrcName) { if (pSrcName == NULL) { // throw new NullPointerException("pSrcName == null"); return E_NULL_POINTER_EXCEPTION; } mPSrcName = pSrcName; return NOERROR; } ECode PSource::GetAlgorithm( /* [out] */ String * result) { VALIDATE_NOT_NULL(result) *result = mPSrcName; return NOERROR; } } // Spec } // Crypto } // Elastosx
27.058824
75
0.619565
[ "object" ]
ca9ae791b55306ebd4ddd8ec8f7829dddb478895
2,090
cc
C++
Strategy/TextProcessor/src/main.cc
kasakun/Design-Patterns
8196c2d3bc03cdf36b913f890a615ccf18924a11
[ "MIT" ]
null
null
null
Strategy/TextProcessor/src/main.cc
kasakun/Design-Patterns
8196c2d3bc03cdf36b913f890a615ccf18924a11
[ "MIT" ]
null
null
null
Strategy/TextProcessor/src/main.cc
kasakun/Design-Patterns
8196c2d3bc03cdf36b913f890a615ccf18924a11
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> using namespace std; enum class OutputFormat { Markdown, Html }; struct ListStrategy { virtual ~ListStrategy() = default; virtual void add_list_item(ostringstream& oss, const string& item) {}; virtual void start(ostringstream& oss) {}; virtual void end(ostringstream& oss) {}; }; struct MarkdownListStrategy : ListStrategy { void add_list_item(ostringstream& oss, const string& item) override { oss << " * " << item << endl; } }; struct HtmlListStrategy : ListStrategy { void start(ostringstream& oss) override { oss << "<ul>" << endl; } void end(ostringstream& oss) override { oss << "</ul>" << endl; } void add_list_item(ostringstream& oss, const string& item) override { oss << "<li>" << item << "</li>" << endl; } }; struct TextProcessor { void clear() { oss.str(""); oss.clear(); } void append_list(const vector<string> items) { list_strategy->start(oss); for (auto& item : items) list_strategy->add_list_item(oss, item); list_strategy->end(oss); } void set_output_format(const OutputFormat format) { switch (format) { case OutputFormat::Markdown: list_strategy = make_unique<MarkdownListStrategy>(); break; case OutputFormat::Html: list_strategy = make_unique<HtmlListStrategy>(); break; default: throw runtime_error("Unsupported strategy."); } } string str() const { return oss.str(); } private: ostringstream oss; unique_ptr<ListStrategy> list_strategy; }; int main() { // markdown TextProcessor tp; tp.set_output_format(OutputFormat::Markdown); tp.append_list({ "foo", "bar", "baz" }); cout << tp.str() << endl; // html tp.clear(); tp.set_output_format(OutputFormat::Html); tp.append_list({ "foo", "bar", "baz" }); cout << tp.str() << endl; getchar(); return 0; }
24.302326
74
0.602871
[ "vector" ]
caa2721441a0d919e67f2cc2825742c05b8713b4
4,349
cpp
C++
src/k_point/test_fv_states.cpp
mtaillefumier/SIRIUS
50ec1c202c019113c5660f1966b170dec9dfd4d4
[ "BSD-2-Clause" ]
77
2016-03-18T08:38:30.000Z
2022-03-11T14:06:25.000Z
src/K_point/test_fv_states.cpp
oschuett/SIRIUS
8725bb9bc56d7655df9e02b2a511cb63def29d85
[ "BSD-2-Clause" ]
240
2016-04-12T16:39:11.000Z
2022-03-31T08:46:12.000Z
src/K_point/test_fv_states.cpp
oschuett/SIRIUS
8725bb9bc56d7655df9e02b2a511cb63def29d85
[ "BSD-2-Clause" ]
43
2016-03-18T17:45:07.000Z
2022-02-28T05:27:59.000Z
// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess // 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. /** \file test_fv_states.hpp * * \brief Test orthonormalisation of first-variational states. */ #include "k_point.hpp" namespace sirius { void K_point::test_fv_states() { PROFILE("sirius::K_point::test_fv_states"); STOP(); // Wave_functions<true> o_fv(wf_size(), ctx_.num_fv_states(), ctx_.cyclic_block_size(), ctx_.blacs_grid(), // ctx_.blacs_grid_slice()); o_fv.set_num_swapped(ctx_.num_fv_states()); // for (int i = 0; i < o_fv.spl_num_col().local_size(); i++) //{ // std::memset(o_fv[i], 0, wf_size() * sizeof(double_complex)); // for (int ia = 0; ia < unit_cell_.num_atoms(); ia++) // { // int offset_wf = unit_cell_.atom(ia).offset_wf(); // auto& type = unit_cell_.atom(ia).type(); // auto& symmetry_class = unit_cell_.atom(ia).symmetry_class(); // for (int l = 0; l <= ctx_.lmax_apw(); l++) // { // int ordmax = type.indexr().num_rf(l); // for (int io1 = 0; io1 < ordmax; io1++) // { // for (int io2 = 0; io2 < ordmax; io2++) // { // for (int m = -l; m <= l; m++) // { // o_fv[i][offset_wf + type.indexb_by_l_m_order(l, m, io2)] += // fv_states<true>()[i][offset_wf + type.indexb_by_l_m_order(l, m, io1)] * // symmetry_class.o_radial_integral(l, io1, io2); // } // } // } // } // } // ctx_.fft().transform<1>(gkvec().partition(), &fv_states<true>()[i][unit_cell_.mt_basis_size()]); // for (int ir = 0; ir < ctx_.fft().local_size(); ir++) ctx_.fft().buffer(ir) *= // ctx_.step_function().theta_r(ir); ctx_.fft().transform<-1>(gkvec().partition(), // &o_fv[i][unit_cell_.mt_basis_size()]); //} // o_fv.swap_backward(0, ctx_.num_fv_states()); // dmatrix<double_complex> ovlp(ctx_.num_fv_states(), ctx_.num_fv_states(), ctx_.blacs_grid(), // ctx_.cyclic_block_size(), ctx_.cyclic_block_size()); // // linalg<device_t::CPU>::gemm(2, 0, ctx_.num_fv_states(), ctx_.num_fv_states(), wf_size(), double_complex(1, 0), // fv_states<true>().prime(), o_fv.prime(), double_complex(0, 0), ovlp); // // double max_err = 0; // for (int i = 0; i < ovlp.num_cols_local(); i++) //{ // for (int j = 0; j < ovlp.num_rows_local(); j++) // { // if (ovlp.icol(i) == ovlp.irow(j)) ovlp(j, i) -= 1; // max_err = std::max(max_err, std::abs(ovlp(j, i))); // } //} // comm().allreduce<double, op_max>(&max_err, 1); // if (comm().rank() == 0) //{ // printf("k-point: %f %f %f, maximum error of fv_states overlap : %18.10e\n", // vk_[0], vk_[1], vk_[2], max_err); //} } } // namespace sirius
44.835052
117
0.5914
[ "transform" ]
caa827f1fd8359081abaaaaf751be1cc1a5bb0aa
6,879
hpp
C++
include/STP/Core/ObjectGroup.hpp
mustafmst/lost-dungeon
78eab777dc4ffeacca48e647cf5945628992ce7c
[ "MIT" ]
33
2015-06-26T19:39:40.000Z
2022-01-03T23:34:12.000Z
include/STP/Core/ObjectGroup.hpp
arnavr23/STP
7c027a84d61137f092f4fac7d847a0085b156dbc
[ "MIT" ]
25
2015-02-17T17:02:51.000Z
2020-08-23T22:57:55.000Z
include/STP/Core/ObjectGroup.hpp
arnavr23/STP
7c027a84d61137f092f4fac7d847a0085b156dbc
[ "MIT" ]
26
2015-02-14T18:21:14.000Z
2020-07-27T04:39:30.000Z
//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // STP - SFML TMX Parser // Copyright (c) 2013-2014 Manuel Sabogal // // 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. // //////////////////////////////////////////////////////////// #ifndef STP_OBJECTGROUP_HPP #define STP_OBJECTGROUP_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <string> #include <vector> #include <unordered_map> #include "SFML/Graphics/VertexArray.hpp" #include "SFML/Graphics/PrimitiveType.hpp" #include "SFML/Graphics/Drawable.hpp" #include "STP/Config.hpp" #include "STP/Core/MapObject.hpp" #include "STP/Core/TileSet.hpp" namespace tmx { enum ObjectType { Rectangle, Ellipse, Polygon, Polyline, Tile }; //////////////////////////////////////////////////////////// /// \brief Class for manage the TMX ObjectGroups /// //////////////////////////////////////////////////////////// class STP_API ObjectGroup : public MapObject { public: //////////////////////////////////////////////////////////// /// \brief Default constructor /// /// Constructs an empty object group with no values. /// //////////////////////////////////////////////////////////// ObjectGroup(); //////////////////////////////////////////////////////////// /// \brief Constructs a object group given a name, width, height /// opacity, visible and hexcolor atributes /// /// \param name The name of the object group /// \param width The width of the object group in tiles /// \param height The height of the object group in tiles /// \param opacity Float value between 0.0 to 1.0 /// \param visible The visibility of the object group /// \param hexcolor Hexadecimal color used to display the objects in this group. (example value: 0x0000FF for blue) /// //////////////////////////////////////////////////////////// ObjectGroup(const std::string& name, unsigned int width, unsigned int height, float opacity, bool visible, int32_t hexcolor = -1); //////////////////////////////////////////////////////////// /// Nested classes /// //////////////////////////////////////////////////////////// class Object; //////////////////////////////////////////////////////////// /// \brief Add a new Object to the object group /// /// \param newobject Object to be added /// //////////////////////////////////////////////////////////// void AddObject(tmx::ObjectGroup::Object newobject); //////////////////////////////////////////////////////////// /// \brief Change the color of the object group, does not affect the opacity /// /// \param color sf::Color RGB value /// //////////////////////////////////////////////////////////// void SetColor(const sf::Color& color); //////////////////////////////////////////////////////////// /// \brief Change the opacity of the object group /// /// \param opacity Float value between 0.0 to 1.0 /// //////////////////////////////////////////////////////////// void SetOpacity(float opacity); private: void draw(sf::RenderTarget& target, sf::RenderStates states) const; private: std::vector<tmx::ObjectGroup::Object> objects_; }; //////////////////////////////////////////////////////////// /// \brief Class for manage each Object inside of the ObjectGroup /// //////////////////////////////////////////////////////////// class STP_API ObjectGroup::Object : public sf::Drawable, public tmx::Properties { public: //////////////////////////////////////////////////////////// /// \brief Construct a Object given a name, width, height /// rotation, visible and image atributes /// /// \param name The name of the object (An arbitrary string) /// \param type The type of the object (An arbitrary string) /// \param x The x coordinate of the object in pixels /// \param y The y coordinate of the object in pixels /// \param width The width of the object in pixels (defaults to 0) /// \param height The width of the object in pixels (defaults to 0) /// \param rotation The rotation of the object in degrees clockwise (defaults to 0) /// \param visible The visibility of the object /// \param shape_type The shape type of the object, see tmx::ObjectType /// \param vertices_points String containing a list of coordinates (example: "0,0 17,17 -14,18") /// \param tile Pointer to a Ttmx::TileSet::Tile, only used when is a Tile-Object, otherwise is nullptr. /// //////////////////////////////////////////////////////////// Object(const std::string& name, const std::string& type, int x, int y, unsigned int width, unsigned int height, float rotation, bool visible, tmx::ObjectType shape_type, const std::string& vertices_points = std::string(), tmx::TileSet::Tile* tile = nullptr); public: //////////////////////////////////////////////////////////// /// \brief Change the color of the tile, affect the opacity. /// /// \param color sf::Color RGBA value /// //////////////////////////////////////////////////////////// void SetColor(const sf::Color& color); private: void draw(sf::RenderTarget& target, sf::RenderStates states) const; private: std::string name_; std::string type_; unsigned int x_, y_; unsigned int width_, height_; float rotation_; tmx::TileSet::Tile* tile_; std::vector<sf::Vertex> vertices_; public: /// \brief Visibility of the Object bool visible; }; } // namespace tmx #endif // STP_OBJECTGROUP_HPP
39.763006
119
0.525222
[ "object", "shape", "vector" ]
caaf6a56c911fc1ba47b4bc7bff1cb8971f2e92e
1,772
hpp
C++
srcs/common/itemprotectionbox.hpp
brooklet/heif
87d0427d750d882acba5f31bae697fe9a433ab50
[ "BSD-3-Clause" ]
9
2018-04-28T02:27:33.000Z
2021-11-24T16:04:36.000Z
srcs/common/itemprotectionbox.hpp
brooklet/heif
87d0427d750d882acba5f31bae697fe9a433ab50
[ "BSD-3-Clause" ]
1
2018-11-20T15:23:29.000Z
2018-11-21T05:10:58.000Z
srcs/common/itemprotectionbox.hpp
brooklet/heif
87d0427d750d882acba5f31bae697fe9a433ab50
[ "BSD-3-Clause" ]
1
2021-01-07T06:47:02.000Z
2021-01-07T06:47:02.000Z
/* This file is part of Nokia HEIF library * * Copyright (c) 2015-2018 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * * Contact: heif@nokia.com * * This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its subsidiaries. All rights are reserved. * * Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior written consent of Nokia. */ #ifndef ITEMPROTECTIONBOX_HPP #define ITEMPROTECTIONBOX_HPP #include "customallocator.hpp" #include "fullbox.hpp" #include "protectionschemeinfobox.hpp" /** Item Protection Box class * @details 'ipro' box implementation as specified in the ISOBMFF specification. */ class ItemProtectionBox : public FullBox { public: ItemProtectionBox(); virtual ~ItemProtectionBox() = default; /** @return Number of contained Protection Scheme Info Boxes */ std::uint16_t getProtectionCount() const; /** Get a ProtectionSchemeInfoBox box. * @param [in] index 0-based index of the box */ const ProtectionSchemeInfoBox& getEntry(std::uint16_t index) const; /** Add a new ProtectionSchemeInfoBox box. * @param [in] sinf The ProtectionSchemeInfoBox to add * @return 0-based index of the added box */ std::uint16_t addEntry(const ProtectionSchemeInfoBox& sinf); /** Write box to ISOBMFF::BitStream. * @see Box::writeBox() */ virtual void writeBox(ISOBMFF::BitStream& bitstream) const; /** Read box from ISOBMFF::BitStream. * @see Box::parseBox() */ virtual void parseBox(ISOBMFF::BitStream& bitstream); private: Vector<ProtectionSchemeInfoBox> mProtectionInformation; ///< 'sinf' boxes }; #endif /* ITEMPROTECTIONBOX_HPP */
34.076923
151
0.726862
[ "vector" ]
cab6a7cd2e55f2a97039ff4a7c270636de314cd5
14,565
cpp
C++
qt-solutions/qtscriptclassic/src/qscriptengineagent.cpp
privet56/qDesktopSearch
702aac770a11895e19180bd4ed2279c7a8ab64be
[ "Apache-2.0" ]
10
2016-04-15T15:31:08.000Z
2019-10-02T01:19:48.000Z
qt-solutions/qtscriptclassic/src/qscriptengineagent.cpp
privet56/qDesktopSearch
702aac770a11895e19180bd4ed2279c7a8ab64be
[ "Apache-2.0" ]
null
null
null
qt-solutions/qtscriptclassic/src/qscriptengineagent.cpp
privet56/qDesktopSearch
702aac770a11895e19180bd4ed2279c7a8ab64be
[ "Apache-2.0" ]
5
2016-04-15T15:31:10.000Z
2022-02-22T02:00:06.000Z
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Solutions component. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qscriptengineagent.h" #include "qscriptvalue.h" #include "qscriptengineagent_p.h" #include "qscriptengine_p.h" #include "qscriptcontext_p.h" #include "qscriptmember_p.h" #include "qscriptobject_p.h" #include "qscriptvalueimpl_p.h" QT_BEGIN_NAMESPACE /*! \since 4.4 \class QScriptEngineAgent \brief The QScriptEngineAgent class provides an interface to report events pertaining to QScriptEngine execution. \ingroup script \mainclass The QScriptEngineAgent class is the basis of tools that monitor and/or control the execution of a QScriptEngine, such as debuggers and profilers. To process script loading and unloading events, reimplement the scriptLoad() and scriptUnload() functions. scriptLoad() is called after the input to QScriptEngine::evaluate() has been parsed, right before the given script is executed. The engine assigns each script an ID, which is available as one of the arguments to scriptLoad(); subsequently, other event handlers can use the ID to identify a particular script. One common usage of scriptLoad() is to retain the script text, filename and base line number (the original input to QScriptEngine::evaluate()), so that other event handlers can e.g. map a line number to the corresponding line of text. scriptUnload() is called when the QScriptEngine has no further use for a script; the QScriptEngineAgent may at this point safely discard any resources associated with the script (such as the script text). Note that after scriptUnload() has been called, the QScriptEngine may reuse the relevant script ID for new scripts (i.e. as argument to a subsequent call to scriptLoad()). Evaluating the following script will result in scriptUnload() being called immediately after evaluation has completed: \snippet doc/src/snippets/code/src_script_qscriptengineagent.cpp 0 Evaluating the following script will \b{not} result in a call to scriptUnload() when evaluation has completed: \snippet doc/src/snippets/code/src_script_qscriptengineagent.cpp 1 The script isn't unloaded because it defines a function (\c{cube}) that remains in the script environment after evaluation has completed. If a subsequent script removed the \c{cube} function (e.g. by setting it to \c{null}), scriptUnload() would be called when the function is garbage collected. In general terms, a script isn't unloaded until the engine has determined that none of its contents is referenced. To process script function calls and returns, reimplement the functionEntry() and functionExit() functions. functionEntry() is called when a script function is about to be executed; functionExit() is called when a script function is about to return, either normally or due to an exception. To process individual script statements, reimplement positionChange(). positionChange() is called each time the engine is about to execute a new statement of a script, and thus offers the finest level of script monitoring. To process exceptions, reimplement exceptionThrow() and exceptionCatch(). exceptionThrow() is called when a script exception is thrown, before it has been handled. exceptionCatch() is called when an exception handler is present, and execution is about to be resumed at the handler code. \sa QScriptEngine::setAgent(), QScriptContextInfo */ /*! \enum QScriptEngineAgent::Extension This enum specifies the possible extensions to a QScriptEngineAgent. \value DebuggerInvocationRequest The agent handles \c{debugger} script statements. \sa extension() */ QScriptEngineAgentPrivate::QScriptEngineAgentPrivate() : engine(0), q_ptr(0) { } QScriptEngineAgentPrivate::~QScriptEngineAgentPrivate() { QScriptEnginePrivate *eng_p = QScriptEnginePrivate::get(engine); eng_p->agentDeleted(q_ptr); } /*! Constructs a QScriptEngineAgent object for the given \a engine. The engine takes ownership of the agent. Call QScriptEngine::setAgent() to make this agent the active agent. */ QScriptEngineAgent::QScriptEngineAgent(QScriptEngine *engine) : d_ptr(new QScriptEngineAgentPrivate) { d_ptr->q_ptr = this; d_ptr->engine = engine; } /*! \internal */ QScriptEngineAgent::QScriptEngineAgent(QScriptEngineAgentPrivate &dd, QScriptEngine *engine) : d_ptr(&dd) { d_ptr->q_ptr = this; d_ptr->engine = engine; } /*! Destroys this QScriptEngineAgent. */ QScriptEngineAgent::~QScriptEngineAgent() { delete d_ptr; d_ptr = 0; } /*! This function is called when the engine has parsed a script and has associated it with the given \a id. The id can be used to identify this particular script in subsequent event notifications. \a program, \a fileName and \a baseLineNumber are the original arguments to the QScriptEngine::evaluate() call that triggered this event. This function is called just before the script is about to be evaluated. You can reimplement this function to record information about the script; for example, by retaining the script text, you can obtain the line of text corresponding to a line number in a subsequent call to positionChange(). The default implementation does nothing. \sa scriptUnload() */ void QScriptEngineAgent::scriptLoad(qint64 id, const QString &program, const QString &fileName, int baseLineNumber) { Q_UNUSED(id); Q_UNUSED(program); Q_UNUSED(fileName); Q_UNUSED(baseLineNumber); } /*! This function is called when the engine has discarded the script identified by the given \a id. You can reimplement this function to clean up any resources you have associated with the script. The default implementation does nothing. \sa scriptLoad() */ void QScriptEngineAgent::scriptUnload(qint64 id) { Q_UNUSED(id); } /*! This function is called when a new script context has been pushed. The default implementation does nothing. \sa contextPop(), functionEntry() */ void QScriptEngineAgent::contextPush() { } /*! This function is called when the current script context is about to be popped. The default implementation does nothing. \sa contextPush(), functionExit() */ void QScriptEngineAgent::contextPop() { } /*! This function is called when a script function is called in the engine. If the script function is not a native Qt Script function, it resides in the script identified by \a scriptId; otherwise, \a scriptId is -1. This function is called just before execution of the script function begins. You can obtain the QScriptContext associated with the function call with QScriptEngine::currentContext(). The arguments passed to the function are available. Reimplement this function to handle this event. For example, a debugger implementation could reimplement this function (and functionExit()) to keep track of the call stack and provide step-over functionality. The default implementation does nothing. \sa functionExit(), positionChange(), QScriptEngine::currentContext() */ void QScriptEngineAgent::functionEntry(qint64 scriptId) { Q_UNUSED(scriptId); } /*! This function is called when the currently executing script function is about to return. If the script function is not a native Qt Script function, it resides in the script identified by \a scriptId; otherwise, \a scriptId is -1. The \a returnValue is the value that the script function will return. This function is called just before the script function returns. You can still access the QScriptContext associated with the script function call with QScriptEngine::currentContext(). If the engine's \l{QScriptEngine::hasUncaughtException()}{hasUncaughtException}() function returns true, the script function is exiting due to an exception; otherwise, the script function is returning normally. Reimplement this function to handle this event; typically you will then also want to reimplement functionEntry(). The default implementation does nothing. \sa functionEntry(), QScriptEngine::hasUncaughtException() */ void QScriptEngineAgent::functionExit(qint64 scriptId, const QScriptValue &returnValue) { Q_UNUSED(scriptId); Q_UNUSED(returnValue); } /*! This function is called when the engine is about to execute a new statement in the script identified by \a scriptId. The statement begins on the line and column specified by \a lineNumber and \a columnNumber. This event is not generated for native Qt Script functions. Reimplement this function to handle this event. For example, a debugger implementation could reimplement this function to provide line-by-line stepping, and a profiler implementation could use it to count the number of times each statement is executed. The default implementation does nothing. \sa scriptLoad(), functionEntry() */ void QScriptEngineAgent::positionChange(qint64 scriptId, int lineNumber, int columnNumber) { Q_UNUSED(scriptId); Q_UNUSED(lineNumber); Q_UNUSED(columnNumber); } /*! This function is called when the given \a exception has occurred in the engine, in the script identified by \a scriptId. If the exception was thrown by a native Qt Script function, \a scriptId is -1. If \a hasHandler is true, there is a \c{catch} or \c{finally} block that will handle the exception. If \a hasHandler is false, there is no handler for the exception. Reimplement this function if you want to handle this event. For example, a debugger can notify the user when an uncaught exception occurs (i.e. \a hasHandler is false). The default implementation does nothing. \sa exceptionCatch() */ void QScriptEngineAgent::exceptionThrow(qint64 scriptId, const QScriptValue &exception, bool hasHandler) { Q_UNUSED(scriptId); Q_UNUSED(exception); Q_UNUSED(hasHandler); } /*! This function is called when the given \a exception is about to be caught, in the script identified by \a scriptId. Reimplement this function if you want to handle this event. The default implementation does nothing. \sa exceptionThrow() */ void QScriptEngineAgent::exceptionCatch(qint64 scriptId, const QScriptValue &exception) { Q_UNUSED(scriptId); Q_UNUSED(exception); } #if 0 /*! This function is called when a property of the given \a object has been added, changed or removed. Reimplement this function if you want to handle this event. The default implementation does nothing. */ void QScriptEngineAgent::propertyChange(qint64 scriptId, const QScriptValue &object, const QString &propertyName, PropertyChange change) { Q_UNUSED(scriptId); Q_UNUSED(object); Q_UNUSED(propertyName); Q_UNUSED(change); } #endif /*! Returns true if the QScriptEngineAgent supports the given \a extension; otherwise, false is returned. By default, no extensions are supported. \sa extension() */ bool QScriptEngineAgent::supportsExtension(Extension extension) const { Q_UNUSED(extension); return false; } /*! This virtual function can be reimplemented in a QScriptEngineAgent subclass to provide support for extensions. The optional \a argument can be provided as input to the \a extension; the result must be returned in the form of a QVariant. You can call supportsExtension() to check if an extension is supported by the QScriptEngineAgent. By default, no extensions are supported, and this function returns an invalid QVariant. If you implement the DebuggerInvocationRequest extension, Qt Script will call this function when a \c{debugger} statement is encountered in a script. The \a argument is a QVariantList containing three items: The first item is the scriptId (a qint64), the second item is the line number (an int), and the third item is the column number (an int). \sa supportsExtension() */ QVariant QScriptEngineAgent::extension(Extension extension, const QVariant &argument) { Q_UNUSED(extension); Q_UNUSED(argument); return QVariant(); } /*! Returns the QScriptEngine that this agent is associated with. */ QScriptEngine *QScriptEngineAgent::engine() const { Q_D(const QScriptEngineAgent); return d->engine; } QT_END_NAMESPACE
32.878104
115
0.730793
[ "object" ]
cab8ae3c5d809b9e52c8c905ce27787a9e4639d0
12,389
cpp
C++
src/caffe/layers/anchors_layer.cpp
GuohongWu/caffe-windows-happynear
88602198ff6507909b8d2992efa79d8ec74d7dfe
[ "BSD-2-Clause" ]
2
2017-09-11T11:59:05.000Z
2021-05-08T13:12:57.000Z
src/caffe/layers/anchors_layer.cpp
GuohongWu/caffe-windows-happynear
88602198ff6507909b8d2992efa79d8ec74d7dfe
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/anchors_layer.cpp
GuohongWu/caffe-windows-happynear
88602198ff6507909b8d2992efa79d8ec74d7dfe
[ "BSD-2-Clause" ]
null
null
null
#include "caffe/layers/anchors_layer.hpp" #include "caffe/util/nms.hpp" #include <algorithm> #include <tuple> #define ROUND(x) ((int)((x) + (Dtype)0.5)) using std::max; using std::min; namespace caffe { template <typename Dtype> static void generate_anchors(int base_size, const Dtype ratios[], const Dtype scales[], const int num_ratios, const int num_scales, Dtype anchors[]) { // base box's width & height & center location const Dtype base_area = (Dtype)(base_size * base_size); const Dtype center = (Dtype)0.5 * (base_size - (Dtype)1); // enumerate all transformed boxes Dtype *p_anchors = anchors; for (int i = 0; i < num_ratios; ++i) { // transformed width & height for given ratio factors const Dtype ratio_w = (Dtype)(sqrt(base_area / ratios[i])); const Dtype ratio_h = (Dtype)(ratio_w * ratios[i]); for (int j = 0; j < num_scales; ++j) { // transformed width & height for given scale factors const Dtype scale_w = (Dtype)0.5 * ROUND(ratio_w * scales[j] * 1.0 - (Dtype)1); const Dtype scale_h = (Dtype)0.5 * ROUND(ratio_h * scales[j] * 1.0 - (Dtype)1); // (x1, y1, x2, y2) for transformed box p_anchors[0] = center - scale_w; p_anchors[1] = center - scale_h; p_anchors[2] = center + scale_w; p_anchors[3] = center + scale_h; p_anchors += 4; } // endfor j } } template <typename Dtype> void AnchorsLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top) { AnchorsParameter param = this->layer_param_.anchors_param(); anchor_stride_ = param.anchor_stride(); base_size_ = param.base_size(); nms_upper_thresh_ = param.nms_upper_thresh(); nms_lower_thresh_ = param.nms_lower_thresh(); vector<Dtype> ratios(param.ratio_size()); for (int i = 0; i < param.ratio_size(); ++i) { ratios[i] = param.ratio(i); } vector<Dtype> scales(param.scale_size()); for (int i = 0; i < param.scale_size(); ++i) { scales[i] = param.scale(i); } vector<int> anchors_shape(2); anchors_shape[0] = ratios.size() * scales.size(); anchors_shape[1] = 4; anchors_0_0_.Reshape(anchors_shape); caffe::generate_anchors(base_size_, &ratios[0], &scales[0], ratios.size(), scales.size(), anchors_0_0_.mutable_cpu_data()); } template <typename Dtype> void AnchorsLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int batch_size = bottom[0]->num(); int anchor_map_H = ceilf(float(bottom[0]->height()) / this->anchor_stride_); int anchor_map_W = ceilf(float(bottom[0]->width()) / this->anchor_stride_); int anchor_nums = anchors_0_0_.num(); top[0]->Reshape(batch_size, anchor_nums, anchor_map_H, anchor_map_W); // label_map top[1]->Reshape(batch_size, 4 * anchor_nums, anchor_map_H, anchor_map_W); // reg_map if(this->layer_param_.top_size() >= 3) { top[2]->Reshape(1, 4, 1, 1); // img_info Dtype* top2_data = top[2]->mutable_cpu_data(); top2_data[0] = bottom[0]->height(); top2_data[1] = bottom[0]->width(); top2_data[2] = 1; top2_data[3] = 1; } // top[3] output max-IoU corre to each anchors. (For debug) if (this->layer_param_.top_size() >= 4) { top[3]->Reshape(batch_size, 5 * anchor_nums, anchor_map_H, anchor_map_W); } } template <typename Dtype> void AnchorsLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top) { int nums = top[0]->num(); int anchor_nums = top[0]->channels(); int height = top[0]->height(); int width = top[0]->width(); int feature_map_area = height * width; int anchor_counts = anchor_nums * feature_map_area; Dtype* top0_data = top[0]->mutable_cpu_data(); Dtype* top1_data = top[1]->mutable_cpu_data(); caffe_set(top[0]->count(), Dtype(-1), top0_data); const Dtype* bbox_start_loc = bottom[1]->cpu_data(); const Dtype* bbox_data = bottom[2]->cpu_data(); int bbox_data_dim_ = bottom[2]->count(1); const Dtype* anchors_data_ = this->anchors_0_0_.cpu_data(); Dtype curAnc[4]; for (int n = 0; n < nums; ++n) { int bbox_end_loc_ = ((n + 1 == nums) ? bottom[2]->num() : bbox_start_loc[n + 1]); vector<bool> bbox_bind_to_noAnc(bbox_end_loc_ - bbox_start_loc[n], false); // 1.assign each anchor to the unique face with highest IoU. Meanwhile, this IoU must be larger than a threshold (e.g. nms_upper_thresh_) int offset_0_first = -1 + n * anchor_counts; for (int c = 0; c < anchor_nums; ++c) { for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { ++offset_0_first; std::copy(anchors_data_ + 4 * c, anchors_data_ + 4 * (c + 1), curAnc); curAnc[0] += w * this->anchor_stride_; curAnc[1] += h * this->anchor_stride_; curAnc[2] += w * this->anchor_stride_; curAnc[3] += h * this->anchor_stride_; if (curAnc[0] < 0 || curAnc[2] > bottom[0]->width() || curAnc[1] < 0 || curAnc[3] > bottom[0]->height()) { // cross-boundary anchors are ignored. *(top0_data + offset_0_first) = -2; // Temporarily assgin to -2, to distinguish. continue; } Dtype max_iou = 0; int max_bbox_idx = -1; for (int k = bbox_start_loc[n]; k < bbox_end_loc_; ++k) { Dtype cur_iou = IoU_cpu(bbox_data + k * bbox_data_dim_, curAnc); if (cur_iou > max_iou) { max_iou = cur_iou; max_bbox_idx = k; } else if (cur_iou == max_iou && max_iou > 0) { if(caffe::caffe_rng_rand() % 2) max_bbox_idx = k; } } if (max_iou > this->nms_upper_thresh_) { *(top0_data + offset_0_first) = max_bbox_idx + 1; bbox_bind_to_noAnc[max_bbox_idx - bbox_start_loc[n]] = true; for (int pos = 0; pos < 4; ++pos) { int offset_1 = top[1]->offset(n, pos * anchor_nums + c, h, w); *(top1_data + offset_1) = curAnc[pos]; } } else if (max_iou < this->nms_lower_thresh_) { *(top0_data + offset_0_first) = 0; // sure to be background! } } } } // 2. For other Bboxes and other Anchors, Assign each bboxes to the anchor(s) with highest Intersection - overUnion(IoU) overlap vector<std::tuple<Dtype, int, vector<int> > > bbox_corres_anchors; for (int k = bbox_start_loc[n]; k < bbox_end_loc_; ++k) { if (bbox_bind_to_noAnc[k - bbox_start_loc[n]]) continue; bbox_corres_anchors.emplace_back(0, k + 1, vector<int>()); vector<int>& max_offset_idn = std::get<2>(bbox_corres_anchors.back()); Dtype& max_iou = std::get<0>(bbox_corres_anchors.back()); //vector<int> max_offset_idn; int offset_0_second = -1 + n * anchor_counts; for (int c = 0; c < anchor_nums; ++c) { for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { int curBbox_idx = *(top0_data + (++offset_0_second)); if (curBbox_idx > 0 || (curBbox_idx == 0 && max_iou >= this->nms_lower_thresh_) || curBbox_idx == -2) continue; std::copy(anchors_data_ + 4 * c, anchors_data_ + 4 * (c + 1), curAnc); curAnc[0] += w * this->anchor_stride_; curAnc[1] += h * this->anchor_stride_; curAnc[2] += w * this->anchor_stride_; curAnc[3] += h * this->anchor_stride_; Dtype cur_iou = IoU_cpu(bbox_data + k * bbox_data_dim_, curAnc); if (cur_iou > max_iou) { max_iou = cur_iou; max_offset_idn.clear(); max_offset_idn.push_back(offset_0_second); } else if (cur_iou == max_iou && max_iou > 0) { max_offset_idn.push_back(offset_0_second); } } } } } std::sort(bbox_corres_anchors.begin(), bbox_corres_anchors.end(), [](const std::tuple<Dtype, int, vector<int> >& A, const std::tuple<Dtype, int, vector<int> >& B) -> bool { return std::get<0>(A) > std::get<0>(B); }); for (auto &curBbox_corres : bbox_corres_anchors) { for (auto &cur_offset0 : std::get<2>(curBbox_corres)) { if (*(top0_data + cur_offset0) > 0) continue; *(top0_data + cur_offset0) = std::get<1>(curBbox_corres); int chan_ = cur_offset0 % anchor_counts / feature_map_area; int w_ = cur_offset0 % feature_map_area % width; int h_ = cur_offset0 % feature_map_area / width; std::copy(anchors_data_ + 4 * chan_, anchors_data_ + 4 * (chan_ + 1), curAnc); curAnc[0] += w_ * this->anchor_stride_; curAnc[1] += h_ * this->anchor_stride_; curAnc[2] += w_ * this->anchor_stride_; curAnc[3] += h_ * this->anchor_stride_; for (int pos = 0; pos < 4; ++pos) { int offset_1 = top[1]->offset(n, pos * anchor_nums + chan_, h_, w_); *(top1_data + offset_1) = curAnc[pos]; } } } // 3. compute transform params and classes int offset_1[4]; for (int c = 0; c < anchor_nums; ++c) { for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { int offset_0 = top[0]->offset(n, c, h, w); int curBbox_idx = *(top0_data + offset_0); if (--curBbox_idx >= 0) { const Dtype* bbox_data_gt = bbox_data + curBbox_idx * bbox_data_dim_; *(top0_data + offset_0) = *(bbox_data_gt + 4); for (int pos = 0; pos < 4; ++pos) offset_1[pos] = top[1]->offset(n, pos * anchor_nums + c, h, w); // get the transform parameters from the box to gbox Dtype src_w = std::max(*(top1_data + offset_1[2]) - *(top1_data + offset_1[0]) + (Dtype)1, (Dtype)1); Dtype src_h = std::max(*(top1_data + offset_1[3]) - *(top1_data + offset_1[1]) + (Dtype)1, (Dtype)1); Dtype src_cenx = *(top1_data + offset_1[0]) + (Dtype)0.5 * src_w; Dtype src_ceny = *(top1_data + offset_1[1]) + (Dtype)0.5 * src_h; Dtype tar_w = std::max(bbox_data_gt[2] - bbox_data_gt[0] + (Dtype)1, (Dtype)1); Dtype tar_h = std::max(bbox_data_gt[3] - bbox_data_gt[1] + (Dtype)1, (Dtype)1); Dtype tar_cenx = bbox_data_gt[0] + (Dtype)0.5 * tar_w; Dtype tar_ceny = bbox_data_gt[1] + (Dtype)0.5 * tar_h; *(top1_data + offset_1[0]) = (tar_cenx - src_cenx) / src_w; *(top1_data + offset_1[1]) = (tar_ceny - src_ceny) / src_h; *(top1_data + offset_1[2]) = std::log(tar_w / src_w); *(top1_data + offset_1[3]) = std::log(tar_h / src_h); //caffe::get_transform_params(top1_data + offset_1, bbox_data + curBbox_idx * bbox_data_dim_, top1_data + offset_1); } else if (curBbox_idx == -3) *(top0_data + offset_0) = -1; } } } } // For debug if (this->layer_param_.top_size() == 4) { Dtype* top3_data = top[3]->mutable_cpu_data(); for (int n = 0; n < nums; ++n) { for (int c = 0; c < anchor_nums; ++c) { for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { std::copy(anchors_data_ + 4 * c, anchors_data_ + 4 * (c + 1), curAnc); curAnc[0] += w * this->anchor_stride_; curAnc[1] += h * this->anchor_stride_; curAnc[2] += w * this->anchor_stride_; curAnc[3] += h * this->anchor_stride_; for (int pos = 1; pos < 5; ++pos) { int offset_3 = top[3]->offset(n, pos * anchor_nums + c, h, w); *(top3_data + offset_3) = curAnc[pos - 1]; } Dtype max_iou = 0; for (int k = bbox_start_loc[n]; k < ((n + 1 == nums) ? bottom[2]->num() : bbox_start_loc[n + 1]); ++k) { Dtype cur_iou = IoU_cpu(bbox_data + k * bbox_data_dim_, curAnc); if (cur_iou > max_iou) { max_iou = cur_iou; } } int offset_3 = top[3]->offset(n, c, h, w); *(top3_data + offset_3) = Dtype(max_iou); } } } } } //int bigger_than_zero_counts = 0; //for(int i = 0; i < top[0]->count(); ++i) // if(top[0]->cpu_data()[i] > 0) // ++bigger_than_zero_counts; //if(bigger_than_zero_counts == 0) { // for(int i = 0; i < bottom[1]->count(); ++i) // LOG(INFO) << bottom[1]->cpu_data()[i]; // // LOG(INFO) << '\n'; // for(int i = 0; i < bottom[2]->count(); ++i) // LOG(INFO) << bottom[2]->cpu_data()[i]; //} //CHECK_GT(bigger_than_zero_counts, 0) << "There must exist at least one anchor(s) matching any bounding boxes."; } template <typename Dtype> void AnchorsLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } #ifdef CPU_ONLY STUB_GPU(AnchorsLayer); #endif INSTANTIATE_CLASS(AnchorsLayer); REGISTER_LAYER_CLASS(Anchors); }
37.542424
219
0.608927
[ "vector", "transform" ]
cabba33de6f1829457511e606e5391d6c60c488d
7,453
cc
C++
v8js_array_access.cc
petk/v8js
6fc0c216d8e1256b42b719c5a645ac4485e3ed4c
[ "MIT" ]
null
null
null
v8js_array_access.cc
petk/v8js
6fc0c216d8e1256b42b719c5a645ac4485e3ed4c
[ "MIT" ]
null
null
null
v8js_array_access.cc
petk/v8js
6fc0c216d8e1256b42b719c5a645ac4485e3ed4c
[ "MIT" ]
1
2021-07-19T19:15:25.000Z
2021-07-19T19:15:25.000Z
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2017 The PHP Group | +----------------------------------------------------------------------+ | http://www.opensource.org/licenses/mit-license.php MIT License | +----------------------------------------------------------------------+ | Author: Stefan Siegl <stesie@php.net> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php_v8js_macros.h" #include "v8js_array_access.h" #include "v8js_exceptions.h" #include "v8js_object_export.h" extern "C" { #include "php.h" #include "ext/date/php_date.h" #include "ext/standard/php_string.h" #include "zend_interfaces.h" #include "zend_closures.h" #include "zend_exceptions.h" } static zval v8js_array_access_dispatch(zend_object *object, const char *method_name, int param_count, uint32_t index, zval zvalue) /* {{{ */ { zend_fcall_info fci; zval php_value; fci.size = sizeof(fci); #if (PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 0) fci.function_table = &object->ce->function_table; fci.symbol_table = NULL; #endif ZVAL_STRING(&fci.function_name, method_name); fci.retval = &php_value; zval params[2]; ZVAL_LONG(&params[0], index); params[1] = zvalue; fci.param_count = param_count; fci.params = params; fci.object = object; fci.no_separation = 0; zend_call_function(&fci, NULL); zval_dtor(&fci.function_name); return php_value; } /* }}} */ void v8js_array_access_getter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */ { v8::Isolate *isolate = info.GetIsolate(); v8::Local<v8::Object> self = info.Holder(); zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1)); zval zvalue; ZVAL_UNDEF(&zvalue); zval php_value = v8js_array_access_dispatch(object, "offsetGet", 1, index, zvalue); v8::Local<v8::Value> ret_value = zval_to_v8js(&php_value, isolate); zval_ptr_dtor(&php_value); info.GetReturnValue().Set(ret_value); } /* }}} */ void v8js_array_access_setter(uint32_t index, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */ { v8::Isolate *isolate = info.GetIsolate(); v8::Local<v8::Object> self = info.Holder(); zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1)); zval zvalue; ZVAL_UNDEF(&zvalue); if (v8js_to_zval(value, &zvalue, 0, isolate) != SUCCESS) { info.GetReturnValue().Set(v8::Local<v8::Value>()); return; } zval php_value = v8js_array_access_dispatch(object, "offsetSet", 2, index, zvalue); zval_ptr_dtor(&php_value); /* simply pass back the value to tell we intercepted the call * as the offsetSet function returns void. */ info.GetReturnValue().Set(value); /* if PHP wanted to hold on to this value, zend_call_function would * have bumped the refcount. */ zval_ptr_dtor(&zvalue); } /* }}} */ static int v8js_array_access_get_count_result(zend_object *object) /* {{{ */ { zval zvalue; ZVAL_UNDEF(&zvalue); zval php_value = v8js_array_access_dispatch(object, "count", 0, 0, zvalue); if(Z_TYPE(php_value) != IS_LONG) { php_error_docref(NULL, E_WARNING, "Non-numeric return value from count() method"); zval_ptr_dtor(&php_value); return 0; } zend_long result = Z_LVAL(php_value); if (result > std::numeric_limits<int>::max()) { zend_throw_exception(php_ce_v8js_exception, "Array size/offset exceeds maximum supported length", 0); return 0; } return static_cast<int>(result); } /* }}} */ static bool v8js_array_access_isset_p(zend_object *object, int index) /* {{{ */ { zval zvalue; ZVAL_UNDEF(&zvalue); zval php_value = v8js_array_access_dispatch(object, "offsetExists", 1, index, zvalue); if(Z_TYPE(php_value) != IS_TRUE && Z_TYPE(php_value) != IS_FALSE) { php_error_docref(NULL, E_WARNING, "Non-boolean return value from offsetExists() method"); zval_ptr_dtor(&php_value); return false; } return Z_TYPE(php_value) == IS_TRUE; } /* }}} */ static void v8js_array_access_length(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& info) /* {{{ */ { v8::Isolate *isolate = info.GetIsolate(); v8::Local<v8::Object> self = info.Holder(); zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1)); int length = v8js_array_access_get_count_result(object); info.GetReturnValue().Set(V8JS_INT(length)); } /* }}} */ void v8js_array_access_deleter(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info) /* {{{ */ { v8::Isolate *isolate = info.GetIsolate(); v8::Local<v8::Object> self = info.Holder(); zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1)); zval zvalue; ZVAL_UNDEF(&zvalue); zval php_value = v8js_array_access_dispatch(object, "offsetUnset", 1, index, zvalue); zval_ptr_dtor(&php_value); info.GetReturnValue().Set(V8JS_BOOL(true)); } /* }}} */ void v8js_array_access_query(uint32_t index, const v8::PropertyCallbackInfo<v8::Integer>& info) /* {{{ */ { v8::Isolate *isolate = info.GetIsolate(); v8::Local<v8::Object> self = info.Holder(); zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1)); /* If index is set, then return an integer encoding a v8::PropertyAttribute; * otherwise we're expected to return an empty handle. */ if(v8js_array_access_isset_p(object, index)) { info.GetReturnValue().Set(V8JS_UINT(v8::PropertyAttribute::None)); } } /* }}} */ void v8js_array_access_enumerator(const v8::PropertyCallbackInfo<v8::Array>& info) /* {{{ */ { v8::Isolate *isolate = info.GetIsolate(); v8::Local<v8::Object> self = info.Holder(); zend_object *object = reinterpret_cast<zend_object *>(self->GetAlignedPointerFromInternalField(1)); int length = v8js_array_access_get_count_result(object); v8::Local<v8::Array> result = v8::Array::New(isolate, length); int i = 0; for(int j = 0; j < length; j ++) { if(v8js_array_access_isset_p(object, j)) { result->Set(i ++, V8JS_INT(j)); } } result->Set(V8JS_STR("length"), V8JS_INT(i)); info.GetReturnValue().Set(result); } /* }}} */ void v8js_array_access_named_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */ { v8::String::Utf8Value cstr(property); const char *name = ToCString(cstr); if(strcmp(name, "length") == 0) { v8js_array_access_length(property, info); return; } v8::Local<v8::Value> ret_value = v8js_named_property_callback(property, info, V8JS_PROP_GETTER); if(ret_value.IsEmpty()) { v8::Isolate *isolate = info.GetIsolate(); v8::Local<v8::Array> arr = v8::Array::New(isolate); v8::Local<v8::Value> prototype = arr->GetPrototype(); if(!prototype->IsObject()) { /* ehh? Array.prototype not an object? strange, stop. */ info.GetReturnValue().Set(ret_value); } ret_value = prototype->ToObject()->Get(property); } info.GetReturnValue().Set(ret_value); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
28.446565
127
0.660271
[ "object" ]
cabcb64d0141d0dae2924f33890bbafa40c70df9
10,014
cpp
C++
src/engine/components/replay/cl_screenshotmanager.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/components/replay/cl_screenshotmanager.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/components/replay/cl_screenshotmanager.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // //=======================================================================================// #include "cl_screenshotmanager.h" #include "replay/screenshot.h" #include "replaysystem.h" #include "cl_replaymanager.h" #include "replay/replayutils.h" #include "replay/ireplayscreenshotsystem.h" #include "gametrace.h" #include "icliententity.h" #include "imageutils.h" #include "filesystem.h" #include "fmtstr.h" #include "vprof.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //---------------------------------------------------------------------------------------- #define SCREENSHOTS_SUBDIR "screenshots" //---------------------------------------------------------------------------------------- CScreenshotManager::CScreenshotManager() : m_flLastScreenshotTime(0.0f), m_hScreenshotReplay(REPLAY_HANDLE_INVALID) { } CScreenshotManager::~CScreenshotManager() { } bool CScreenshotManager::Init() { // Create thumbnails directory CFmtStr fmtThumbnailsPath( "%s%cmaterials%cvgui%creplay%cthumbnails", g_pEngine->GetGameDir(), CORRECT_PATH_SEPARATOR, CORRECT_PATH_SEPARATOR, CORRECT_PATH_SEPARATOR, CORRECT_PATH_SEPARATOR ); g_pFullFileSystem->CreateDirHierarchy(fmtThumbnailsPath.Access()); // Compute all possible resolutions if first time we're running this function for (int iAspect = 0; iAspect < 3; ++iAspect) { for (int iRes = 0; iRes < 2; ++iRes) { int nWidth = (int) FastPow2(9 + iRes); m_aScreenshotWidths[iAspect][iRes] = nWidth; } } // Set current screenshot dims to 0 - screenshot cache will be created first time we see // proper screen dimensions m_nPrevScreenDims[0] = 0; m_nPrevScreenDims[1] = 0; // Initialize screenshot taker in client g_pClient->GetReplayScreenshotSystem()->UpdateReplayScreenshotCache(); return true; } float CScreenshotManager::GetNextThinkTime() const { return 0.0f; } void CScreenshotManager::Think() { VPROF_BUDGET("CScreenshotManager::Think", VPROF_BUDGETGROUP_REPLAY); // // NOTE:DoCaptureScreenshot() gets called from CReplaySystem::CL_Render() // IReplayScreenshotSystem *pScreenshotSystem = g_pClient->GetReplayScreenshotSystem(); Assert(pScreenshotSystem); // Check to see if screen resolution changed, and if so, update the client-side screenshot cache. int nScreenWidth = g_pEngineClient->GetScreenWidth(); int nScreenHeight = g_pEngineClient->GetScreenHeight(); if (!CL_GetMovieManager()->IsRendering() && (m_nPrevScreenDims[0] != nScreenWidth || m_nPrevScreenDims[1] != nScreenHeight)) { if (m_nPrevScreenDims[0] != 0) // If this is not the first update { pScreenshotSystem->UpdateReplayScreenshotCache(); } m_nPrevScreenDims[0] = nScreenWidth; m_nPrevScreenDims[1] = nScreenHeight; } } bool CScreenshotManager::ShouldCaptureScreenshot() { // Record a screenshot if its been setup return (m_flScreenshotCaptureTime >= 0.0f && m_flScreenshotCaptureTime <= g_pEngine->GetHostTime()); } void CScreenshotManager::CaptureScreenshot(CaptureScreenshotParams_t &params) { extern ConVar replay_enableeventbasedscreenshots; if (!replay_enableeventbasedscreenshots.GetBool() && !params.m_bPrimary) return; // Schedule screenshot m_flScreenshotCaptureTime = g_pEngine->GetHostTime() + params.m_flDelay; // Cache parameters for when we take the screenshot V_memcpy(&m_screenshotParams, &params, sizeof(params)); } void CScreenshotManager::DoCaptureScreenshot() { // Reset screenshot capture schedule time, even if we don't end up actually taking the screenshot m_flScreenshotCaptureTime = -1.0f; // Make sure we're in-game if (!g_pEngineClient->IsConnected()) return; // Get a pointer to the replay CReplay *pReplay = ::GetReplay(m_hScreenshotReplay); if (!pReplay) { AssertMsg(0, "Failed to take screenshot!\n"); return; } // Max # of screenshots already taken? extern ConVar replay_maxscreenshotsperreplay; int nScreenshotLimit = replay_maxscreenshotsperreplay.GetInt(); if (nScreenshotLimit && pReplay->GetScreenshotCount() >= nScreenshotLimit) return; // If not enough time has passed since the last screenshot was taken, get out extern ConVar replay_mintimebetweenscreenshots; if (!m_screenshotParams.m_bIgnoreMinTimeBetweenScreenshots && (g_pEngine->GetHostTime() - m_flLastScreenshotTime < replay_mintimebetweenscreenshots.GetInt())) return; // Update last screenshot taken time m_flLastScreenshotTime = g_pEngine->GetHostTime(); // Setup screenshot base filename as <.dem base filename>_<N> char szBaseFilename[MAX_OSPATH]; char szIdealBaseFilename[MAX_OSPATH]; V_strcpy_safe(szIdealBaseFilename, CL_GetRecordingSessionManager()->m_ServerRecordingState.m_strSessionName.Get()); Replay_GetFirstAvailableFilename(szBaseFilename, sizeof(szBaseFilename), szIdealBaseFilename, ".vtf", "materials\\vgui\\replay\\thumbnails", pReplay->GetScreenshotCount()); // Remove extension int i = V_strlen(szBaseFilename) - 1; while (i >= 0) { if (szBaseFilename[i] == '.') break; --i; } szBaseFilename[i] = '\0'; // Get destination file char szScreenshotPath[MAX_OSPATH]; V_snprintf(szScreenshotPath, sizeof(szScreenshotPath), "materials\\vgui\\replay\\thumbnails\\%s.vtf", szBaseFilename); // Make sure we're using the correct path separator V_FixSlashes(szScreenshotPath); // Setup screenshot dimensions int nScreenshotDims[2]; GetUnpaddedScreenshotSize(nScreenshotDims[0], nScreenshotDims[1]); // Setup parameters for screenshot WriteReplayScreenshotParams_t params; V_memset(&params, 0, sizeof(params)); // Setup the camera Vector origin; QAngle angles; if (m_screenshotParams.m_nEntity > 0) { IClientEntity *pEntity = entitylist->GetClientEntity(m_screenshotParams.m_nEntity); if (pEntity) { // Clip the camera position if any world geometry is in the way trace_t trace; Ray_t ray; CTraceFilterWorldAndPropsOnly traceFilter; Vector vStartPos = pEntity->GetAbsOrigin(); ray.Init(vStartPos, pEntity->GetAbsOrigin() + m_screenshotParams.m_posCamera); g_pEngineTraceClient->TraceRay(ray, MASK_PLAYERSOLID, &traceFilter, &trace); // Setup world position and angles for camera origin = trace.endpos; if (trace.DidHit()) { float d = 5; // The distance to push in if we Vector dir = trace.endpos - vStartPos; VectorNormalize(dir); origin -= Vector(d * dir.x, d * dir.y, d * dir.z); } // Use the new camera origin params.m_pOrigin = &origin; // Use angles too if appropriate if (m_screenshotParams.m_bUseCameraAngles) { angles = m_screenshotParams.m_angCamera; params.m_pAngles = &angles; } } } // Write the screenshot to disk params.m_nWidth = nScreenshotDims[0]; params.m_nHeight = nScreenshotDims[1]; params.m_pFilename = szScreenshotPath; g_pClient->GetReplayScreenshotSystem()->WriteReplayScreenshot(params); // Write a generic VMT char szVTFFullPath[MAX_OSPATH]; V_snprintf(szVTFFullPath, sizeof(szVTFFullPath), "%s\\materials\\vgui\\replay\\thumbnails\\%s.vtf", g_pEngine->GetGameDir(), szBaseFilename); V_FixSlashes(szVTFFullPath); ImgUtl_WriteGenericVMT(szVTFFullPath, "vgui/replay/thumbnails"); // Create the new screenshot info pReplay->AddScreenshot(nScreenshotDims[0], nScreenshotDims[1], szBaseFilename); } void CScreenshotManager::DeleteScreenshotsForReplay(CReplay *pReplay) { char szFilename[MAX_OSPATH]; for (int i = 0; i < pReplay->GetScreenshotCount(); ++i) { const CReplayScreenshot *pScreenshot = pReplay->GetScreenshot(i); // Delete the VGUI thumbnail VTF V_snprintf(szFilename, sizeof(szFilename), "materials\\vgui\\replay\\thumbnails\\%s.vtf", pScreenshot->m_szBaseFilename); V_FixSlashes(szFilename); g_pFullFileSystem->RemoveFile(szFilename); // Delete the VGUI thumbnail VMT V_snprintf(szFilename, sizeof(szFilename), "materials\\vgui\\replay\\thumbnails\\%s.vmt", pScreenshot->m_szBaseFilename); V_FixSlashes(szFilename); g_pFullFileSystem->RemoveFile(szFilename); } } void CScreenshotManager::GetUnpaddedScreenshotSize(int &nOutWidth, int &nOutHeight) { // Figure out the proper screenshot size to use based on the aspect ratio int nScreenWidth = g_pEngineClient->GetScreenWidth(); int nScreenHeight = g_pEngineClient->GetScreenHeight(); float flAspectRatio = (float) nScreenWidth / nScreenHeight; // Get the screenshot res extern ConVar replay_screenshotresolution; int iRes = clamp(replay_screenshotresolution.GetInt(), 0, 1); int iAspect; if (flAspectRatio == 16.0f / 9) { iAspect = 0; } else if (flAspectRatio == 16.0f / 10) { iAspect = 1; } else { iAspect = 2; // 4:3 } static float s_flInvAspectRatios[3] = {9.0f / 16.0f, 10.0f / 16, 3.0f / 4}; nOutWidth = min(nScreenWidth, m_aScreenshotWidths[iAspect][iRes]); nOutHeight = m_aScreenshotWidths[iAspect][iRes] * s_flInvAspectRatios[iAspect]; } void CScreenshotManager::SetScreenshotReplay(ReplayHandle_t hReplay) { m_hScreenshotReplay = hReplay; } //----------------------------------------------------------------------------------------
36.95203
119
0.65688
[ "geometry", "vector" ]
cabdc126a8bf2ad02981ae91eb17a88861742b9a
5,754
hpp
C++
Sources/Renderer/Pipelines/ShaderProgram.hpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
1
2019-03-13T08:26:38.000Z
2019-03-13T08:26:38.000Z
Sources/Renderer/Pipelines/ShaderProgram.hpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
null
null
null
Sources/Renderer/Pipelines/ShaderProgram.hpp
hhYanGG/Acid
f5543e9290aee5e25c6ecdafe8a3051054b203c0
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <sstream> #include <string> #include <vector> #include <vulkan/vulkan.h> #include "PipelineCreate.hpp" namespace glslang { class TProgram; } namespace acid { class ACID_EXPORT Uniform { private: std::string m_name; int m_binding; int m_offset; int m_size; int m_glType; VkShaderStageFlags m_stageFlags; public: Uniform(const std::string &name, const int &binding, const int &offset, const int &size, const int &glType, const VkShaderStageFlags &stageFlags) : m_name(name), m_binding(binding), m_offset(offset), m_size(size), m_glType(glType), m_stageFlags(stageFlags) { } ~Uniform() { } std::string GetName() const { return m_name; } int GetBinding() const { return m_binding; } int GetOffset() const { return m_offset; } int GetSize() const { return m_size; } int GetGlType() const { return m_glType; } VkShaderStageFlags GetStageFlags() const { return m_stageFlags; } void SetStageFlags(const VkShaderStageFlags &stageFlags) { m_stageFlags = stageFlags; } bool operator==(const Uniform &other) const { return m_name == other.m_name && m_binding == other.m_binding && m_offset == other.m_offset && m_glType == other.m_glType; } bool operator!=(const Uniform &other) const { return !(*this == other); } std::string ToString() const { std::stringstream result; result << "Uniform(name '" << m_name << "', binding " << m_binding << ", offset " << m_offset << ", size " << m_size << ", glType " << m_glType << ")"; return result.str(); } }; class ACID_EXPORT UniformBlock { private: std::string m_name; int m_binding; int m_size; VkShaderStageFlags m_stageFlags; std::vector<Uniform *> *m_uniforms; public: UniformBlock(const std::string &name, const int &binding, const int &size, const VkShaderStageFlags &stageFlags) : m_name(name), m_binding(binding), m_size(size), m_stageFlags(stageFlags), m_uniforms(new std::vector<Uniform *>()) { } ~UniformBlock() { delete m_uniforms; } void AddUniform(Uniform *uniform) { for (auto &u : *m_uniforms) { if (*u == *uniform) { return; } } m_uniforms->emplace_back(uniform); } Uniform *GetUniform(const std::string &uniformName) { for (auto &uniform : *m_uniforms) { if (uniform->GetName() == uniformName) { return uniform; } } return nullptr; } std::string GetName() const { return m_name; } int GetBinding() const { return m_binding; } int GetSize() const { return m_size; } VkShaderStageFlags GetStageFlags() const { return m_stageFlags; } void SetStageFlags(const VkShaderStageFlags &stageFlags) { m_stageFlags = stageFlags; } std::vector<Uniform *> *GetUniforms() const { return m_uniforms; } std::string ToString() const { std::stringstream result; result << "UniformBlock(name '" << m_name << "', binding " << m_binding << ", size " << m_size << ")"; return result.str(); } }; class ACID_EXPORT VertexAttribute { private: std::string m_name; int m_location; int m_size; int m_glType; public: VertexAttribute(const std::string &name, const int &location, const int &size, const int &glType) : m_name(name), m_location(location), m_size(size), m_glType(glType) { } ~VertexAttribute() { } std::string GetName() const { return m_name; } int GetLocation() const { return m_location; } int GetSize() const { return m_size; } int GetGlType() const { return m_glType; } std::string ToString() const { std::stringstream result; result << "VertexAttribute(name '" << m_name << "', location " << m_location << ", size " << m_size << ", glType " << m_glType << ")"; return result.str(); } }; class ACID_EXPORT ShaderProgram { private: std::string m_name; std::vector<Uniform *> m_uniforms; std::vector<UniformBlock *> m_uniformBlocks; std::vector<VertexAttribute *> m_vertexAttributes; std::vector<DescriptorType> m_descriptors; std::vector<VkVertexInputAttributeDescription> m_attributeDescriptions; std::vector<std::string> m_notFoundNames; public: ShaderProgram(const std::string &name); ~ShaderProgram(); std::string GetName() const { return m_name; } bool ReportedNotFound(const std::string &name, const bool &reportIfFound); void ProcessShader(); VkFormat GlTypeToVk(const int &type); int GetDescriptorLocation(const std::string &descriptor); Uniform *GetUniform(const std::string &uniformName); UniformBlock *GetUniformBlock(const std::string &blockName); VertexAttribute *GetVertexAttribute(const std::string &attributeName); std::vector<DescriptorType> GetDescriptors() const { return m_descriptors; } uint32_t GetLastDescriptorBinding() const; std::vector<VkVertexInputAttributeDescription> GetAttributeDescriptions() const { return m_attributeDescriptions; } static VkShaderStageFlagBits GetShaderStage(const std::string &filename); static std::string InsertDefineBlock(const std::string &shaderCode, const std::string &blockCode); static std::string ProcessIncludes(const std::string &shaderCode); VkShaderModule ProcessShader(const std::string &shaderCode, const VkShaderStageFlags &stageFlag); std::string ToString() const; private: void LoadProgram(const glslang::TProgram &program, const VkShaderStageFlags &stageFlag); void LoadUniformBlock(const glslang::TProgram &program, const VkShaderStageFlags &stageFlag, const int &i); void LoadUniform(const glslang::TProgram &program, const VkShaderStageFlags &stageFlag, const int &i); void LoadVertexAttribute(const glslang::TProgram &program, const VkShaderStageFlags &stageFlag, const int &i); }; }
24.278481
154
0.695864
[ "vector" ]
cac453f5e444a6eb849d82aa83a6e07261b2a018
3,345
cpp
C++
clone-graph_test.cpp
babu-thomas/interviewbit-solutions
21125bf30b2d94b6f03310a4917679f216f55af3
[ "MIT" ]
16
2018-12-04T16:23:07.000Z
2021-09-21T06:32:04.000Z
clone-graph_test.cpp
babu-thomas/interviewbit-solutions
21125bf30b2d94b6f03310a4917679f216f55af3
[ "MIT" ]
1
2019-08-21T16:20:03.000Z
2019-08-21T16:21:41.000Z
clone-graph_test.cpp
babu-thomas/interviewbit-solutions
21125bf30b2d94b6f03310a4917679f216f55af3
[ "MIT" ]
23
2019-06-21T12:09:57.000Z
2021-09-22T18:03:28.000Z
#include <bits/stdc++.h> using namespace std; #define DEBUG(x) \ do { \ std::cout << #x << ": " << x << " "; \ } while (0) #define DEBUGL(x) \ do { \ std::cout << #x << ": " << x << "\n"; \ } while (0) #define MOD 1000000007 template <typename T> void print_vector(vector<T> a) { for (auto &i : a) { cout << i << " "; } cout << "\n"; } template <typename T> void print_matrix_2d(vector<vector<T>> a) { int r = 0; for (auto &i : a) { cout << r << ": "; for (auto &j : i) { cout << j << " "; } r++; cout << "\n"; } cout << "\n"; } struct UndirectedGraphNode { int label; vector<UndirectedGraphNode *> neighbors; UndirectedGraphNode(int x) : label(x){}; }; void bfs(UndirectedGraphNode *node) { unordered_set<UndirectedGraphNode *> visited_nodes; queue<UndirectedGraphNode *> to_visit; to_visit.push(node); while (!to_visit.empty()) { auto cur_node = to_visit.front(); to_visit.pop(); cout << cur_node->label << " : "; visited_nodes.insert(cur_node); for (auto neighbour : cur_node->neighbors) { cout << neighbour->label << ", "; // visited_nodes.insert(neighbour); if (visited_nodes.count(neighbour) == 0) { to_visit.push(neighbour); } } cout << "\n"; } cout << "\n"; } // Time - O(N), Space - O(N) UndirectedGraphNode *solve(UndirectedGraphNode *node) { unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> copied_nodes; auto copy = new UndirectedGraphNode(node->label); copied_nodes[node] = copy; queue<UndirectedGraphNode *> to_visit; to_visit.push(node); while (!to_visit.empty()) { auto cur_node = to_visit.front(); to_visit.pop(); for (auto neighbour : cur_node->neighbors) { if (copied_nodes.count(neighbour) == 0) { auto neighbour_copy = new UndirectedGraphNode(neighbour->label); copied_nodes[neighbour] = neighbour_copy; to_visit.push(neighbour); } copied_nodes[cur_node]->neighbors.push_back( copied_nodes[neighbour]); } } return copy; } int main() { // ios::sync_with_stdio(0); // cin.tie(0); /* +----+ | 0 | +----+ +-------+ | +----+ | | | +--+-+ +--+-+ +----+ | 1 | | 2 | | 3 | | | | +-----+ | +----+ +----+ +----+ */ // Create above graph UndirectedGraphNode *node = new UndirectedGraphNode(0); node->neighbors.push_back(new UndirectedGraphNode(1)); node->neighbors.push_back(new UndirectedGraphNode(2)); node->neighbors[node->neighbors.size() - 1]->neighbors.push_back( new UndirectedGraphNode(3)); bfs(node); auto copy = solve(node); bfs(copy); return 0; }
28.836207
80
0.462481
[ "vector" ]
cac4e866fd0896f5c60749bb0bd1031cedb473b2
3,843
cc
C++
content/browser/scheduler/browser_io_thread_delegate.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
content/browser/scheduler/browser_io_thread_delegate.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
content/browser/scheduler/browser_io_thread_delegate.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/scheduler/browser_io_thread_delegate.h" #include "base/message_loop/message_pump.h" #include "base/message_loop/message_pump_type.h" #include "base/task/sequence_manager/sequence_manager.h" #include "base/task/sequence_manager/task_queue.h" #include "base/task/task_executor.h" #include "base/task/task_observer.h" #include "content/browser/scheduler/browser_task_executor.h" #include "content/public/browser/browser_thread.h" namespace content { using ::base::sequence_manager::CreateUnboundSequenceManager; using ::base::sequence_manager::SequenceManager; using ::base::sequence_manager::TaskQueue; class BrowserIOThreadDelegate::TLSMultiplexer : public base::TaskObserver { public: TLSMultiplexer() = default; ~TLSMultiplexer() override = default; void SetIOTaskExecutor(base::TaskExecutor* io_task_executor) { io_task_executor_ = io_task_executor; } void WillProcessTask(const base::PendingTask& pending_task, bool was_blocked_or_low_priority) override { base::TaskExecutor* previous_executor = base::GetTaskExecutorForCurrentThread(); if (previous_executor) { previous_executors_.push_back(previous_executor); base::SetTaskExecutorForCurrentThread(nullptr); } base::SetTaskExecutorForCurrentThread(io_task_executor_); } void DidProcessTask(const base::PendingTask& pending_task) override { base::SetTaskExecutorForCurrentThread(nullptr); if (!previous_executors_.empty()) { base::SetTaskExecutorForCurrentThread(previous_executors_.back()); previous_executors_.pop_back(); } } base::TaskExecutor* io_task_executor_ = nullptr; std::vector<base::TaskExecutor*> previous_executors_; }; BrowserIOThreadDelegate::BrowserIOThreadDelegate() : owned_sequence_manager_(CreateUnboundSequenceManager( SequenceManager::Settings::Builder() .SetMessagePumpType(base::MessagePumpType::IO) .Build())), sequence_manager_(owned_sequence_manager_.get()) { Init(); } BrowserIOThreadDelegate::BrowserIOThreadDelegate( SequenceManager* sequence_manager) : sequence_manager_(sequence_manager), tls_multiplexer_(std::make_unique<TLSMultiplexer>()) { sequence_manager_->AddTaskObserver(tls_multiplexer_.get()); Init(); } void BrowserIOThreadDelegate::Init() { task_queues_ = std::make_unique<BrowserTaskQueues>( BrowserThread::IO, sequence_manager_, sequence_manager_->GetRealTimeDomain()); default_task_runner_ = task_queues_->GetHandle()->GetDefaultTaskRunner(); } void BrowserIOThreadDelegate::SetTaskExecutor( base::TaskExecutor* task_executor) { if (tls_multiplexer_) { tls_multiplexer_->SetIOTaskExecutor(task_executor); } else { task_executor_ = task_executor; } } scoped_refptr<base::SingleThreadTaskRunner> BrowserIOThreadDelegate::GetDefaultTaskRunner() { return default_task_runner_; } BrowserIOThreadDelegate::~BrowserIOThreadDelegate() { if (task_executor_) { base::SetTaskExecutorForCurrentThread(nullptr); } if (tls_multiplexer_) { sequence_manager_->RemoveTaskObserver(tls_multiplexer_.get()); } } void BrowserIOThreadDelegate::BindToCurrentThread( base::TimerSlack timer_slack) { DCHECK(sequence_manager_); sequence_manager_->BindToMessagePump( base::MessagePump::Create(base::MessagePumpType::IO)); sequence_manager_->SetTimerSlack(timer_slack); sequence_manager_->SetDefaultTaskRunner(GetDefaultTaskRunner()); sequence_manager_->EnableCrashKeys("io_scheduler_async_stack"); if (task_executor_) { base::SetTaskExecutorForCurrentThread(task_executor_); } } } // namespace content
33.12931
75
0.766068
[ "vector" ]
cac5139ea19b667d6f01a3f11c41a6eff1ce659d
1,067
hpp
C++
ext/src/org/apache/commons/collections4/bidimap/TreeBidiMap_ValueView.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/org/apache/commons/collections4/bidimap/TreeBidiMap_ValueView.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/org/apache/commons/collections4/bidimap/TreeBidiMap_ValueView.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/commons-collections4-4.1.jar #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/util/fwd-POI.hpp> #include <org/apache/commons/collections4/bidimap/fwd-POI.hpp> #include <org/apache/commons/collections4/bidimap/TreeBidiMap_View.hpp> struct default_init_tag; class org::apache::commons::collections4::bidimap::TreeBidiMap_ValueView : public TreeBidiMap_View { public: typedef TreeBidiMap_View super; public: /* package */ TreeBidiMap* this$0 { }; protected: void ctor(TreeBidiMap_DataElement* orderType); public: bool contains(::java::lang::Object* obj) override; ::java::util::Iterator* iterator() override; bool remove(::java::lang::Object* o) override; // Generated TreeBidiMap_ValueView(TreeBidiMap *TreeBidiMap_this, TreeBidiMap_DataElement* orderType); protected: TreeBidiMap_ValueView(TreeBidiMap *TreeBidiMap_this, const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: virtual ::java::lang::Class* getClass0(); };
24.813953
93
0.735708
[ "object" ]
cac6d3a6c10b0e58444b6788480be55f188102c8
5,177
cpp
C++
arf_planning_server/src/server_3.cpp
JeroenDM/benchmark_planning_servers
f87230421e344e678c9aa406d2cda2362d6cb6d7
[ "MIT" ]
null
null
null
arf_planning_server/src/server_3.cpp
JeroenDM/benchmark_planning_servers
f87230421e344e678c9aa406d2cda2362d6cb6d7
[ "MIT" ]
null
null
null
arf_planning_server/src/server_3.cpp
JeroenDM/benchmark_planning_servers
f87230421e344e678c9aa406d2cda2362d6cb6d7
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <nexon_msgs/LINPlanning.h> #include <eigen_conversions/eigen_msg.h> #include <eigen3/Eigen/Geometry> #include "arf_moveit_wrapper/redundant_robot.h" #include "arf_trajectory/trajectory.h" // I put some code in header files instead of separate libraries #quickanddirty #include "arf_planning_server/visual_tools_wrapper.h" #include "arf_planning_server/planner.h" #include "arf_planning_server/interpolation.h" arf::Trajectory createTrajectory() { arf::Trajectory ee_trajectory_; for (int i = 0; i < 10; ++i) { arf::Number x(0.98); arf::Number y(-0.5 + static_cast<double>(i) / 9); arf::Number z(0.02); arf::Number rx(0.0), ry(135.0 * M_PI / 180.0); //, ry(-M_PI); // TolerancedNumber ry(-M_PI, -M_PI - 1.0, -M_PI + 1.0, 5); arf::TolerancedNumber rz(0, -M_PI, M_PI, 10); arf::TrajectoryPoint tp(x, y, z, rx, ry, rz); ee_trajectory_.push_back(tp); } return ee_trajectory_; } arf::Trajectory createTrajectory(Eigen::Affine3d& start, Eigen::Affine3d& goal, arf::PlannerSettings& settings) { auto poses = arf::interpolate(start, goal, settings.max_translation, settings.max_rotation); std::size_t steps = poses.size(); arf::Trajectory ee_trajectory_; for (int i = 0; i < steps; ++i) { Eigen::Vector3d position = poses[i].translation(); arf::Number x(position[0]); arf::Number y(position[1]); arf::Number z(position[2]); Eigen::Vector3d rpy_angles = poses[i].rotation().eulerAngles(0, 1, 2); // ROS_INFO_STREAM("EUler angles: " << rpy_angles << "\n"); arf::Number rx(rpy_angles[0]), ry(rpy_angles[1]); arf::TolerancedNumber rz(rpy_angles[2], -M_PI, M_PI, 30); // Number rx(0.0), ry(135.0 * M_PI / 180.0); // TolerancedNumber rz(0, -M_PI, M_PI, 10); arf::TrajectoryPoint tp(x, y, z, rx, ry, rz); ee_trajectory_.push_back(tp); } return ee_trajectory_; } std::vector<trajectory_msgs::JointTrajectoryPoint> jointPathToMsg(arf::JointPath& jp) { double time = 0; double dt = 0.1; std::vector<trajectory_msgs::JointTrajectoryPoint> ros_traj; for (auto q : jp) { trajectory_msgs::JointTrajectoryPoint pt; pt.positions = q; pt.velocities.resize(q.size(), 0.0); pt.accelerations.resize(q.size(), 0.0); pt.time_from_start = ros::Duration(time); time += dt; // ROS_INFO_STREAM("Created ros traj pt: " << pt); ros_traj.push_back(pt); } return ros_traj; } class PlanningServer { ros::NodeHandle nh_; ros::ServiceServer cart_plannig_server_; arf::RedundantRobot robot_; arf::Rviz rviz_; arf::PlannerSettings settings_; public: PlanningServer() { cart_plannig_server_ = nh_.advertiseService("arf_cart_planning", &PlanningServer::executePlanningRequest, this); // start with default settings, read them from parameter server when planning settings_ = arf::PlannerSettings(); ROS_INFO_STREAM("Ready to receive Cartesian planning requests."); } ~PlanningServer() = default; void testServer() { robot_.printCurrentJointValues(); } void readSettigsFromParameterServer() { if (ros::param::has("/cart_config")) { double max_translation, max_rotation, pos_tol_resolution, rot_tol_resolution; if (ros::param::get("/cart_config/max_translation", max_translation)) settings_.max_translation = max_translation; if (ros::param::get("/cart_config/max_rotation", max_rotation)) settings_.max_rotation = max_rotation; if (ros::param::get("/cart_config/pos_tol_resolution", pos_tol_resolution)) settings_.pos_tol_resolution = pos_tol_resolution; if (ros::param::get("/cart_config/max_translation", rot_tol_resolution)) settings_.rot_tol_resolution = rot_tol_resolution; } else { ROS_INFO_STREAM("Could not find a planner configuration /cart_config, using defaults."); } } bool executePlanningRequest(nexon_msgs::LINPlanning::Request& req, nexon_msgs::LINPlanning::Response& resp) { // do stuff ROS_INFO_STREAM("ARF Cartesian planning server received planning request."); ROS_INFO_STREAM(req); arf::JointPose start_config = req.start_config; auto start_pose = robot_.fk(start_config); Eigen::Affine3d goal_pose; tf::poseMsgToEigen(req.pose_goal, goal_pose); // ROS_INFO_STREAM("Start pose:\n" << start_pose.translation()); auto traj = createTrajectory(start_pose, goal_pose, settings_); auto gd = arf::calculateValidJointPoses(robot_, traj, rviz_); // slow but easy operation std::vector<arf::JointPose> first_tp = { start_config }; gd.insert(gd.begin(), first_tp); // std::cout << "Created graph data.\n"; // std::cout << gd << std::endl; auto jp = arf::calculateShortestPath(robot_, gd); if (arf::DEBUG) rviz_.plotPath(robot_, jp); auto ros_jp = jointPathToMsg(jp); resp.success = true; resp.joint_path = ros_jp; return true; } }; int main(int argc, char** argv) { ros::init(argc, argv, "arf_cart_planning_server"); ros::NodeHandle node_handle; ros::AsyncSpinner spinner(3); spinner.start(); PlanningServer server; ros::waitForShutdown(); return 0; }
29.924855
116
0.688623
[ "geometry", "vector" ]
cac7b7835307e89ef70b15f5dbb5cc8e4bdc1c91
1,147
cpp
C++
LIFA/Firmware/LINX/examples/RaspberryPi_2_B_Serial/src/RaspberryPi_2_B_Serial.cpp
Errrneist/AIARG-UWKWT-HighLevel-Break-Controller
78c60f16094c344a32bdc5ff49f4e1b65ff05f97
[ "Apache-2.0" ]
null
null
null
LIFA/Firmware/LINX/examples/RaspberryPi_2_B_Serial/src/RaspberryPi_2_B_Serial.cpp
Errrneist/AIARG-UWKWT-HighLevel-Break-Controller
78c60f16094c344a32bdc5ff49f4e1b65ff05f97
[ "Apache-2.0" ]
null
null
null
LIFA/Firmware/LINX/examples/RaspberryPi_2_B_Serial/src/RaspberryPi_2_B_Serial.cpp
Errrneist/AIARG-UWKWT-HighLevel-Break-Controller
78c60f16094c344a32bdc5ff49f4e1b65ff05f97
[ "Apache-2.0" ]
null
null
null
/**************************************************************************************** ** LINX Serial Listener For Raspberry Pi 2 Model B ** ** For more information see: www.labviewmakerhub.com/linx ** For support visit the forums at: www.labviewmakerhub.com/forums/linx ** ** Written By Sam Kristoff ** ** BSD2 License. ****************************************************************************************/ #include <stdio.h> #include <iostream> #include "LinxDevice.h" #include "LinxRaspberryPi.h" #include "LinxRaspberryPi2B.h" #include "LinxSerialListener.h" #define LISTENER_UART_PORT 0 LinxRaspberryPi2B* LinxDevice; int main() { fprintf(stdout, "\n\n ..:: LINX ::..\n\n"); //Instantiate The LINX Device LinxDevice = new LinxRaspberryPi2B(); //The LINXT Listener Is Pre Instantiated, Call Start And Pass A Pointer To The LINX Device And The UART Channel To Listen On LinxSerialConnection.Start(LinxDevice, LISTENER_UART_PORT); fprintf(stdout, "Listening On UART %d.\n", LISTENER_UART_PORT); //Check for and process commands while(1) { LinxSerialConnection.CheckForCommands(); } return 0; }
26.068182
125
0.612031
[ "model" ]
cacb4438b1564685a656089b69a3f97d57ff21f3
1,313
cpp
C++
src/Logger.cpp
walidAbbassi/LoggerCpp
1ca2e3e6049759c7ecb94c8a83b9b65588a79daa
[ "MIT" ]
1
2018-12-13T05:35:31.000Z
2018-12-13T05:35:31.000Z
src/Logger.cpp
walidAbbassi/LoggerCpp
1ca2e3e6049759c7ecb94c8a83b9b65588a79daa
[ "MIT" ]
null
null
null
src/Logger.cpp
walidAbbassi/LoggerCpp
1ca2e3e6049759c7ecb94c8a83b9b65588a79daa
[ "MIT" ]
null
null
null
/** * @file Logger.cpp * @ingroup LoggerCpp * @brief A simple thread-safe Logger class * * Copyright (c) 2013 Sebastien Rombauts (sebastien.rombauts@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <LoggerCpp/Logger.h> #include <LoggerCpp/Manager.h> #include <cassert> namespace Log { // Initialize a Logger utility object Logger::Logger(const char* apChannelName) { assert(nullptr != apChannelName); mChannelPtr = Manager::get(apChannelName); assert(mChannelPtr); } // Non virtual destructor Logger::~Logger(void) { } // Utility const method to produce Log objets, used to collect the stream to output Log Logger::debug(void) const { return Log(*this, Log::eDebug); } Log Logger::info(void) const { return Log(*this, Log::eInfo); } Log Logger::notice(void) const { return Log(*this, Log::eNotice); } Log Logger::warning(void) const { return Log(*this, Log::eWarning); } Log Logger::error(void) const { return Log(*this, Log::eError); } Log Logger::critic(void) const { return Log(*this, Log::eCritic); } // To be used only by the Log class void Logger::output(const Log& aLog) const { Manager::output(mChannelPtr, aLog); } } // namespace Log
21.177419
83
0.689261
[ "object" ]
cacb5f51a735d9a33e27986bc507cc6cd5fe162e
4,744
cpp
C++
runtime/mmap-module.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
278
2021-08-31T00:46:51.000Z
2022-02-13T19:43:28.000Z
runtime/mmap-module.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
9
2021-11-05T22:28:43.000Z
2021-11-23T08:39:04.000Z
runtime/mmap-module.cpp
tekknolagi/skybison
bea8fc2af0a70e7203b4c19f36c14a745512a335
[ "CNRI-Python-GPL-Compatible" ]
12
2021-08-31T07:49:54.000Z
2021-10-08T01:09:01.000Z
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #include "mmap-module.h" #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <cerrno> #include "builtins.h" #include "file.h" #include "handles.h" #include "module-builtins.h" #include "modules.h" #include "objects.h" #include "os.h" #include "runtime.h" #include "symbols.h" #include "thread.h" #include "type-builtins.h" namespace py { void FUNC(mmap, __init_module__)(Thread* thread, const Module& module, View<byte> bytecode) { HandleScope scope(thread); Object page_size(&scope, SmallInt::fromWord(OS::pageSize())); moduleAtPutById(thread, module, ID(PAGESIZE), page_size); Object prot_exec(&scope, SmallInt::fromWord(static_cast<word>(PROT_EXEC))); moduleAtPutById(thread, module, ID(PROT_EXEC), prot_exec); Object prot_read(&scope, SmallInt::fromWord(static_cast<word>(PROT_READ))); moduleAtPutById(thread, module, ID(PROT_READ), prot_read); Object prot_write(&scope, SmallInt::fromWord(static_cast<word>(PROT_WRITE))); moduleAtPutById(thread, module, ID(PROT_WRITE), prot_write); Object map_shared(&scope, SmallInt::fromWord(static_cast<word>(MAP_SHARED))); moduleAtPutById(thread, module, ID(MAP_SHARED), map_shared); Object map_private(&scope, SmallInt::fromWord(static_cast<word>(MAP_PRIVATE))); moduleAtPutById(thread, module, ID(MAP_PRIVATE), map_private); executeFrozenModule(thread, module, bytecode); } RawObject FUNC(mmap, _mmap_new)(Thread* thread, Arguments args) { HandleScope scope(thread); Runtime* runtime = thread->runtime(); word fd = intUnderlying(args.get(1)).asWord(); word length = intUnderlying(args.get(2)).asWord(); word flags = intUnderlying(args.get(3)).asWord(); word prot = intUnderlying(args.get(4)).asWord(); word offset = intUnderlying(args.get(5)).asWord(); if (fd != -1) { struct stat sbuf; if (::fstat(fd, &sbuf) == 0 && S_ISREG(sbuf.st_mode)) { if (length == 0) { if (sbuf.st_size == 0) { return thread->raiseWithFmt(LayoutId::kValueError, "cannot mmap an empty file"); } if (offset >= sbuf.st_size) { return thread->raiseWithFmt(LayoutId::kValueError, "mmap offset is greater than file size"); } length = sbuf.st_size - offset; } else if (offset > sbuf.st_size || sbuf.st_size - offset < length) { return thread->raiseWithFmt(LayoutId::kValueError, "mmap length is greater than file size"); } } fd = ::fcntl(fd, F_DUPFD_CLOEXEC, 0); if (fd < 0) { return thread->raiseOSErrorFromErrno(errno); } } else { flags |= MAP_ANONYMOUS; } void* address = ::mmap(nullptr, length, prot, flags, fd, offset); if (address == MAP_FAILED) { return thread->raiseOSErrorFromErrno(errno); } Type type(&scope, args.get(0)); Layout layout(&scope, type.instanceLayout()); Mmap result(&scope, runtime->newInstance(layout)); result.setAccess(0); if ((prot & PROT_READ) != 0) { result.setReadable(); } if ((prot & PROT_WRITE) != 0) { result.setWritable(); } if ((flags == MAP_PRIVATE) != 0) { result.setCopyOnWrite(); } result.setData(runtime->newPointer(address, length)); result.setFd(runtime->newInt(fd)); return *result; } RawObject METH(mmap, close)(Thread* thread, Arguments args) { HandleScope scope(thread); Object self(&scope, args.get(0)); if (!thread->runtime()->isInstanceOfMmap(*self)) { return thread->raiseRequiresType(self, ID(mmap)); } Mmap mmap_obj(&scope, *self); // TODO(T64468928): Take into account exporters word fd = Int::cast(mmap_obj.fd()).asWord(); if (fd >= 0) { int close_result = File::close(fd); if (close_result < 0) return thread->raiseOSErrorFromErrno(-close_result); } mmap_obj.setFd(SmallInt::fromWord(-1)); Pointer pointer(&scope, mmap_obj.data()); void* address = pointer.cptr(); if (address != nullptr) { OS::freeMemory(static_cast<byte*>(address), pointer.length()); mmap_obj.setData(NoneType::object()); } return NoneType::object(); } static const BuiltinAttribute kMmapAttributes[] = { {ID(_mmap__access), RawMmap::kAccessOffset, AttributeFlags::kHidden}, {ID(_mmap__data), RawMmap::kDataOffset, AttributeFlags::kHidden}, {ID(_mmap__fd), RawMmap::kFdOffset, AttributeFlags::kHidden}, }; void initializeMmapType(Thread* thread) { addBuiltinType(thread, ID(mmap), LayoutId::kMmap, /*superclass_id=*/LayoutId::kObject, kMmapAttributes, Mmap::kSize, /*basetype=*/true); } } // namespace py
33.174825
79
0.655987
[ "object" ]
cacd69625aad4feb64e6fa7553e10ef5ed227dd7
3,808
cpp
C++
som/test/saved model/main.cpp
dsilko/SOM
9d27f101176b789305e783f643930a7a1c384bc5
[ "Apache-2.0" ]
9
2018-05-19T21:37:06.000Z
2021-05-31T20:10:34.000Z
som/test/saved model/main.cpp
dsilko/SOM
9d27f101176b789305e783f643930a7a1c384bc5
[ "Apache-2.0" ]
null
null
null
som/test/saved model/main.cpp
dsilko/SOM
9d27f101176b789305e783f643930a7a1c384bc5
[ "Apache-2.0" ]
3
2018-06-30T20:55:56.000Z
2020-09-14T20:35:23.000Z
/* Copyright 2018 Denis Silko. 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 "som.hpp" #include <assert.h> using namespace som; using namespace std; int main(int argc, const char * argv[]) { // Create data set // BGR colors vector<float> red {0.00, 0.0, 1.00}, green {0.0, 1.0, 0.00}, blue {1.00, 0.0, 0.00}, yellow {0.20, 1.0, 1.00}, orange {0.25, 0.4, 1.00}, purple {1.0, 0.0, 1.00}, dk_green {0.25, 0.5, 0.00}, dk_blue {0.50, 0.0, 0.00}; vector<vector<float>> data{red, green, blue, yellow, orange, purple, dk_green, dk_blue}; // Create model const auto channels = 3; const auto radius = 3; const auto hexSize = 5; const auto learningRate = 0.2; const auto iterationsCount = 1000; SOM som(CPU); som.create(radius, hexSize, channels); som.prepare(data); som.train(iterationsCount, learningRate); auto cells = som.getCells(); const auto cellsCount = cells.size(); const auto width = som.getWidth(); const auto height = som.getHeight(); const auto topologicalDimensionality = som.getTopologicalDimensionality(); const auto nodeDimensionality = som.getNodeDimensionality(); vector<vector<cl_float>> weights, points, corners; vector<cl_float> distances; vector<cl_int> labels, states; for (auto i = 0; i < cells.size(); i++) { vector<cl_float> w, p, c; for (auto j = 0; j < topologicalDimensionality; j++) { p.push_back(cells[i].center[j]); } for (auto j = 0; j < nodeDimensionality; j++) { w.push_back(cells[i].weights[j]); } for (auto j = 0; j < HEXAGON_CORNERS_COUNT; j++) { c.push_back(cells[i].corners[j]); } som.setLabel(rand(), i); distances.push_back(cells[i].distance[0]); labels.push_back(cells[i].label[0]); states.push_back(cells[i].state[0]); weights.push_back(w); points.push_back(p); corners.push_back(c); } // Save and release model som.save("model.som"); som.release(); cells.clear(); // Load and test saved model som.load("model.som"); cells = som.getCells(); assert(cells.size() == cellsCount); assert(som.getWidth() == width); assert(som.getHeight() == height); assert(som.getTopologicalDimensionality() == topologicalDimensionality); assert(som.getNodeDimensionality() == nodeDimensionality); for (auto i = 0; i < cells.size(); i++) { for (auto j = 0; j < topologicalDimensionality; j++) { assert(cells[i].center[j] == points[i][j]); } for (auto j = 0; j < nodeDimensionality; j++) { assert(cells[i].weights[j] == weights[i][j]); } for (auto j = 0; j < nodeDimensionality; j++) { assert(cells[i].corners[j] == corners[i][j]); } assert(cells[i].distance[0] == distances[i]); assert(cells[i].label[0] == labels[i]); assert(cells[i].state[0] == states[i]); } return 0; }
32
92
0.574055
[ "vector", "model" ]
cad7fb6792d9b4fd02a100cac3454833cc0dfc8c
9,700
cxx
C++
main/framework/source/uielement/fontmenucontroller.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/framework/source/uielement/fontmenucontroller.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/framework/source/uielement/fontmenucontroller.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_framework.hxx" #include <uielement/fontmenucontroller.hxx> //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <threadhelp/resetableguard.hxx> #include "services.h" //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/awt/XDevice.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/awt/MenuItemStyle.hpp> #include <com/sun/star/frame/XDispatchProvider.hpp> //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _VCL_MENU_HXX_ #include <vcl/menu.hxx> #endif #include <vcl/svapp.hxx> #include <vcl/i18nhelp.hxx> #include <tools/urlobj.hxx> #include <rtl/ustrbuf.hxx> #ifndef _VCL_MNEMONIC_HXX_ #include <vcl/mnemonic.hxx> #endif #include <dispatch/uieventloghelper.hxx> #include <vos/mutex.hxx> //_________________________________________________________________________________________________________________ // Defines //_________________________________________________________________________________________________________________ // using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::frame; using namespace com::sun::star::beans; using namespace com::sun::star::util; using namespace std; bool lcl_I18nCompareString(const rtl::OUString& rStr1, const rtl::OUString& rStr2) { const vcl::I18nHelper& rI18nHelper = Application::GetSettings().GetUILocaleI18nHelper(); return rI18nHelper.CompareString( rStr1, rStr2 ) < 0 ? true : false; } namespace framework { DEFINE_XSERVICEINFO_MULTISERVICE ( FontMenuController , OWeakObject , SERVICENAME_POPUPMENUCONTROLLER , IMPLEMENTATIONNAME_FONTMENUCONTROLLER ) DEFINE_INIT_SERVICE ( FontMenuController, {} ) FontMenuController::FontMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) : svt::PopupMenuControllerBase( xServiceManager ) { } FontMenuController::~FontMenuController() { } // private function void FontMenuController::fillPopupMenu( const Sequence< ::rtl::OUString >& rFontNameSeq, Reference< css::awt::XPopupMenu >& rPopupMenu ) { const rtl::OUString* pFontNameArray = rFontNameSeq.getConstArray(); VCLXPopupMenu* pPopupMenu = (VCLXPopupMenu *)VCLXMenu::GetImplementation( rPopupMenu ); PopupMenu* pVCLPopupMenu = 0; vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); resetPopupMenu( rPopupMenu ); if ( pPopupMenu ) pVCLPopupMenu = (PopupMenu *)pPopupMenu->GetMenu(); if ( pVCLPopupMenu ) { vector<rtl::OUString> aVector; aVector.reserve(rFontNameSeq.getLength()); for ( sal_uInt16 i = 0; i < rFontNameSeq.getLength(); i++ ) { aVector.push_back(MnemonicGenerator::EraseAllMnemonicChars(pFontNameArray[i])); } sort(aVector.begin(), aVector.end(), lcl_I18nCompareString ); const rtl::OUString aFontNameCommandPrefix( RTL_CONSTASCII_USTRINGPARAM( ".uno:CharFontName?CharFontName.FamilyName:string=" )); const sal_Int16 nCount = (sal_Int16)aVector.size(); for ( sal_Int16 i = 0; i < nCount; i++ ) { const rtl::OUString& rName = aVector[i]; m_xPopupMenu->insertItem( i+1, rName, css::awt::MenuItemStyle::RADIOCHECK | css::awt::MenuItemStyle::AUTOCHECK, i ); if ( rName == m_aFontFamilyName ) m_xPopupMenu->checkItem( i+1, sal_True ); // use VCL popup menu pointer to set vital information that are not part of the awt implementation rtl::OUStringBuffer aCommandBuffer( aFontNameCommandPrefix ); aCommandBuffer.append( INetURLObject::encode( rName, INetURLObject::PART_HTTP_QUERY, '%', INetURLObject::ENCODE_ALL )); rtl::OUString aFontNameCommand = aCommandBuffer.makeStringAndClear(); pVCLPopupMenu->SetItemCommand( i+1, aFontNameCommand ); // Store font name into item command. } } } // XEventListener void SAL_CALL FontMenuController::disposing( const EventObject& ) throw ( RuntimeException ) { Reference< css::awt::XMenuListener > xHolder(( OWeakObject *)this, UNO_QUERY ); osl::MutexGuard aLock( m_aMutex ); m_xFrame.clear(); m_xDispatch.clear(); m_xFontListDispatch.clear(); m_xServiceManager.clear(); if ( m_xPopupMenu.is() ) m_xPopupMenu->removeMenuListener( Reference< css::awt::XMenuListener >(( OWeakObject *)this, UNO_QUERY )); m_xPopupMenu.clear(); } // XStatusListener void SAL_CALL FontMenuController::statusChanged( const FeatureStateEvent& Event ) throw ( RuntimeException ) { com::sun::star::awt::FontDescriptor aFontDescriptor; Sequence< rtl::OUString > aFontNameSeq; if ( Event.State >>= aFontDescriptor ) { osl::MutexGuard aLock( m_aMutex ); m_aFontFamilyName = aFontDescriptor.Name; } else if ( Event.State >>= aFontNameSeq ) { osl::MutexGuard aLock( m_aMutex ); if ( m_xPopupMenu.is() ) fillPopupMenu( aFontNameSeq, m_xPopupMenu ); } } // XMenuListener void FontMenuController::impl_select(const Reference< XDispatch >& _xDispatch,const ::com::sun::star::util::URL& aTargetURL) { Sequence<PropertyValue> aArgs; if(::comphelper::UiEventsLogger::isEnabled()) //#i88653# UiEventLogHelper(::rtl::OUString::createFromAscii("FontMenuController")).log( m_xServiceManager, m_xFrame, aTargetURL, Sequence<PropertyValue>()); OSL_ENSURE(_xDispatch.is(),"FontMenuController::impl_select: No dispatch"); if ( _xDispatch.is() ) _xDispatch->dispatch( aTargetURL, aArgs ); } void SAL_CALL FontMenuController::itemActivated( const css::awt::MenuEvent& ) throw (RuntimeException) { osl::MutexGuard aLock( m_aMutex ); if ( m_xPopupMenu.is() ) { // find new font name and set check mark! sal_uInt16 nChecked = 0; sal_uInt16 nItemCount = m_xPopupMenu->getItemCount(); rtl::OUString aEmpty; for( sal_uInt16 i = 0; i < nItemCount; i++ ) { sal_uInt16 nItemId = m_xPopupMenu->getItemId( i ); if ( m_xPopupMenu->isItemChecked( nItemId ) ) nChecked = nItemId; rtl::OUString aText = m_xPopupMenu->getItemText( nItemId ); // TODO: must be replaced by implementation of VCL, when available sal_Int32 nIndex = aText.indexOf( (sal_Unicode)'~' ); if ( nIndex >= 0 ) aText = aText.replaceAt( nIndex, 1, aEmpty ); // TODO: must be replaced by implementation of VCL, when available if ( aText == m_aFontFamilyName ) { m_xPopupMenu->checkItem( nItemId, sal_True ); return; } } if ( nChecked ) m_xPopupMenu->checkItem( nChecked, sal_False ); } } // XPopupMenuController void FontMenuController::impl_setPopupMenu() { Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); com::sun::star::util::URL aTargetURL; // Register for font list updates to get the current font list from the controller aTargetURL.Complete = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontNameList" )); m_xURLTransformer->parseStrict( aTargetURL ); m_xFontListDispatch = xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); } void SAL_CALL FontMenuController::updatePopupMenu() throw ( ::com::sun::star::uno::RuntimeException ) { svt::PopupMenuControllerBase::updatePopupMenu(); osl::ClearableMutexGuard aLock( m_aMutex ); Reference< XDispatch > xDispatch( m_xFontListDispatch ); com::sun::star::util::URL aTargetURL; aTargetURL.Complete = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:FontNameList" )); m_xURLTransformer->parseStrict( aTargetURL ); aLock.clear(); if ( xDispatch.is() ) { xDispatch->addStatusListener( SAL_STATIC_CAST( XStatusListener*, this ), aTargetURL ); xDispatch->removeStatusListener( SAL_STATIC_CAST( XStatusListener*, this ), aTargetURL ); } } }
37.451737
147
0.710412
[ "vector" ]
cae274265ba4f2b67fbbb9bf7fbab7a2cc196e2b
4,971
cpp
C++
tests/testDogleg.cpp
versatran01/minisam
b3840d2629551fdfa287df8aac2e7956873d2b0e
[ "BSD-3-Clause" ]
338
2019-09-03T10:44:08.000Z
2022-03-31T12:12:08.000Z
tests/testDogleg.cpp
bhsphd/minisam
ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb
[ "BSD-3-Clause" ]
23
2019-09-26T09:00:43.000Z
2022-01-04T06:04:02.000Z
tests/testDogleg.cpp
bhsphd/minisam
ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb
[ "BSD-3-Clause" ]
87
2019-09-04T05:17:07.000Z
2022-02-23T09:47:23.000Z
// test Levenberg-Marquardt // use the same factor graph in testlinearization #include <minisam/3rdparty/Catch2/catch.hpp> #include <minisam/utils/testAssertions.h> #include <minisam/nonlinear/DoglegOptimizer.h> #include <minisam/nonlinear/linearization.h> #include <minisam/nonlinear/SparsityPattern.h> #include <minisam/core/FactorGraph.h> #include <minisam/core/VariableOrdering.h> #include <minisam/core/Factor.h> #include <minisam/core/LossFunction.h> #include <minisam/core/Variables.h> #include <minisam/core/Key.h> #include <minisam/core/Scalar.h> #include <string> #include <sstream> using namespace std; using namespace minisam; // example factor for test class PFactor: public Factor { private: double prior_; public: PFactor(Key key, double prior, const std::shared_ptr<LossFunction>& lossfunc): Factor(1, std::vector<Key>{key}, lossfunc), prior_(prior) {} virtual ~PFactor() {} std::shared_ptr<Factor> copy() const { return std::shared_ptr<Factor>(new PFactor(*this)); } Eigen::VectorXd error(const Variables& values) const { return (Eigen::VectorXd(1) << values.at<double>(keys()[0]) - prior_).finished(); } std::vector<Eigen::MatrixXd> jacobians(const Variables& /*values*/) const { return std::vector<Eigen::MatrixXd>{Eigen::MatrixXd::Identity(1, 1)}; } }; // prepared graph and values Variables values_prep; FactorGraph graph_prep; Eigen::SparseMatrix<double> A, AtA, AtA_low; Eigen::VectorXd b, Atb; internal::JacobianSparsityPattern jcache; internal::LowerHessianSparsityPattern hcache; /* ************************************************************************** */ TEST_CASE("LevenbergMarquardt_prep_static_values", "[nonlinear]") { values_prep.add<double>(0, 0.5); values_prep.add<double>(1, 1.2); graph_prep.add(PFactor(0, 0.0, nullptr)); graph_prep.add(PFactor(1, 1.0, nullptr)); VariableOrdering vordering({0, 1}); // jaocbian linearization jcache = internal::constructJacobianSparsity(graph_prep, values_prep, vordering); internal::linearzationJacobian(graph_prep, values_prep, jcache, A, b); // hessian linearization hcache = internal::constructLowerHessianSparsity(graph_prep, values_prep, vordering); internal::linearzationLowerHessian(graph_prep, values_prep, hcache, AtA_low, Atb); internal::linearzationFullHessian(graph_prep, values_prep, hcache, AtA, Atb); } /* ************************************************************************** */ TEST_CASE("DoglegSteepestDescent", "[nonlinear]") { Eigen::VectorXd dx_sd_exp(2), dx_sd_act(2); double alpha, gnorm2; dx_sd_exp << -0.5, -0.2; dx_sd_act = internal::steepestDescentJacobian(A, b, gnorm2, alpha); CHECK(assert_equal(dx_sd_exp, dx_sd_act)); CHECK(assert_equal(Atb.squaredNorm(), gnorm2)); CHECK(assert_equal(dx_sd_act.norm() / Atb.norm(), alpha)); dx_sd_act = internal::steepestDescentHessian(AtA, Atb, gnorm2, alpha); CHECK(assert_equal(dx_sd_exp, dx_sd_act)); CHECK(assert_equal(Atb.squaredNorm(), gnorm2)); CHECK(assert_equal(dx_sd_act.norm() / Atb.norm(), alpha)); dx_sd_act = internal::steepestDescentHessian(AtA_low, Atb, gnorm2, alpha); CHECK(assert_equal(dx_sd_exp, dx_sd_act)); CHECK(assert_equal(Atb.squaredNorm(), gnorm2)); CHECK(assert_equal(dx_sd_act.norm() / Atb.norm(), alpha)); } /* ************************************************************************** */ TEST_CASE("DoglegStep", "[nonlinear]") { Eigen::VectorXd dx_gn(2), dx_sd(2), dx_dl_exp(2), dx_dl_act(2); double r = 1.0, beta; // use GN dx_gn << 0., 0.; dx_sd << 0., 0.; dx_dl_exp = dx_gn; beta = internal::doglegStep(dx_gn, dx_sd, r, dx_dl_act); CHECK(assert_equal(dx_dl_exp, dx_dl_act)); CHECK(beta > 1.0); dx_gn << 0.4, 0.3; dx_sd << 0.2, 1.2; dx_dl_exp = dx_gn; beta = internal::doglegStep(dx_gn, dx_sd, r, dx_dl_act); CHECK(assert_equal(dx_dl_exp, dx_dl_act)); CHECK(beta > 1.0); // use SD dx_gn << 1.4, 1.3; dx_sd << 2.0, 0.0; dx_dl_exp << 1.0, 0.0; beta = internal::doglegStep(dx_gn, dx_sd, r, dx_dl_act); CHECK(assert_equal(dx_dl_exp, dx_dl_act)); CHECK(beta < 0.0); dx_gn << 1.4, 1.3; dx_sd << 1.6, 1.2; dx_dl_exp << 0.8, 0.6; beta = internal::doglegStep(dx_gn, dx_sd, r, dx_dl_act); CHECK(assert_equal(dx_dl_exp, dx_dl_act)); CHECK(beta < 0.0); // use blended dx_gn << 2.0, 0.0; dx_sd << 0.0, 0.0; // zero SD dx_dl_exp << 1.0, 0.0; beta = internal::doglegStep(dx_gn, dx_sd, r, dx_dl_act); CHECK(assert_equal(dx_dl_exp, dx_dl_act)); CHECK(assert_equal(0.5, beta)); dx_gn << 0.0, 1.732050807568877; dx_sd << 1.0, 0.0; // one SD dx_dl_exp << 0.5, 0.866025403784439; beta = internal::doglegStep(dx_gn, dx_sd, r, dx_dl_act); CHECK(assert_equal(dx_dl_exp, dx_dl_act)); CHECK(assert_equal(0.5, beta)); // use blended: just test norm dx_gn << 2.3, 4.5; dx_sd << 0.2, 0.5; r = 0.98345; beta = internal::doglegStep(dx_gn, dx_sd, r, dx_dl_act); CHECK(assert_equal(r, dx_dl_act.norm())); }
31.462025
94
0.670087
[ "vector" ]
cae79749030067f5fbdd0ce363c081dd59d7f79e
10,008
cc
C++
tce/src/applibs/hdb/FUArchitecture.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
tce/src/applibs/hdb/FUArchitecture.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
tce/src/applibs/hdb/FUArchitecture.cc
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
/* Copyright (c) 2002-2009 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). 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. */ /** * @file FUArchitecture.cc * * Implementation of FUArchitecture class. * * @author Lasse Laasonen 2005 (lasse.laasonen-no.spam-tut.fi) * @note rating: red */ #include <string> #include "FUArchitecture.hh" #include "FunctionUnit.hh" #include "HWOperation.hh" #include "ExecutionPipeline.hh" #include "AssocTools.hh" #include "MapTools.hh" #include "FUPort.hh" #include "PipelineElement.hh" using namespace TTAMachine; using std::string; namespace HDB { /** * The constructor. * * @param fu The function unit of which architecture is represented. Becomes * property of the FUArchitecture object. */ FUArchitecture::FUArchitecture(TTAMachine::FunctionUnit* fu) : fu_(fu) { } /** * Copy constructor. * * @param original FUArchitecture to copy. */ FUArchitecture::FUArchitecture(const FUArchitecture& original) : HWBlockArchitecture(original) { fu_ = original.fu_->copy(); parameterizedPorts_ = original.parameterizedPorts_; guardedPorts_ = original.guardedPorts_; } /** * The destructor. */ FUArchitecture::~FUArchitecture() { delete fu_; } /** * Tells whether the given port has parameterized width. * * @param port Name of the port. * @return True if the port is parameterized, otherwise false. */ bool FUArchitecture::hasParameterizedWidth(const std::string& port) const { return AssocTools::containsKey(parameterizedPorts_, port); } /** * Sets parameterized width for the given port. * * @param port Name of the port. */ void FUArchitecture::setParameterizedWidth(const std::string& port) { parameterizedPorts_.insert(port); } /** * Tells whether the given port is guarded. * * @param port Name of the port. * @return True if the port is guarded, otherwise false. */ bool FUArchitecture::hasGuardSupport(const std::string& port) const { return AssocTools::containsKey(guardedPorts_, port); } /** * Sets guard support for the given port. * * @param port Name of the port. */ void FUArchitecture::setGuardSupport(const std::string& port) { guardedPorts_.insert(port); } /** * Returns the FunctionUnit instance that represents the architecture. * * @return The FunctionUnit instance. */ TTAMachine::FunctionUnit& FUArchitecture::architecture() const { return *fu_; } /** * Tells the direction of the given port. * * @param portName Name of the port in the FU architecture. * @exception InstanceNotFound If the FU architecture does not have the given * port. * @exception InvalidData If the given port is not used by any pipeline. */ HDB::Direction FUArchitecture::portDirection(const std::string& portName) const { FunctionUnit& fu = architecture(); if (!fu.hasOperationPort(portName)) { throw InstanceNotFound(__FILE__, __LINE__, __func__); } FUPort* port = fu.operationPort(portName); bool read = false; bool written = false; int operationCount = fu.operationCount(); for (int i = 0; i < operationCount; i++) { HWOperation* operation = fu.operation(i); ExecutionPipeline* pLine = operation->pipeline(); int latency = operation->latency(); for (int cycle = 0; cycle < latency; cycle++) { if (!read) { if (pLine->isPortRead(*port, cycle)) { read = true; } } if (!written) { if (pLine->isPortWritten(*port, cycle)) { written = true; } } } if (read && written) { break; } } if (read && written) { return HDB::BIDIR; } else if (read) { return HDB::IN; } else if (written) { return HDB::OUT; } else { throw InvalidData(__FILE__, __LINE__, __func__); } } /** * Checks whether the given FU has a mathing architecture with the given FU * architecture instance. * * @param rightHand Right hand operand. * @return True if the architectures match, otherwise false. */ bool FUArchitecture::operator==(const FUArchitecture& rightHand) const { if (rightHand.architecture().operationCount() != this->architecture().operationCount()) { return false; } std::map<const FUPort*, const FUPort*> portMap; for (int i = 0; i < rightHand.architecture().operationPortCount(); i++) { portMap.insert( std::pair<const FUPort*, const FUPort*>( rightHand.architecture().operationPort(i), NULL)); } PipelineElementUsageTable plineElementUsages; for (int i = 0; i < rightHand.architecture().operationCount(); i++) { HWOperation* rightHandOp = rightHand.architecture().operation(i); if (!architecture().hasOperation(rightHandOp->name())) { return false; } HWOperation* thisOp = architecture().operation( rightHandOp->name()); if (rightHandOp->latency() != thisOp->latency()) { return false; } // check operand bindings for (int i = 0; i < rightHand.architecture().operationPortCount(); i++) { FUPort* port = rightHand.architecture().operationPort(i); if (rightHandOp->isBound(*port)) { int io = rightHandOp->io(*port); FUPort* samePort = thisOp->port(io); if (samePort == NULL) { return false; } const FUPort* existingSamePort = MapTools::valueForKey<const FUPort*>(portMap, port); if (existingSamePort != NULL && existingSamePort != samePort) { return false; } // check the width of the ports // widths must equal if (hasParameterizedWidth(samePort->name()) != rightHand.hasParameterizedWidth(port->name())) { return false; } // if the FUArchitectures have parameterized port width // those ports widths are not needed to check if (!hasParameterizedWidth(samePort->name()) && samePort->width() != port->width()) { return false; } if (port->isOpcodeSetting() != samePort->isOpcodeSetting() || port->isTriggering() != samePort->isTriggering()) { return false; } portMap.erase(port); portMap.insert( std::pair<const FUPort*, const FUPort*>(port, samePort)); } } // check operation pipeline ExecutionPipeline* opPipeline = rightHandOp->pipeline(); ExecutionPipeline* thisOpPipeline = thisOp->pipeline(); for (int cycle = 0; cycle < rightHandOp->latency(); cycle++) { ExecutionPipeline::OperandSet written1 = opPipeline->writtenOperands(cycle); ExecutionPipeline::OperandSet written2 = thisOpPipeline->writtenOperands(cycle); if (written1 != written2) { return false; } ExecutionPipeline::OperandSet read1 = opPipeline->readOperands(cycle); ExecutionPipeline::OperandSet read2 = thisOpPipeline->readOperands(cycle); if (read1 != read2) { return false; } PipelineElementUsage usage; for (int i = 0; i < rightHand.architecture().pipelineElementCount(); i++) { const PipelineElement* elem = rightHand.architecture().pipelineElement(i); if (opPipeline->isResourceUsed(elem->name(),cycle)) { usage.usage1.insert(elem); } } for (int i = 0; i < architecture().pipelineElementCount(); i++) { const PipelineElement* elem = architecture().pipelineElement(i); if (thisOpPipeline->isResourceUsed(elem->name(), cycle)) { usage.usage2.insert(elem); } } plineElementUsages.push_back(usage); } } std::set<const TTAMachine::PipelineElement*> difference; for (size_t i = 0; i < plineElementUsages.size(); i++) { AssocTools::difference(plineElementUsages[i].usage1, plineElementUsages[i].usage2, difference); } if (!difference.empty()) { return false; } return true; } }
31.275
78
0.593125
[ "object" ]
cae7c3182d0133f47960099b59dcb7f974be03e9
6,008
hpp
C++
src/graph_cc.hpp
owodolab/graspi
4319cad2d5490903998094cdee85f039f70a4ff6
[ "BSD-3-Clause" ]
2
2020-11-24T15:07:00.000Z
2021-03-09T00:22:14.000Z
src/graph_cc.hpp
owodolab/graspi
4319cad2d5490903998094cdee85f039f70a4ff6
[ "BSD-3-Clause" ]
2
2021-05-21T21:33:55.000Z
2021-07-08T16:17:12.000Z
src/graph_cc.hpp
owodolab/graspi
4319cad2d5490903998094cdee85f039f70a4ff6
[ "BSD-3-Clause" ]
3
2020-11-19T22:18:32.000Z
2021-12-22T11:13:22.000Z
/*** * $Id$ ** * File: graph_cc.hpp * Created: May 9, 2012 * * Author: Olga Wodo, Baskar Ganapathysubramanian * Copyright (c) 2012 Olga Wodo, Baskar Ganapthysubramanian * See accompanying LICENSE. * * This file is part of GraSPI. */ #ifndef GRAPH_CC_HPP #define GRAPH_CC_HPP #include "graspi_types.hpp" #include "graspi_predicates.hpp" #include <boost/graph/connected_components.hpp> #include <boost/graph/filtered_graph.hpp> namespace graspi{ /// find the connected components /// /// This function finds the connected components where each component consists of vertices of the same color /// @param G is the graph /// @param C is the vector with the colors of vertices /// @param cVV is the vector storing the indices of the connected component of each vertex, this vector is initialized and filled as a result of this function execution inline void identify_connected_components( graspi::graph_t* G, const vertex_colors_t& C, vertex_ccs_t& vCC ){ connect_same_color pred(*G, C); boost::filtered_graph<graspi::graph_t,connect_same_color> FG(*G, pred); int size_of_G = boost::num_vertices(*G); vCC.resize(size_of_G, 0); boost::connected_components(FG, &vCC[0]); }//identify_connected_components /// This function determines the number of connected components /// /// This function determines the number of connected components once the connected components are identified for each vertex in the graph /// @param vCC is the vector storing the indices of the connected component of each vertex /// @param d_g is the structure storing basic informations about the graph dimensionality /// return the number of connected components (without the meta vertices) inline int determine_number_of_CCs( const graspi::vertex_ccs_t& vCC, const graspi::dim_g_t& d_g){ int max_index = 0; // find max index for (unsigned int i = 0; i < vCC.size(); ++i) { std::cout << "id,cc: " << i << " " << vCC[i] << std::endl; if(vCC[i] > max_index) max_index = vCC[i]; } int number_of_conn_comp = max_index + 1; // correct nOfCC - subtract meta vertices that are identified as separate CC return number_of_conn_comp - d_g.n_meta_total(); }//determine_number_of_CCs /// This function determines the basic statistics of graph in terms of connected components /// /// This function determines the statistics of the graph related to the connected components /// @param G is the input graph /// @param d_g is the structure storing basic informations about the graph dimensionality /// @param CCs is structure storing information about individual components (e.g. if the CC is connected to meta vertex) /// @param C is the vector with the colors of vertices /// @param vCC is the vector storing the indices of the connected component of each vertex inline void determine_basic_stats_of_ccs( graspi::graph_t* G, const graspi::dim_g_t& d_g, graspi::ccs_t& CCs, const graspi::vertex_colors_t& C, const graspi::vertex_ccs_t& vCCs ){ std::vector<int>::const_iterator it = max_element( vCCs.begin(), vCCs.end() ); CCs.resize( (*it)+1 ); #ifdef DEBUG std::cout << "Total number of connected components" << *it << std::endl; #endif for (unsigned int i = 0; i < vCCs.size(); i++){ CCs[vCCs[i]].color = C[i]; CCs[vCCs[i]].size++; } // unsigned int size_of_G = boost::num_vertices(*G); // determine all vertices connected to the bottom electrode std::set<int> comp_conn_to_electrode; graspi::vertex_t source = d_g.id_blue(); // bottom electrode index graspi::graph_t::adjacency_iterator u, u_end; boost::tie(u, u_end) = boost::adjacent_vertices(source, *G); for (; u != u_end; ++u) { comp_conn_to_electrode.insert(vCCs[*u]); } #ifdef DEBUG std::cout << "Id of connected components connected to bottom " << std::endl; copy(comp_conn_to_electrode.begin(), comp_conn_to_electrode.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; #endif // pass info about connectivity to bottom electrode to data of components for(unsigned int i = 0; i < CCs.size(); i++ ){ if( comp_conn_to_electrode.find(i) != comp_conn_to_electrode.end() ) CCs[i].if_connected_to_electrode += 1; } // determine all vertices connected to the top electrode comp_conn_to_electrode.clear(); source = d_g.id_red(); // top electrode index boost::tie(u, u_end) = boost::adjacent_vertices(source, *G); for (; u != u_end; ++u) { comp_conn_to_electrode.insert(vCCs[*u]); } #ifdef DEBUG std::cout << "Id of connected components conn to top " << std::endl; std::set<int>::iterator its = comp_conn_to_electrode.begin(); for (int i = 0; i < comp_conn_to_electrode.size(); i++){ int id = *its; std::cout << id << " " << CCs[id].color << std::endl; its++; } std::cout << std::endl; #endif // pass info about connectivity to top electrode to data of components for(unsigned int i = 0; i < CCs.size(); i++ ){ if( comp_conn_to_electrode.find(i) != comp_conn_to_electrode.end() ) CCs[i].if_connected_to_electrode += 2; } }//determine_basic_stats_of_ccs } #endif
39.788079
172
0.601365
[ "vector" ]
cae9cd1ea56dd308b362d3362c1e4d9f58f7730d
577
hpp
C++
frontend/error/Manager.hpp
patrickf2000/tiny-lang
0339bf046be53e31130c47a9eae4c0a62fe5a1a6
[ "BSD-3-Clause" ]
null
null
null
frontend/error/Manager.hpp
patrickf2000/tiny-lang
0339bf046be53e31130c47a9eae4c0a62fe5a1a6
[ "BSD-3-Clause" ]
null
null
null
frontend/error/Manager.hpp
patrickf2000/tiny-lang
0339bf046be53e31130c47a9eae4c0a62fe5a1a6
[ "BSD-3-Clause" ]
null
null
null
// // Copyright 2021-2022 Patrick Flynn // This file is part of the Tiny Lang compiler. // Tiny Lang is licensed under the BSD-3 license. See the COPYING file for more information. // #pragma once #include <string> #include <vector> struct Error { int line; std::string message; }; class ErrorManager { public: void addError(int line, std::string message); void addWarning(int line, std::string message); bool errorsPresent(); void printErrors(); void printWarnings(); private: std::vector<Error> errors; std::vector<Error> warnings; };
20.607143
92
0.691508
[ "vector" ]
caeb9e7ee3bfb3ef00f1fe2643307ef254f0e1d9
32,854
cpp
C++
cygic/logic/logic_circuit.cpp
T145/archive
520ce95fb533ac0c41d3c59511637ad06faea095
[ "MIT" ]
null
null
null
cygic/logic/logic_circuit.cpp
T145/archive
520ce95fb533ac0c41d3c59511637ad06faea095
[ "MIT" ]
null
null
null
cygic/logic/logic_circuit.cpp
T145/archive
520ce95fb533ac0c41d3c59511637ad06faea095
[ "MIT" ]
null
null
null
/***************************************************************************** Project: CEDAR Logic Simulator Copyright 2006 Cedarville University, Benjamin Sprague, Matt Lewellyn, and David Knierim All rights reserved. For license information see license.txt included with distribution. *****************************************************************************/ // logic_circuit.cpp: implementation of the Circuit class. // ////////////////////////////////////////////////////////////////////// #include "logic_circuit.h" #include <iostream> #include <algorithm> #include <stack> #include "../Z80/Z_80LogicGate.h" #ifndef _PRODUCTION_ ofstream* logiclog; #endif // ************************** Event class ******************************** unsigned long long Event::globalCreationTime = 0; // Definition of operator for Events: bool operator > (const Event &left, const Event &right) { if( left.eventTime == right.eventTime ) { return ( left.getCreationTime() > right.getCreationTime() ); } else { return (left.eventTime > right.eventTime); } } // ************************** End Event class ******************************** // If this is defined, use inertial delay, otherwise default to transport delay //#define INERTIAL_DELAY ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Circuit::Circuit() { // Set time to begin starting: systemTime = 0; // Set the initial ID values: gateIDCount = 0; wireIDCount = 0; juncIDCount = 0; #ifndef _PRODUCTION_ logiclog = new ofstream( "corelog.log"); #endif } Circuit::~Circuit() { // Cause all of the gates to destroy themselves // before the Circuit gets destroyed, or any other // objects are removed: // (This is needed so that if their destructors call // any Circuit methods, they won't crash.) gateList.clear(); } // **************** The visible interface of the circuit ******************** // ********** Circuit input methods ************* //*************************************** //Edit by Joshua Lansford 3/27/07 //purpose of edit: The ram gate needs to //update its pop-up right after it loads //even if it is paused. Thus this method //is created, so that the pop-ups //can request that the core proces //thegateUpdateList without advanceing //the system time void Circuit::stepOnlyGates(){ // Update the gates that have been connected or disconnected or had a // parameter change within the last call to step() so that they can // recalculate correctly: ID_SET< IDType >::iterator updateGate = gateUpdateList.begin(); while( updateGate != gateUpdateList.end() ) { gateList[*updateGate]->updateGate( *updateGate, this ); updateGate++; } gateUpdateList.clear(); } //End of Edit***************************** // Step the simulation forward by one timestep: // If a pointer to a set is passed, then it will // return a set of all the changed wires to the calling function. void Circuit::step( ID_SET< IDType > *changedWires ) { // NOTE: Should activate the polled gates here: // Basically just loop through the things in polledGates and call updateGate() on them. ID_SET< IDType >::iterator gateToPoll = polledGates.begin(); while( gateToPoll != polledGates.end() ) { gateList[*gateToPoll]->updateGate( *gateToPoll, this ); gateToPoll++; } // Update the gates that have been connected or disconnected or had a // parameter change within the last call to step() so that they can // recalculate correctly: ID_SET< IDType >::iterator updateGate = gateUpdateList.begin(); while( updateGate != gateUpdateList.end() ) { gateList[*updateGate]->updateGate( *updateGate, this ); updateGate++; } gateUpdateList.clear(); // Loop through all of the events with time == now, and // activate them. bool makeYourOwnFreakinChangedWiresList = (changedWires == NULL); if( makeYourOwnFreakinChangedWiresList ) changedWires = new ID_SET< IDType >; int processedEvents = 0; Event myEvent; if(!eventQueue.empty()) myEvent = eventQueue.top(); while ( !eventQueue.empty() && (myEvent.eventTime <= systemTime) ) { // Pop the event off of the event queue: eventQueue.pop(); // If the event is a junction event, handle it as a junction: if( myEvent.isJunctionEvent ) { // Handle the junction event: setJunctionState( myEvent.junctionID, myEvent.newJunctionState ); // Also adds all of the wires hooked up to this junction to // the "wireUpdateList" list. // (Handled inside of a setJunctionState() method, to allow // it to be called from outside of an event handle - for zero delay.) } else { // Else, make the event happen to the wire: WIRE_PTR myWire = wireList[myEvent.wireID]; myWire->setInputState(myEvent.gateID, myEvent.gateOutputID, myEvent.newState); // Insert all attached wires into the changed wires list: set< IDType > wireGroup = getJunctionGroupIDs( myEvent.wireID ); changedWires->insert( wireGroup.begin(), wireGroup.end() ); } // Look at the next thing in the list: myEvent = eventQueue.top(); processedEvents++; } // Insert the wires that have been disconnected (or were part of a junction that changed) within // the last call to step() so that they will be properly updated: changedWires->insert( wireUpdateList.begin(), wireUpdateList.end() ); wireUpdateList.clear(); // Empty the wireUpdateList, since we are handling the updates. // Calculate the new wire states, and make a list of affected gates: ID_SET< IDType > changedGates; vector< IDType > affectedGates; // This keeps track of wires that share junctions that have already // calculated their state: ID_SET< IDType > doneWires; ID_SET< IDType >::iterator chgWireIterator = changedWires->begin(); while ( chgWireIterator != changedWires->end() ) { WIRE_PTR myWire = wireList[*chgWireIterator]; // Calculate the new state of a wire: // (Note: It sends the group of attached wires to the Wire::calculateState() method. if( doneWires.find( *chgWireIterator ) == doneWires.end() ) { set< IDType > wireGroupIDs = getJunctionGroupIDs( *chgWireIterator ); set< WIRE_PTR > wireGroup = getJunctionGroup( &wireGroupIDs ); StateType juncState = myWire->calculateState( wireGroup ); set< WIRE_PTR >::iterator wgWire = wireGroup.begin(); while( wgWire != wireGroup.end() ) { (*wgWire)->forceState( juncState ); wgWire++; } doneWires.insert( wireGroupIDs.begin(), wireGroupIDs.end() ); } // Add this wire's gates to the overall gate list: affectedGates = myWire->getOutputGates(); changedGates.insert( affectedGates.begin(), affectedGates.end() ); // NOTE: Aparently MSVCC doesn't like this last *STL standard and legal* line // of code. // Move on to the next wire in the list: chgWireIterator++; } // Update the gate's states and post the events from the gates: ID_SET< IDType >::iterator changedGatesIterator = changedGates.begin(); // Update all of the gates and retrieve the events from them: while( changedGatesIterator != changedGates.end() ) { GATE_PTR myGate = gateList[*changedGatesIterator]; myGate->updateGate( *changedGatesIterator, this ); changedGatesIterator++; } // Increment the system timer, because this timestep is complete: systemTime++; // Remove the changedWiresList if we created it ourselves: if( makeYourOwnFreakinChangedWiresList ) delete changedWires; } // step() // Create a new gate, and return its ID: IDType Circuit::newGate( string type, IDType gateID ) { IDType thisGateID; if( gateID == ID_NONE ) { // If no ID is specified for the new gate, then generate one: thisGateID = gateIDCount; gateIDCount++; } else { // Otherwise use the one given and make sure that the ID is not // ever re-used for a generated ID: thisGateID = gateID; gateIDCount = max(gateID + 1, gateIDCount); } // If the gate isn't already created, then make it: if( gateList.find(thisGateID)== gateList.end() ) { // Create a gate of the proper type: if( type == "AND" ) { gateList[thisGateID] = GATE_PTR( new Gate_AND ); } else if( type == "OR" ) { gateList[thisGateID] = GATE_PTR( new Gate_OR ); } else if( type == "XOR" ) { gateList[thisGateID] = GATE_PTR( new Gate_XOR ); } else if( type == "BUFFER" ) { gateList[thisGateID] = GATE_PTR( new Gate_PASS ); } else if( type == "MUX" ) { gateList[thisGateID] = GATE_PTR( new Gate_MUX ); } else if( type == "DECODER" ) { gateList[thisGateID] = GATE_PTR( new Gate_DECODER ); } else if( type == "CLOCK" ) { gateList[thisGateID] = GATE_PTR( new Gate_CLOCK ); // This is a polled gate, so insert it into the polled gates queue! polledGates.insert(thisGateID); } else if( type == "PULSE" ) { gateList[thisGateID] = GATE_PTR( new Gate_PULSE ); // This is a polled gate, so insert it into the polled gates queue! polledGates.insert(thisGateID); } else if( type == "DRIVER" ) { gateList[thisGateID] = GATE_PTR( new Gate_DRIVER ); } else if( type == "ADDER" ) { gateList[thisGateID] = GATE_PTR( new Gate_ADDER ); } else if( type == "COMPARE" ) { gateList[thisGateID] = GATE_PTR( new Gate_COMPARE ); } else if( type == "JKFF" ) { gateList[thisGateID] = GATE_PTR( new Gate_JKFF ); } else if( type == "RAM" ) { gateList[thisGateID] = GATE_PTR( new Gate_RAM ); } else if( type == "REGISTER" ) { gateList[thisGateID] = GATE_PTR( new Gate_REGISTER ); } else if( ( type == "FROM" ) || ( type == "TO" ) ) { gateList[thisGateID] = GATE_PTR( new Gate_JUNCTION( this ) ); } else if( type == "TGATE" ) { gateList[thisGateID] = GATE_PTR( new Gate_T( this ) ); } else if( type == "NODE" ) { gateList[thisGateID] = GATE_PTR( new Gate_NODE( this ) ); } else if( type == "EQUIVALENCE" ) { gateList[thisGateID] = GATE_PTR( new Gate_EQUIVALENCE ); //******************************************************************* // Edit by Joshua Lansford 1/22/06 // This edit is added because Nathan Harro and I are adding a new // gate type!! } else if( type == "Z80" ){ gateList[thisGateID] = GATE_PTR( new Z_80LogicGate() ); // End of edit******************************************************* //******************************** // Edit by Joshua Lansford 4/10/07 // now adding the ADC } else if( type == "ADC" ){ gateList[thisGateID] = GATE_PTR( new Gate_ADC() ); // End of edit******************** //******************************** // Edit by Joshua Lansford 6/05/07 // now adding the pauseulator } else if( type == "Pauseulator" ){ gateList[thisGateID] = GATE_PTR( new Gate_pauseulator() ); // End of edit******************* } else { WARNING( "Circuit::newGate() - Invalid logic type!" ); } } else { WARNING( "Circuit::newGate() - Re-used gate ID!" ); } // Always initialize the non-polled gates, so that it drives some value: //NOTE: Crashed the small computer file for some reason. // if( polledGates.find( thisGateID ) == polledGates.end() ) { // gateUpdateList.insert( gateID ); // } return thisGateID; } // Create a new wire and return its ID: IDType Circuit::newWire( IDType wireID ) { IDType thisWireID; WIRE_PTR myWire(new Wire); if( wireID == ID_NONE ) { // If no ID is specified for the new wire, then generate one: thisWireID = wireIDCount; wireIDCount++; } else { // Otherwise use the one given and make sure that the ID is not // ever re-used for a generated ID: thisWireID = wireID; wireIDCount = max(wireID + 1, wireIDCount); } // If the wire isn't already created, then make it: if( wireList.find(thisWireID) == wireList.end() ) { wireList[thisWireID] = myWire; } else { WARNING( "Circuit::newWire() - Re-used wire ID!" ); } return thisWireID; } // Create a new junction and return its ID: IDType Circuit::newJunction( IDType juncID ) { IDType thisJuncID; if( juncID == ID_NONE ) { // If no ID is specified for the new junction, then generate one: thisJuncID = juncIDCount; juncIDCount++; } else { // Otherwise use the one given and make sure that the ID is not // ever re-used for a generated ID: thisJuncID = juncID; juncIDCount = max(juncID + 1, juncIDCount); } JUNC_PTR myJunc(new Junction(thisJuncID) ); // If the junction isn't already created, then make it: if( juncList.find(thisJuncID) == juncList.end() ) { juncList[thisJuncID] = myJunc; } else { WARNING( "Circuit::newJunction() - Re-used junction ID!" ); } return thisJuncID; } // Delete a gate, removing its connections to wires first: void Circuit::deleteGate( IDType theGate ) { if( gateList.find( theGate ) == gateList.end() ) { WARNING("Circuit::deleteGate() - Invalid gate ID."); return; } GATE_PTR myGate = gateList[ theGate ]; // Delete the gate's inputs: while( myGate->getFirstConnectedInput() != "" ) { disconnectGateInput( theGate, myGate->getFirstConnectedInput() ); } // Remove the gate from the update list, since disconnectGateInput() // will add it, and we don't want it updating after it's gone! gateUpdateList.erase( theGate ); // Delete the gate's outputs: while( myGate->getFirstConnectedOutput() != "" ) { disconnectGateOutput( theGate, myGate->getFirstConnectedOutput() ); } // Remove the gate from the circuit: gateList.erase( theGate ); if ( polledGates.find( theGate ) != polledGates.end() ) polledGates.erase( theGate ); } // Delete a wire, removing its connections from gates first: // (The implementation of this may require that wires keep track // of their input gates.) void Circuit::deleteWire( IDType theWire ) { if( wireList.find( theWire ) == wireList.end() ) { WARNING("Circuit::deleteWire() - Invalid wire ID."); return; } WIRE_PTR myWire = wireList[theWire]; // Delete the wire's inputs: WireInput tempI = myWire->getFirstInput(); while( tempI.gateID != ID_NONE ) { disconnectGateOutput( tempI.gateID, tempI.gateOutputID ); tempI = myWire->getFirstInput(); } // Remove the wire from all connected junctions: // (This will put all of the connected wires into the update list to have their // state updated during the next step.) ID_SET< IDType > wireJuncs = myWire->getJunctions(); ID_SET< IDType >::iterator theJunc = wireJuncs.begin(); while( theJunc != wireJuncs.end() ) { disconnectJunction( *theJunc, theWire ); theJunc++; } // Delete the wire's outputs: WireOutput tempO = myWire->getFirstOutput(); while( tempO.gateID != ID_NONE ) { disconnectGateInput( tempO.gateID, tempO.gateInputID ); tempO = myWire->getFirstOutput(); } // Remove the wire from the update list, since disconnectGateOutput() // and disconnectJunction() will add it, and we don't want it // updating after it's gone! wireUpdateList.erase( theWire ); // Remove the wire from the circuit: wireList.erase( theWire ); } // Delete a junction, removing all its connections from wires first: void Circuit::deleteJunction( IDType theJunc ) { if( juncList.find( theJunc ) == juncList.end() ) { WARNING("Circuit::deleteJunction() - Invalid junction ID."); return; } JUNC_PTR myJunc = juncList[theJunc]; // Unhook all of the junction's connections: // (This will put all of the connected wires into the update list to have their // state updated during the next step.) ID_SET< IDType > juncWires = myJunc->getWires(); ID_SET< IDType >::iterator theWire = juncWires.begin(); while( theWire != juncWires.end() ) { disconnectJunction( theJunc, *theWire ); theWire++; } // Take the junction out of the event list, to avoid calling events on it // after it has been removed. // Empty the priority queue into a temporary stack, filtering out outdated events: stack< Event > tempEventStack; while( !eventQueue.empty() ) { Event tempEvent = eventQueue.top(); if( !((tempEvent.isJunctionEvent) && (tempEvent.junctionID == theJunc)) ) { tempEventStack.push( tempEvent ); } eventQueue.pop(); } // Push the stack back into the event queue: while( !tempEventStack.empty() ) { eventQueue.push( tempEventStack.top() ); tempEventStack.pop(); } // Remove the junction from the circuit: juncList.erase( theJunc ); } /*OBSOLETE // Connect an external event output to this wire, and return a new wire input ID // which the output can connect to: IDType extCount = 0; IDType Circuit::connectExternalWireInput( IDType theWire ) { if( wireList.find( theWire ) != wireList.end() ) { extCount++; // Get a unique ID for the external input. (wireList[theWire])->connectInput(ID_NONE, extCount); return extCount; } else { WARNING("Circuit::connectExternalWireInput() - Invalid wire ID."); return ID_NONE; } } */ // Connect a gate input to the output of a wire: IDType Circuit::connectGateInput( IDType gateID, string gateInputID, IDType wireID ) { IDType returnWireID = 0; // First of all, create the wire if it doesn't already exist: if( wireList.find(wireID) == wireList.end() ) { returnWireID = newWire(wireID); } // Hook the gate input to the wireID: (gateList[gateID])->connectInput( gateInputID, wireID ); // Hook the wire output to the gateID: (wireList[wireID])->connectOutput( gateID, gateInputID ); //TODO: Should trigger some kind of event since the wire now is connected to this here gate, // and therefore the gate's input has changed! // Gate needs to update its state and pass along events if outputs changed. // We basically just need to force it into the update list. gateUpdateList.insert( gateID ); return returnWireID; } // Connect a gate output to the input of a wire: // (The wire will create one unique input for each unique gateID/gateOutputID combination.) IDType Circuit::connectGateOutput( IDType gateID, string gateOutputID, IDType wireID) { IDType returnWireID = 0; // First of all, create the wire if it doesn't already exist: if( wireList.find(wireID) == wireList.end() ) { returnWireID = newWire(wireID); } // Connect the wire input to the gate: (wireList[wireID])->connectInput( gateID, gateOutputID ); // Connect the gate output to the wire: (gateList[gateID])->connectOutput( gateOutputID, wireID ); //TODO: Should trigger some kind of event since the gate is now providing a new input // to this wire, and the wire's state has changed! // Should be: wireinput.state == gate.lastoutput, unless an event is already // scheduled for this gate output. // Could do weird things if we connect a wire between the time a gate issued // an event and the time that it is processed. ,'o) // We need to force the gate to update and re-issue the last event for just this wire. // But it needs to be an event so that the wire will update its output gates, too. // My decision: // I'm going to have the gate output keep track of its last event, and when the // wire is connected, we will simply tell the gate to resend its last event to // the newly connected wire. (gateList[gateID])->resendLastEvent( gateID, gateOutputID, this ); return returnWireID; } // Disconnect a gate input from the output of a wire: void Circuit::disconnectGateInput( IDType gateID, string gateInputID ) { if( gateList.find( gateID ) == gateList.end() ) { WARNING("Circuit::disconnectGateInput() - Invalid gate ID."); return; } GATE_PTR myGate = gateList[ gateID ]; // Disconnect the gate from the wire: IDType theWire = myGate->disconnectInput( gateInputID ); // Disconnect the wire from the gate: if( wireList.find( theWire ) != wireList.end() ) { WIRE_PTR myWire = wireList[ theWire ]; myWire->disconnectOutput(gateID, gateInputID ); } else if( theWire != ID_NONE ) { WARNING("Circuit::disconnectGateInput() - Wire not found."); } //TODO: Trigger event to update gate. // Gate needs to update its state and pass along events if outputs changed. // We basically just need to force it into the update list. gateUpdateList.insert( gateID ); } // Disconnect a gate output from the input of a wire: void Circuit::disconnectGateOutput( IDType gateID, string gateOutputID ) { if( gateList.find( gateID ) == gateList.end() ) { WARNING("Circuit::disconnectGateOutput() - Invalid gate ID."); return; } GATE_PTR myGate = gateList[ gateID ]; // Wire needs to update based on its other inputs and // cause its output gates to update as well. Just force it onto the update list. // ADDITION: All wires connected by junctions also need to be updated, and // the list needs to be made *before* the wire is disconnected. IDType theWire = myGate->getOutputWire( gateOutputID ); ID_SET< IDType > juncWires = getJunctionGroupIDs( theWire ); wireUpdateList.insert( juncWires.begin(), juncWires.end() ); // Disconnect the gate from the wire: myGate->disconnectOutput( gateOutputID ); // Disconnect the wire from the gate: if( wireList.find( theWire ) != wireList.end() ) { WIRE_PTR myWire = wireList[ theWire ]; myWire->disconnectInput(gateID, gateOutputID ); } else if( theWire != ID_NONE ) { WARNING("Circuit::disconnectGateOutput() - Wire not found."); return; } // You also have to clear the event queue of any events scheduled for this // gate/gateOutput combination. // Empty the priority queue into a temporary stack, filtering out outdated events: stack< Event > tempEventStack; while( !eventQueue.empty() ) { Event tempEvent = eventQueue.top(); if( !((!tempEvent.isJunctionEvent) && (tempEvent.gateID == gateID) && (tempEvent.gateOutputID == gateOutputID)) ) { tempEventStack.push( tempEvent ); } eventQueue.pop(); } // Push the stack back into the event queue: while( !tempEventStack.empty() ) { eventQueue.push( tempEventStack.top() ); tempEventStack.pop(); } return; } // Connect a junction to a wire: void Circuit::connectJunction( IDType juncID, IDType wireID ) { //TODO: Warn the user when a junction cannot happen! if( juncList.find( juncID ) == juncList.end() ) return; if( wireList.find( wireID ) == wireList.end() ) return; // Get the junction and wire: JUNC_PTR myJunc = juncList[juncID]; WIRE_PTR myWire = wireList[wireID]; // Link the wire to the junction. myJunc->connectWire( wireID ); // Connect the wire to the junction: myWire->addJunction( juncID ); // Put all the wires of the junction group into the update list to have its // state updated during the next step. // (Note: Do this before after hooking up the wire!) ID_SET< IDType > juncWires = getJunctionGroupIDs( wireID ); wireUpdateList.insert( juncWires.begin(), juncWires.end() ); } // Unhook a junction from a wire: void Circuit::disconnectJunction( IDType juncID, IDType wireID ) { //TODO: Warn the user when a junction cannot happen! if( juncList.find( juncID ) == juncList.end() ) return; if( wireList.find( wireID ) == wireList.end() ) return; // Put all the wires of the junction group into the update list to have its // state updated during the next step. // (Note: Do this before unhooking the wire!) ID_SET< IDType > juncWires = getJunctionGroupIDs( wireID ); wireUpdateList.insert( juncWires.begin(), juncWires.end() ); // Get the junction and wire: JUNC_PTR myJunc = juncList[juncID]; WIRE_PTR myWire = wireList[wireID]; // Unlink the wire from the junction. if( myJunc->disconnectWire( wireID ) ) { // If the junction has no more of this wire // connected to it, then unhook the wire from the junction: myWire->removeJunction( juncID ); } } // Create an event and put it in the event queue: void Circuit::createEvent( TimeType eventTime, IDType wireID, IDType gateID, string gateOutputID, StateType newState ) { Event myEvent; myEvent.eventTime = eventTime; myEvent.wireID = wireID; myEvent.gateID = gateID; myEvent.gateOutputID = gateOutputID; myEvent.newState = newState; ostringstream oss; oss << "Creating event for gate " << gateID << " output " << gateOutputID << " to state " << (int) newState << " at time = " << eventTime << "." << endl; WARNING(oss.str()); #ifdef INERTIAL_DELAY // Erase any other events in the queue with this gate output: // Clear the event queue of any events scheduled for this gate/gateOutput combination: // Empty the priority queue into a temporary stack, filtering out outdated events: stack< Event > tempEventStack; while( !eventQueue.empty() ) { Event tempEvent = eventQueue.top(); if( !((!tempEvent.isJunctionEvent) && (tempEvent.gateID == gateID) && (tempEvent.gateOutputID == gateOutputID)) ) { tempEventStack.push( tempEvent ); } eventQueue.pop(); } // Push the stack back into the event queue: while( !tempEventStack.empty() ) { eventQueue.push( tempEventStack.top() ); tempEventStack.pop(); } #endif // Push the event onto the event queue: eventQueue.push(myEvent); } // Create an event that occurs at systemTime + delay: TimeType Circuit::createDelayedEvent( TimeType delay, IDType wireID, IDType gateID, string gateOutputID, StateType newState ) { if( (wireID != ID_NONE) && (gateOutputID != "") ) { createEvent( delay + getSystemTime(), wireID, gateID, gateOutputID, newState ); } return delay + getSystemTime(); } // Create Junction Event and put it in the event queue: void Circuit::createJunctionEvent( TimeType eventTime, IDType juncID, bool newState ) { Event myEvent; myEvent.eventTime = eventTime; myEvent.isJunctionEvent = true; myEvent.newJunctionState = newState; myEvent.junctionID = juncID; #ifdef INERTIAL_DELAY // Erase any other events in the queue with this gate output: // Clear the event queue of any events scheduled for this gate/gateOutput combination: // Empty the priority queue into a temporary stack, filtering out outdated events: stack< Event > tempEventStack; while( !eventQueue.empty() ) { Event tempEvent = eventQueue.top(); if( !((tempEvent.isJunctionEvent) && (tempEvent.junctionID == juncID)) ) { tempEventStack.push( tempEvent ); } eventQueue.pop(); } // Push the stack back into the event queue: while( !tempEventStack.empty() ) { eventQueue.push( tempEventStack.top() ); tempEventStack.pop(); } #endif // Push the event onto the event queue: eventQueue.push(myEvent); } // Clear out the event queue, destroying all events, // and also erase all events in the gateUpdateList and wireUpdateList. // This is used if we wanted a simulation where all of the wires // start with "UNKNOWN" state and don't update until a signal // from the outside world reaches them. void Circuit::destroyAllEvents( void ) { while( !eventQueue.empty() ) { eventQueue.pop(); } gateUpdateList.clear(); wireUpdateList.clear(); } // Set a gate parameter: // (If the gate's parameter change requires the gate to be // re-evaluated during the next cycle, then add it to the void Circuit::setGateParameter( IDType gateID, string paramName, string value ) { if( gateList.find( gateID ) != gateList.end() ) { if( gateList[gateID]->setParameter( paramName, value ) ) { // If the gate has changed parameters and needs updated, then // add it to the gateUpdateList: gateUpdateList.insert( gateID ); } } else { WARNING("Circuit::setGateParameter() - Gate not found."); } return; } void Circuit::setGateInputParameter( IDType gateID, string inputID, string paramName, string value ) { if( gateList.find( gateID ) != gateList.end() ) { if( gateList[gateID]->setInputParameter( inputID, paramName, value ) ) { // If the gate has changed parameters and needs updated, then // add it to the gateUpdateList: gateUpdateList.insert( gateID ); } } else { WARNING("Circuit::setGateParameter() - Gate not found."); } return; } void Circuit::setGateOutputParameter( IDType gateID, string outputID, string paramName, string value ) { if( gateList.find( gateID ) != gateList.end() ) { if( gateList[gateID]->setOutputParameter( outputID, paramName, value ) ) { // If the gate has changed parameters and needs updated, then // add it to the gateUpdateList: gateUpdateList.insert( gateID ); } } else { WARNING("Circuit::setGateParameter() - Gate not found."); } return; } // ************ Circuit inspection methods ************** // Get the value of a gate parameter: string Circuit::getGateParameter( IDType gateID, string paramName ) { if( gateList.find( gateID ) != gateList.end() ) { return gateList[ gateID ]->getParameter( paramName ); } else { WARNING("Circuit::setGateParameter() - Gate not found."); } return ""; } // Get a wire state by ID: StateType Circuit::getWireState( IDType wireID ) { if( wireList.find( wireID ) != wireList.end() ) { return wireList[wireID]->getState(); } else { WARNING("Circuit::getWireState() - Wire does not exist."); return UNKNOWN; } } // Get and set a junction's on/off toggle state: void Circuit::setJunctionState( IDType juncID, bool newState ) { //TODO: Warn the user when a junction doesn't exist! if( juncList.find( juncID ) == juncList.end() ) return; // Get the junction: JUNC_PTR myJunc = juncList[juncID]; myJunc->setEnableState( newState ); // Put all of the connected wires into the "wireUpdateList" list to have their // state updated during the next (or current) step() call. //NOTE: MUST add ALL wires in ALL junction nodes that are attached to this junction! ID_SET< IDType > juncWires = myJunc->getWires(); ID_SET< IDType >::iterator juncWire = juncWires.begin(); while( juncWire != juncWires.end() ) { ID_SET< IDType > juncGroup = getJunctionGroupIDs( *juncWire ); wireUpdateList.insert( juncGroup.begin(), juncGroup.end() ); juncWire++; } } bool Circuit::getJunctionState( IDType juncID ) { //TODO: Warn the user when a junction doesn't exist! if( juncList.find( juncID ) == juncList.end() ) return false; // Get the junction: JUNC_PTR myJunc = juncList[juncID]; return myJunc->getEnableState(); } // Return the current simulation time: TimeType Circuit::getSystemTime( void ) { return systemTime; } // Returns a list of IDs of wires that are connected to this // wire via junctions: set< IDType > Circuit::getJunctionGroupIDs( IDType wireID ) { // This is the wire group IDs that will be returned: set< IDType > wireGroupIDs; //TODO: Warn the user when a wire does not exist! if( wireList.find( wireID ) == wireList.end() ) return wireGroupIDs; // This wire is automatically included in the group: WIRE_PTR thisWire = wireList[wireID]; wireGroupIDs.insert( wireID ); // This is the set of wires left to be searched: set< IDType > searchList = wireGroupIDs; // Do a breadth-first search to add other wires into the list: // Loop through any wires that are left to be checked: while( !searchList.empty() ) { // Pop the first item off of the searching list: IDType thisWireID = *(searchList.begin()); searchList.erase( thisWireID ); // Loop through all the junctions in this wire. thisWire = wireList[thisWireID]; set< IDType > wireJuncs = thisWire->getJunctions(); set< IDType >::iterator thisJunc = wireJuncs.begin(); while( thisJunc != wireJuncs.end() ) { // If the junction is marked as "enabled", then // add all of its wires into the group: if( getJunctionState( *thisJunc ) ) { set< IDType > juncWires = juncList[*thisJunc]->getWires(); // Add all of the new wires into the "yet to check" list: set_difference( juncWires.begin(), juncWires.end(), wireGroupIDs.begin(), wireGroupIDs.end(), inserter( searchList, searchList.begin() ) ); // Add the new wires to the "found attached" list: wireGroupIDs.insert( juncWires.begin(), juncWires.end() ); } thisJunc++; } } // while( !searchList.empty() ) return wireGroupIDs; } // Returns a list of all wires that are connected to this // wire via junctions: set< WIRE_PTR > Circuit::getJunctionGroup( IDType wireID ) { // This is the wire group that will be returned: set< WIRE_PTR > wireGroup; // Get the IDs of connected wires: set< IDType > wireGroupIDs = getJunctionGroupIDs( wireID ); // Convert all of the wire IDs into wire pointers: set< IDType >::iterator wireIDs = wireGroupIDs.begin(); while( wireIDs != wireGroupIDs.end() ) { IDType theWireID = *wireIDs; WIRE_PTR theWirePtr = wireList[ theWireID ]; wireGroup.insert( theWirePtr ); wireIDs++; } return wireGroup; } // Convert the wire IDs to wire pointers: set< WIRE_PTR > Circuit::getJunctionGroup( set< IDType >* wireGroupIDs ) { // This is the wire group that will be returned: set< WIRE_PTR > wireGroup; // Convert all of the wire IDs into wire pointers: set< IDType >::iterator wireIDs = wireGroupIDs->begin(); while( wireIDs != wireGroupIDs->end() ) { IDType theWireID = *wireIDs; WIRE_PTR theWirePtr = wireList[ theWireID ]; wireGroup.insert( theWirePtr ); wireIDs++; } return wireGroup; } // ************* End of the visible interface of the circuit ****************
32.788423
154
0.681957
[ "vector" ]
caefd845ceb99e8ebacf03715ca6660c826f026e
5,174
cpp
C++
src/LMR/cpm_LeafCommInfo.cpp
jorji/CPMlib
7ba683d1abc60f11bafcc5732da831278b002afa
[ "BSD-2-Clause" ]
4
2015-03-17T17:30:10.000Z
2019-01-31T15:13:59.000Z
src/LMR/cpm_LeafCommInfo.cpp
jorji/CPMlib
7ba683d1abc60f11bafcc5732da831278b002afa
[ "BSD-2-Clause" ]
null
null
null
src/LMR/cpm_LeafCommInfo.cpp
jorji/CPMlib
7ba683d1abc60f11bafcc5732da831278b002afa
[ "BSD-2-Clause" ]
4
2015-12-09T02:42:29.000Z
2022-03-18T09:03:28.000Z
/* ################################################################################### # # CPMlib - Computational space Partitioning Management library # # Copyright (c) 2012-2014 Institute of Industrial Science (IIS), The University of Tokyo. # All rights reserved. # # Copyright (c) 2014-2016 Advanced Institute for Computational Science (AICS), RIKEN. # All rights reserved. # # Copyright (c) 2016-2017 Research Institute for Information Technology (RIIT), Kyushu University. # All rights reserved. # ################################################################################### */ /** * @file cpm_LeafCommInfo.cpp * LMRの袖通信情報管理クラスソースファイル * @date 2016/07/29 */ #include "cpm_LeafCommInfo.h" //////////////////////////////////////////////////////////////////////////////// // コンストラクタ cpm_LeafCommInfo::cpm_LeafCommInfo(int distRankID) { m_iDistRankNo = distRankID; m_vecCommInfo.clear(); m_pCommSendBuf = NULL; m_pCommRecvBuf = NULL; m_reqSend = MPI_REQUEST_NULL; m_reqRecv = MPI_REQUEST_NULL; } //////////////////////////////////////////////////////////////////////////////// // デストラクタ cpm_LeafCommInfo::~cpm_LeafCommInfo() { for( int i=0;i<m_vecCommInfo.size();i++ ) { delete m_vecCommInfo[i]; } m_vecCommInfo.clear(); delete [] m_pCommSendBuf; delete [] m_pCommRecvBuf; m_pCommSendBuf = NULL; m_pCommRecvBuf = NULL; } //////////////////////////////////////////////////////////////////////////////// // CommInfoを追加 void cpm_LeafCommInfo::AddCommInfo(stCommInfo *commInfo) { m_vecCommInfo.push_back(commInfo); } //////////////////////////////////////////////////////////////////////////////// // CommInfoリストのソート // type ソートタイプ(0:自身のリーフ番号でソート, 1:相手のリーフ番号でソート) // 0のときは自身のリーフ番号を優先1、相手のリーフ番号を優先2としてソートする // 1のときは相手のリーフ番号を優先1、自身のリーフ番号を優先2としてソートする void cpm_LeafCommInfo::Sort( int type ) { if( m_vecCommInfo.size() == 0 ) { return; } // 優先1でソート Qsort(type, m_vecCommInfo, 0, (int)m_vecCommInfo.size()-1); // 優先2でソート int type2 = 1 - type; int iStart = 0; int iEnd = iStart; while( iEnd < m_vecCommInfo.size()-1 ) { // 優先1の同じリーフIDのインデクス範囲を検索 int leafID = m_vecCommInfo[iStart]->GetLeafID(type); for( int i=iStart+1;i<(int)m_vecCommInfo.size();i++ ) { if( m_vecCommInfo[i]->GetLeafID(type) == leafID ) { iEnd = i; } else { break; } } // 優先2でソート if( iEnd > iStart ) { Qsort(type2, m_vecCommInfo, iStart, iEnd); } // 次の範囲を検索 iStart = iEnd + 1; iEnd = iStart; } } //////////////////////////////////////////////////////////////////////////////// // CommInfoリストのクイックソート void cpm_LeafCommInfo::Qsort( int type, std::vector<stCommInfo*> &vecCommInfo, int iStart, int iEnd ) { if( iStart >= iEnd ) return; //終了番号が開始番号以下の場合、関数を抜ける int iBaseNumber = (iStart + iEnd) / 2; //中央のインデックスを求める stCommInfo *BaseValue = vecCommInfo[iBaseNumber]; //配列の真ん中の値を基準値にする vecCommInfo[iBaseNumber] = vecCommInfo[iStart]; //中央の要素に開始番号の値を格納 int iCounter = iStart; //格納位置カウンタを開始番号と同じにする //大小比較と入れ替え for( int i=iStart+1;i<=iEnd;i++ ) //開始番号の次の要素から終了番号までループ { if( vecCommInfo[i]->GetLeafID(type) < BaseValue->GetLeafID(type) ) //大小で比較 { iCounter++; //格納位置カウンタをインクリメント stCommInfo *Buffer = vecCommInfo[iCounter]; //[i] と [vntCounter] の値をスワップ vecCommInfo[iCounter] = vecCommInfo[i]; vecCommInfo[i] = Buffer; } } vecCommInfo[iStart] = vecCommInfo[iCounter]; //[iCounter]を開始番号の値にする vecCommInfo[iCounter] = BaseValue; //基準値を[iCounter]に格納 Qsort(type, vecCommInfo, iStart, iCounter-1); //分割された配列をクイックソート(再帰) Qsort(type, vecCommInfo, iCounter+1, iEnd); //分割された配列をクイックソート(再帰) } //////////////////////////////////////////////////////////////////////////////// // 袖通信バッファのセット bool cpm_LeafCommInfo::SetBndCommBuffer( int myRankNo, size_t sz_face[2], size_t maxVC, size_t maxN ) { m_CommSendBufSize = 0; m_CommRecvBufSize = 0; m_pCommSendBuf = NULL; m_pCommRecvBuf = NULL; // 各経路ごとに計算、加算 for( int i=0;i<m_vecCommInfo.size();i++ ) { // 送受信バッファサイズをそれぞれ加算 m_CommSendBufSize += m_vecCommInfo[i]->CalcSendBufferSize(sz_face, maxVC, maxN); m_CommRecvBufSize += m_vecCommInfo[i]->CalcRecvBufferSize(sz_face, maxVC, maxN); } m_pCommSendBuf = new REAL_BUF_TYPE[m_CommSendBufSize]; m_pCommRecvBuf = new REAL_BUF_TYPE[m_CommRecvBufSize]; if( !m_pCommSendBuf || !m_pCommRecvBuf ) { return false; } return true; } //////////////////////////////////////////////////////////////////////////////// // 対となる通信情報を検索 cpm_LeafCommInfo::stCommInfo* cpm_LeafCommInfo::SearchDistCommInfo(cpm_LeafCommInfo::stCommInfo *commInfo) { for( size_t i=0;i<m_vecCommInfo.size();i++ ) { stCommInfo *commInfoDist = m_vecCommInfo[i]; // OwnLeafとDistLeafが入れ替わりでbPeriodicが同じ通信情報かどうか if( commInfoDist->iOwnLeafID == commInfo->iDistLeafID && commInfoDist->iDistLeafID == commInfo->iOwnLeafID && commInfoDist->bPeriodic == commInfo->bPeriodic ) { return commInfoDist; } } return NULL; }
27.668449
106
0.57673
[ "vector" ]
cafca702eef73eb0a7561a6fc594506ab11ee039
2,628
cpp
C++
Example/Visualization/VisualizationPipeline/main.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Example/Visualization/VisualizationPipeline/main.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Example/Visualization/VisualizationPipeline/main.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /** * @file main.cpp * @brief Example program for kvs::VisualizationPipeline class. * @author Naohisa Sakamoto */ /*****************************************************************************/ #include <kvs/Message> #include <kvs/VisualizationPipeline> #include <kvs/glut/Application> #include <kvs/glut/Screen> /*===========================================================================*/ /** * @brief Main function. * @param argc [i] argument count * @param argv [i] argument values * @return 0, if the process is done successfully. */ /*===========================================================================*/ int main( int argc, char** argv ) { kvs::glut::Application app( argc, argv ); // Visualization pipeline. const std::string filename( argc > 1 ? argv[1] : "" ); kvs::VisualizationPipeline pipeline( filename ); /* Execute the visualization pipeline by caling the 'exec' method. * * You can confirm whether the pipeline is executed successfully or not * by checking the return value of the 'exec' method. * * In case that any pipeline modules is connected to the pipeline, the * suitable file format class, importer class and renderer class are * automatically estimated and connected. If you want to use some KVS module, * for example kvs::MarchingCubes to extract surfaces from a volume object, * the pipeline can be connected as follows: * * // Input parameters for Marching cubes. * double isolevel = 100; * kvs::PolygonObject::NormalType normal = kvs::PolygonObject::PolygonNormal; * kvs::TransferFunction transfer_function( 256 ); * // Create a marching cubes module. * kvs::PipelineModule mapper( new kvs::MarchingCubes ); * mapper.get<kvs::MarchingCubes>()->setTransferFunction( transfer_function ); * mapper.get<kvs::MarchingCubes>()->setNormalType( normal ); * mapper.get<kvs::MarchingCubes>()->setIsolevel( isolevel ); * // Connect to the pipeline. * pipeline.connect( mapper ); */ if ( !pipeline.exec() ) { kvsMessageError("Cannot execute the visulization pipeline."); return( false ); } // Output the visualization pipeline as a string. pipeline.print(); // Screen. kvs::glut::Screen screen( &app ); screen.registerObject( &pipeline ); screen.setGeometry( 0, 0, 512, 512 ); screen.setTitle( "kvs::VisualizationPipeline" ); screen.show(); return( app.run() ); }
37.014085
85
0.574581
[ "object" ]
1b09d96180e7bc411bbdd6b57bf2df6f68397288
12,750
cpp
C++
SYCL/GroupAlgorithm/SYCL2020/sort.cpp
AerialMantis/llvm-test-suite
c28d0d3b7a26f069f904d652a974968c5e40e994
[ "Apache-2.0" ]
10
2020-08-04T04:29:03.000Z
2022-02-23T21:43:56.000Z
SYCL/GroupAlgorithm/SYCL2020/sort.cpp
AerialMantis/llvm-test-suite
c28d0d3b7a26f069f904d652a974968c5e40e994
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
SYCL/GroupAlgorithm/SYCL2020/sort.cpp
AerialMantis/llvm-test-suite
c28d0d3b7a26f069f904d652a974968c5e40e994
[ "Apache-2.0" ]
117
2020-06-24T13:11:04.000Z
2022-03-23T15:44:23.000Z
// RUN: %clangxx -fsycl -fsycl-targets=%sycl_triple %s -I . -o %t.out // RUN: %CPU_RUN_PLACEHOLDER %t.out // RUN: %GPU_RUN_PLACEHOLDER %t.out // RUN: %ACC_RUN_PLACEHOLDER %t.out // // RUNx: %clangxx -fsycl -fsycl-targets=%sycl_triple %s -I . -o %t13.out #include "support.h" #include <CL/sycl.hpp> #include <algorithm> #include <iostream> #include <random> #include <vector> namespace my_sycl = sycl::ext::oneapi; auto async_handler_ = [](sycl::exception_list ex_list) { for (auto &ex : ex_list) { try { std::rethrow_exception(ex); } catch (sycl::exception &ex) { std::cerr << ex.what() << std::endl; std::exit(EXIT_FAILURE); } } }; constexpr uint32_t items_per_work_item = 4; struct CustomType { int x; }; struct CustomFunctor { bool operator()(const CustomType &lhs, const CustomType &rhs) const { return lhs.x < rhs.x; } }; // we need it since using std::abs leads to compilation error template <typename T> T my_abs(T x) { return x >= 0 ? x : -x; } template <typename T> bool check(T lhs, T rhs, float epsilon) { return my_abs(lhs - rhs) > epsilon; } bool check(CustomType lhs, CustomType rhs, float epsilon) { return my_abs(lhs.x - rhs.x) > epsilon; } template <typename T> bool verify(T *expected, T *got, std::size_t n, float epsilon) { for (std::size_t i = 0; i < n; ++i) { if (check(expected[i], got[i], epsilon)) { return false; } } return true; } // forward declared classes to name kernels template <typename... Args> class sort_over_group_kernel_name; template <typename... Args> class joint_sort_kernel_name; template <typename... Args> class custom_sorter_kernel_name; // this class is needed to pass dimension value to aforementioned classes template <int dim> class int_wrapper; // custom sorter template <typename Compare> struct bubble_sorter { Compare comp; size_t idx; template <typename Group, typename Ptr> void operator()(Group g, Ptr begin, Ptr end) { size_t n = end - begin; if (idx == 0) for (size_t i = 0; i < n; ++i) for (size_t j = i + 1; j < n; ++j) if (comp(begin[j], begin[i])) std::swap(begin[i], begin[j]); } }; template <int dim> sycl::range<dim> get_range(const std::size_t local); template <> sycl::range<1> get_range<1>(const std::size_t local) { return sycl::range<1>(local); } template <> sycl::range<2> get_range<2>(const std::size_t local) { return sycl::range<2>(local, 1); } template <> sycl::range<3> get_range<3>(const std::size_t local) { return sycl::range<3>(local, 1, 1); } template <int dim, typename T, typename Compare> int test_sort_over_group(sycl::queue &q, std::size_t local, sycl::buffer<T> &bufI1, Compare comp, int test_case) { auto n = bufI1.size(); if (n > local) return -1; sycl::range<dim> local_range = get_range<dim>(local); std::size_t local_memory_size = my_sycl::experimental::default_sorter<>::memory_required<T>( sycl::memory_scope::work_group, local_range); if (local_memory_size > q.get_device().template get_info<sycl::info::device::local_mem_size>()) std::cout << "local_memory_size = " << local_memory_size << ", available = " << q.get_device() .template get_info<sycl::info::device::local_mem_size>() << std::endl; q.submit([&](sycl::handler &h) { auto aI1 = sycl::accessor(bufI1, h); sycl::accessor<std::byte, 1, sycl::access_mode::read_write, sycl::access::target::local> scratch({local_memory_size}, h); h.parallel_for<sort_over_group_kernel_name<int_wrapper<dim>, T, Compare>>( sycl::nd_range<dim>(local_range, local_range), [=](sycl::nd_item<dim> id) { scratch[0] = std::byte{}; auto local_id = id.get_local_linear_id(); switch (test_case) { case 0: if constexpr (std::is_same_v<Compare, std::less<T>> && !std::is_same_v<T, CustomType>) aI1[local_id] = my_sycl::sort_over_group( my_sycl::experimental::group_with_scratchpad( id.get_group(), sycl::span{&scratch[0], local_memory_size}), aI1[local_id]); break; case 1: aI1[local_id] = my_sycl::sort_over_group( my_sycl::experimental::group_with_scratchpad( id.get_group(), sycl::span{&scratch[0], local_memory_size}), aI1[local_id], comp); break; case 2: aI1[local_id] = my_sycl::sort_over_group( id.get_group(), aI1[local_id], my_sycl::experimental::default_sorter<Compare>( sycl::span{&scratch[0], local_memory_size})); break; } }); }).wait_and_throw(); return 1; } template <typename T, typename Compare> int test_joint_sort(sycl::queue &q, std::size_t n_items, std::size_t local, sycl::buffer<T> &bufI1, Compare comp, int test_case) { auto n = bufI1.size(); auto n_groups = (n - 1) / n_items + 1; std::size_t local_memory_size = my_sycl::experimental::default_sorter<>::memory_required<T>( sycl::memory_scope::work_group, n); if (local_memory_size > q.get_device().template get_info<sycl::info::device::local_mem_size>()) std::cout << "local_memory_size = " << local_memory_size << ", available = " << q.get_device() .template get_info<sycl::info::device::local_mem_size>() << std::endl; q.submit([&](sycl::handler &h) { auto aI1 = sycl::accessor(bufI1, h); sycl::accessor<std::byte, 1, sycl::access_mode::read_write, sycl::access::target::local> scratch({local_memory_size}, h); h.parallel_for<joint_sort_kernel_name<T, Compare>>( sycl::nd_range<1>{{n_groups * local}, {local}}, [=](sycl::nd_item<1> id) { auto group_id = id.get_group(0); auto ptr_keys = &aI1[group_id * n_items]; // Replacing the line above with the line below also works // auto ptr_keys = aI1.get_pointer() + group_id * n_items; scratch[0] = std::byte{}; switch (test_case) { case 0: if constexpr (std::is_same_v<Compare, std::less<T>> && !std::is_same_v<T, CustomType>) my_sycl::joint_sort( my_sycl::experimental::group_with_scratchpad( id.get_group(), sycl::span{&scratch[0], local_memory_size}), ptr_keys, ptr_keys + sycl::min(n_items, n - group_id * n_items)); break; case 1: my_sycl::joint_sort( my_sycl::experimental::group_with_scratchpad( id.get_group(), sycl::span{&scratch[0], local_memory_size}), ptr_keys, ptr_keys + sycl::min(n_items, n - group_id * n_items), comp); break; case 2: my_sycl::joint_sort( id.get_group(), ptr_keys, ptr_keys + sycl::min(n_items, n - group_id * n_items), my_sycl::experimental::default_sorter<Compare>( sycl::span{&scratch[0], local_memory_size})); break; } }); }).wait_and_throw(); return n_groups; } template <typename T, typename Compare> int test_custom_sorter(sycl::queue &q, sycl::buffer<T> &bufI1, Compare comp) { std::size_t local = 256; auto n = bufI1.size(); if (n > local) return -1; local = std::min(local, n); q.submit([&](sycl::handler &h) { auto aI1 = sycl::accessor(bufI1, h); h.parallel_for<custom_sorter_kernel_name<T, Compare>>( sycl::nd_range<2>({local, 1}, {local, 1}), [=](sycl::nd_item<2> id) { auto ptr = aI1.get_pointer(); my_sycl::joint_sort( id.get_group(), ptr, ptr + n, bubble_sorter<Compare>{comp, id.get_local_linear_id()}); }); }).wait_and_throw(); return 1; } template <typename T, typename Compare> void run_sort(sycl::queue &q, std::vector<T> &in, std::size_t size, Compare comp, int test_case, int sort_case) { std::vector<T> in2(in.begin(), in.begin() + size); std::vector<T> expected(in.begin(), in.begin() + size); std::size_t local = q.get_device() .template get_info<sycl::info::device::max_work_group_size>(); local = std::min(local, size); auto n_items = items_per_work_item * local; int n_groups = 1; { // scope to destruct buffers sycl::buffer<T> bufKeys(in2.data(), size); { switch (sort_case) { case 0: // this case is just to check the compilation n_groups = test_sort_over_group<1>(q, local, bufKeys, comp, test_case); n_groups = test_sort_over_group<2>(q, local, bufKeys, comp, test_case); break; case 1: n_groups = test_joint_sort(q, n_items, local, bufKeys, comp, test_case); break; case 2: n_groups = test_custom_sorter(q, bufKeys, comp); break; } } } // check results for (int i_group = 0; i_group < n_groups; ++i_group) { std::sort(expected.begin() + i_group * n_items, expected.begin() + std::min((i_group + 1) * n_items, size), comp); } if (n_groups != -1 && (test_case != 0 || test_case == 0 && std::is_same_v<Compare, std::less<T>> && !std::is_same_v<T, CustomType>)&&!verify(expected.data(), in2.data(), size, 0.001f)) { std::cerr << "Verification failed \n"; exit(1); } } template <typename T> struct test_sort_cases { template <typename Generator, typename Compare> void operator()(sycl::queue &q, std::size_t dataSize, Compare comp, Generator generate) { std::vector<T> stationaryData(dataSize); // fill data for (std::size_t i = 0; i < dataSize; ++i) stationaryData[i] = generate(i); // run test for (int test_case = 0; test_case < 3; ++test_case) { for (int sort_case = 0; sort_case < 3; ++sort_case) { run_sort(q, stationaryData, dataSize, comp, test_case, sort_case); } } } }; void test_custom_type(sycl::queue &q, std::size_t dataSize) { std::vector<CustomType> stationaryData(dataSize, CustomType{0}); // fill data for (std::size_t i = 0; i < dataSize; ++i) stationaryData[i] = CustomType{int(i)}; // run test for (int test_case = 0; test_case < 1; ++test_case) { for (int sort_case = 0; sort_case < 3; ++sort_case) { run_sort(q, stationaryData, dataSize, CustomFunctor{}, test_case, sort_case); } } } template <typename T, typename Compare> void test_sort_by_comp(sycl::queue &q, std::size_t dataSize) { std::default_random_engine generator; std::normal_distribution<float> distribution((10.0), (2.0)); T max_size = std::numeric_limits<T>::max(); std::size_t to_fill = dataSize; if (dataSize > max_size) to_fill = max_size; // reversed order test_sort_cases<T>()(q, to_fill, Compare{}, [to_fill](std::size_t i) { return T(to_fill - i - 1); }); // filled by 1 test_sort_cases<T>()(q, dataSize, Compare{}, [](std::size_t) { return T(1); }); // random distribution test_sort_cases<T>()(q, dataSize, Compare{}, [&distribution, &generator](std::size_t) { return T(distribution(generator)); }); } template <typename T> void test_sort_by_type(sycl::queue &q, std::size_t dataSize) { test_sort_by_comp<T, std::less<T>>(q, dataSize); test_sort_by_comp<T, std::greater<T>>(q, dataSize); } int main(int argc, char *argv[]) { sycl::queue q(sycl::default_selector{}, async_handler_); if (!isSupportedDevice(q.get_device())) { std::cout << "Skipping test\n"; return 0; } std::vector<int> sizes{1, 2, 64, 256, 1024, 2048, 4096}; for (int i = 0; i < sizes.size(); ++i) { test_sort_by_type<std::int8_t>(q, sizes[i]); test_sort_by_type<std::uint16_t>(q, sizes[i]); test_sort_by_type<std::int32_t>(q, sizes[i]); test_sort_by_type<std::uint32_t>(q, sizes[i]); test_sort_by_type<float>(q, sizes[i]); test_sort_by_type<sycl::half>(q, sizes[i]); test_sort_by_type<double>(q, sizes[i]); test_sort_by_type<std::size_t>(q, sizes[i]); test_custom_type(q, sizes[i]); } std::cout << "Test passed." << std::endl; }
34
80
0.588863
[ "vector" ]
db47084c28d2eafda50a7858c1ee841c38deb359
1,748
cpp
C++
labosi/lab-2/2019-20/by_KitKat/struk.cpp
studosi-fer/DISMATe1
d34de1f54c9607602521af311c55e7cacd16c411
[ "Apache-2.0" ]
null
null
null
labosi/lab-2/2019-20/by_KitKat/struk.cpp
studosi-fer/DISMATe1
d34de1f54c9607602521af311c55e7cacd16c411
[ "Apache-2.0" ]
null
null
null
labosi/lab-2/2019-20/by_KitKat/struk.cpp
studosi-fer/DISMATe1
d34de1f54c9607602521af311c55e7cacd16c411
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <queue> #include <fstream> #include <string> using namespace std; #define N 100200 const int MAX = 20; vector<int> gr[N]; // bridovi void Add_edge(int x, int y) { gr[x].push_back(y); gr[y].push_back(x); } int struk(int n) { // pomocna varijabla za dulj ciklusa int ans = INT_MAX; // za sve vrhove for (int i = 0; i < n; i++) { // neka je udaljenost max vector<int> dist(n, (int)(1e9)); vector<int> par(n, -1); // udaljenost od sourcea do sourcea je 0 dist[i] = 0; queue<int> q; // Push source q.push(i); // Nastavi sve dok queue ne bude prazan while (!q.empty()) { // uzmi prvi int x = q.front(); q.pop(); // i idi po redu for (int child : gr[x]) { // ako nije jos posjecen, dist ++ if (dist[child] == (int)(1e9)) { dist[child] = 1 + dist[x]; par[child] = x; q.push(child); } // ako vec je posjecen else if (par[x] != child and par[child] != x) ans = min(ans, dist[x] + dist[child] + 1); } } } // nema ciklusa if (ans == INT_MAX) return -1; // ima ciklusa else return ans; } int main() { int rez; int i, j; ifstream stream; string fileName; cout << "Unesite ime datoteke: "; cin >> fileName; stream.open(fileName); int n = 0; stream >> n; int mat[MAX][MAX]; stream.ignore(1, '\n'); for ( i = 0; i < n; i++) { for ( j = 0; j < n; j++) { stream >> mat[i][j]; } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (mat[i][j] == 1) Add_edge(i, j); } } rez = struk(n); if (rez == -1) cout << "Graf nema ciklusa"; else cout << "Minimalni ciklus grafa je " << rez; getchar(); getchar(); return 0; }
14.940171
49
0.540618
[ "vector" ]
db4d2ec0db929b475b4a8c83fcf65cd93ce0a0f5
14,766
cpp
C++
core/resource.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
null
null
null
core/resource.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
null
null
null
core/resource.cpp
literaldumb/godot
a2903fc51d1d20eba4dc451bdacbe477d6670163
[ "CC-BY-3.0", "MIT" ]
1
2019-01-13T00:44:17.000Z
2019-01-13T00:44:17.000Z
/*************************************************************************/ /* resource.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "resource.h" #include "core_string_names.h" #include <stdio.h> #include "os/file_access.h" #include "io/resource_loader.h" #include "script_language.h" void ResourceImportMetadata::set_editor(const String& p_editor) { editor=p_editor; } String ResourceImportMetadata::get_editor() const{ return editor; } void ResourceImportMetadata::add_source(const String& p_path,const String& p_md5) { Source s; s.md5=p_md5; s.path=p_path; sources.push_back(s); } String ResourceImportMetadata::get_source_path(int p_idx) const{ ERR_FAIL_INDEX_V(p_idx,sources.size(),String()); return sources[p_idx].path; } String ResourceImportMetadata::get_source_md5(int p_idx) const{ ERR_FAIL_INDEX_V(p_idx,sources.size(),String()); return sources[p_idx].md5; } void ResourceImportMetadata::set_source_md5(int p_idx,const String& p_md5) { ERR_FAIL_INDEX(p_idx,sources.size()); sources[p_idx].md5=p_md5; } void ResourceImportMetadata::remove_source(int p_idx){ ERR_FAIL_INDEX(p_idx,sources.size()); sources.remove(p_idx); } int ResourceImportMetadata::get_source_count() const { return sources.size(); } void ResourceImportMetadata::set_option(const String& p_key, const Variant& p_value) { if (p_value.get_type()==Variant::NIL) { options.erase(p_key); return; } ERR_FAIL_COND(p_value.get_type() == Variant::OBJECT); ERR_FAIL_COND(p_value.get_type() == Variant::_RID); options[p_key]=p_value; } bool ResourceImportMetadata::has_option(const String& p_key) const { return options.has(p_key); } Variant ResourceImportMetadata::get_option(const String& p_key) const { ERR_FAIL_COND_V(!options.has(p_key),Variant()); return options[p_key]; } void ResourceImportMetadata::get_options(List<String> *r_options) const { for(Map<String,Variant>::Element *E=options.front();E;E=E->next()) { r_options->push_back(E->key()); } } PoolStringArray ResourceImportMetadata::_get_options() const { PoolStringArray option_names; option_names.resize(options.size()); int i=0; for(Map<String,Variant>::Element *E=options.front();E;E=E->next()) { option_names.set(i++,E->key()); } return option_names; } void ResourceImportMetadata::_bind_methods() { ClassDB::bind_method(_MD("set_editor","name"),&ResourceImportMetadata::set_editor); ClassDB::bind_method(_MD("get_editor"),&ResourceImportMetadata::get_editor); ClassDB::bind_method(_MD("add_source","path","md5"),&ResourceImportMetadata::add_source, ""); ClassDB::bind_method(_MD("get_source_path","idx"),&ResourceImportMetadata::get_source_path); ClassDB::bind_method(_MD("get_source_md5","idx"),&ResourceImportMetadata::get_source_md5); ClassDB::bind_method(_MD("set_source_md5","idx", "md5"),&ResourceImportMetadata::set_source_md5); ClassDB::bind_method(_MD("remove_source","idx"),&ResourceImportMetadata::remove_source); ClassDB::bind_method(_MD("get_source_count"),&ResourceImportMetadata::get_source_count); ClassDB::bind_method(_MD("set_option","key","value"),&ResourceImportMetadata::set_option); ClassDB::bind_method(_MD("get_option","key"),&ResourceImportMetadata::get_option); ClassDB::bind_method(_MD("get_options"),&ResourceImportMetadata::_get_options); } ResourceImportMetadata::ResourceImportMetadata() { } void Resource::emit_changed() { emit_signal(CoreStringNames::get_singleton()->changed); } void Resource::_resource_path_changed() { } void Resource::set_path(const String& p_path, bool p_take_over) { if (path_cache==p_path) return; if (path_cache!="") { ResourceCache::lock->write_lock(); ResourceCache::resources.erase(path_cache); ResourceCache::lock->write_unlock(); } path_cache=""; ResourceCache::lock->read_lock(); bool has_path = ResourceCache::resources.has( p_path ); ResourceCache::lock->read_unlock(); if (has_path) { if (p_take_over) { ResourceCache::lock->write_lock(); ResourceCache::resources.get(p_path)->set_name(""); ResourceCache::lock->write_unlock(); } else { ERR_EXPLAIN("Another resource is loaded from path: "+p_path); ResourceCache::lock->read_lock(); bool exists = ResourceCache::resources.has( p_path ); ResourceCache::lock->read_unlock(); ERR_FAIL_COND( exists ); } } path_cache=p_path; if (path_cache!="") { ResourceCache::lock->write_lock(); ResourceCache::resources[path_cache]=this;; ResourceCache::lock->write_unlock(); } _change_notify("resource_path"); _resource_path_changed(); } String Resource::get_path() const { return path_cache; } void Resource::set_subindex(int p_sub_index) { subindex=p_sub_index; } int Resource::get_subindex() const{ return subindex; } void Resource::set_name(const String& p_name) { name=p_name; _change_notify("resource_name"); } String Resource::get_name() const { return name; } bool Resource::editor_can_reload_from_file() { return true; //by default yes } void Resource::reload_from_file() { String path=get_path(); if (!path.is_resource_file()) return; Ref<Resource> s = ResourceLoader::load(path,get_class(),true); if (!s.is_valid()) return; List<PropertyInfo> pi; s->get_property_list(&pi); for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) { if (!(E->get().usage&PROPERTY_USAGE_STORAGE)) continue; if (E->get().name=="resource_path") continue; //do not change path set(E->get().name,s->get(E->get().name)); } } Ref<Resource> Resource::duplicate_for_local_scene(Node *p_for_scene, Map<Ref<Resource>, Ref<Resource> > &remap_cache) { List<PropertyInfo> plist; get_property_list(&plist); Resource *r = (Resource*)ClassDB::instance(get_class()); ERR_FAIL_COND_V(!r,Ref<Resource>()); r->local_scene=p_for_scene; for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { if (!(E->get().usage&PROPERTY_USAGE_STORAGE)) continue; Variant p = get(E->get().name); if (p.get_type()==Variant::OBJECT) { RES sr = p; if (sr.is_valid()) { if (sr->is_local_to_scene()) { if (remap_cache.has(sr)) { p=remap_cache[sr]; } else { RES dupe = sr->duplicate_for_local_scene(p_for_scene,remap_cache); p=dupe; remap_cache[sr]=dupe; } } } } r->set(E->get().name,p); } return Ref<Resource>(r); } Ref<Resource> Resource::duplicate(bool p_subresources) { List<PropertyInfo> plist; get_property_list(&plist); Resource *r = (Resource*)ClassDB::instance(get_class()); ERR_FAIL_COND_V(!r,Ref<Resource>()); for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { if (!(E->get().usage&PROPERTY_USAGE_STORAGE)) continue; Variant p = get(E->get().name); if (p.get_type()==Variant::OBJECT && p_subresources) { RES sr = p; if (sr.is_valid()) p=sr->duplicate(true); } r->set(E->get().name,p); } return Ref<Resource>(r); } void Resource::_set_path(const String& p_path) { set_path(p_path,false); } void Resource::_take_over_path(const String& p_path) { set_path(p_path,true); } RID Resource::get_rid() const { return RID(); } void Resource::register_owner(Object *p_owner) { owners.insert(p_owner->get_instance_ID()); } void Resource::unregister_owner(Object *p_owner) { owners.erase(p_owner->get_instance_ID()); } void Resource::notify_change_to_owners() { for(Set<ObjectID>::Element *E=owners.front();E;E=E->next()) { Object *obj = ObjectDB::get_instance(E->get()); ERR_EXPLAIN("Object was deleted, while still owning a resource"); ERR_CONTINUE(!obj); //wtf //TODO store string obj->call("resource_changed",RES(this)); } } void Resource::set_import_metadata(const Ref<ResourceImportMetadata>& p_metadata) { #ifdef TOOLS_ENABLED import_metadata=p_metadata; #endif } Ref<ResourceImportMetadata> Resource::get_import_metadata() const { #ifdef TOOLS_ENABLED return import_metadata; #else return Ref<ResourceImportMetadata>(); #endif } #ifdef TOOLS_ENABLED uint32_t Resource::hash_edited_version() const { uint32_t hash = hash_djb2_one_32(get_edited_version()); List<PropertyInfo> plist; get_property_list(&plist); for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { if (E->get().type==Variant::OBJECT && E->get().hint==PROPERTY_HINT_RESOURCE_TYPE) { RES res = get(E->get().name); if (res.is_valid()) { hash = hash_djb2_one_32(res->hash_edited_version(),hash); } } } return hash; } #endif void Resource::set_local_to_scene(bool p_enable) { local_to_scene=p_enable; } bool Resource::is_local_to_scene() const { return local_to_scene; } Node* Resource::get_local_scene() const { if (local_scene) return local_scene; if (_get_local_scene_func) { return _get_local_scene_func(); } return NULL; } void Resource::setup_local_to_scene() { if (get_script_instance()) get_script_instance()->call("_setup_local_to_scene"); } Node* (*Resource::_get_local_scene_func)()=NULL; void Resource::_bind_methods() { ClassDB::bind_method(_MD("set_path","path"),&Resource::_set_path); ClassDB::bind_method(_MD("take_over_path","path"),&Resource::_take_over_path); ClassDB::bind_method(_MD("get_path"),&Resource::get_path); ClassDB::bind_method(_MD("set_name","name"),&Resource::set_name); ClassDB::bind_method(_MD("get_name"),&Resource::get_name); ClassDB::bind_method(_MD("get_rid"),&Resource::get_rid); ClassDB::bind_method(_MD("set_import_metadata","metadata"),&Resource::set_import_metadata); ClassDB::bind_method(_MD("get_import_metadata"),&Resource::get_import_metadata); ClassDB::bind_method(_MD("set_local_to_scene","enable"),&Resource::set_local_to_scene); ClassDB::bind_method(_MD("is_local_to_scene"),&Resource::is_local_to_scene); ClassDB::bind_method(_MD("get_local_scene:Node"),&Resource::get_local_scene); ClassDB::bind_method(_MD("setup_local_to_scene"),&Resource::setup_local_to_scene); ClassDB::bind_method(_MD("duplicate","subresources"),&Resource::duplicate,DEFVAL(false)); ADD_SIGNAL( MethodInfo("changed") ); ADD_GROUP("Resource","resource_"); ADD_PROPERTYNZ( PropertyInfo(Variant::BOOL,"resource_local_to_scene" ), _SCS("set_local_to_scene"),_SCS("is_local_to_scene")); ADD_PROPERTY( PropertyInfo(Variant::STRING,"resource_path",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR ), _SCS("set_path"),_SCS("get_path")); ADD_PROPERTYNZ( PropertyInfo(Variant::STRING,"resource_name"), _SCS("set_name"),_SCS("get_name")); BIND_VMETHOD( MethodInfo("_setup_local_to_scene") ); } Resource::Resource() { #ifdef TOOLS_ENABLED last_modified_time=0; #endif subindex=0; local_scene=NULL; } Resource::~Resource() { if (path_cache!="") { ResourceCache::lock->write_lock(); ResourceCache::resources.erase(path_cache); ResourceCache::lock->write_unlock(); } if (owners.size()) { WARN_PRINT("Resource is still owned"); } } HashMap<String,Resource*> ResourceCache::resources; RWLock *ResourceCache::lock=NULL; void ResourceCache::setup() { lock = RWLock::create(); } void ResourceCache::clear() { if (resources.size()) ERR_PRINT("Resources Still in use at Exit!"); resources.clear(); memdelete(lock); } void ResourceCache::reload_externals() { //const String *K=NULL; //while ((K=resources.next(K))) { // resources[*K]->reload_external_data(); // } } bool ResourceCache::has(const String& p_path) { lock->read_lock();; bool b = resources.has(p_path); lock->read_unlock();; return b; } Resource *ResourceCache::get(const String& p_path) { lock->read_lock(); Resource **res = resources.getptr(p_path); lock->read_unlock(); if (!res) { return NULL; } return *res; } void ResourceCache::get_cached_resources(List<Ref<Resource> > *p_resources) { lock->read_lock(); const String* K=NULL; while((K=resources.next(K))) { Resource *r = resources[*K]; p_resources->push_back( Ref<Resource>( r )); } lock->read_unlock(); } int ResourceCache::get_cached_resource_count() { lock->read_lock(); int rc = resources.size(); lock->read_unlock(); return rc; } void ResourceCache::dump(const char* p_file,bool p_short) { #ifdef DEBUG_ENABLED lock->read_lock(); Map<String,int> type_count; FileAccess *f=NULL; if (p_file) { f = FileAccess::open(p_file,FileAccess::WRITE); ERR_FAIL_COND(!f); } const String* K=NULL; while((K=resources.next(K))) { Resource *r = resources[*K]; if (!type_count.has(r->get_class())) { type_count[r->get_class()]=0; } type_count[r->get_class()]++; if (!p_short) { if (f) f->store_line(r->get_class()+": "+r->get_path()); } } for(Map<String,int>::Element *E=type_count.front();E;E=E->next()) { if (f) f->store_line(E->key()+" count: "+itos(E->get())); } if (f) { f->close(); memdelete(f); } lock->read_unlock(); #endif }
23.550239
142
0.673845
[ "object" ]
db4d7121a6936fe76cf4af3b4cb6cef7265bcbbc
100,493
cpp
C++
src/module.cpp
Jiboo/wembed
8d6ce78d8e499ffdbd736e4cfb688e1aba265adf
[ "MIT" ]
2
2019-04-22T05:50:37.000Z
2020-02-11T20:45:12.000Z
src/module.cpp
Jiboo/wembed
8d6ce78d8e499ffdbd736e4cfb688e1aba265adf
[ "MIT" ]
null
null
null
src/module.cpp
Jiboo/wembed
8d6ce78d8e499ffdbd736e4cfb688e1aba265adf
[ "MIT" ]
null
null
null
#include <sstream> #include <llvm-c/Analysis.h> #include <llvm-c/Transforms/AggressiveInstCombine.h> #include <llvm-c/Transforms/InstCombine.h> #include <llvm-c/Transforms/IPO.h> #include <llvm-c/Transforms/Scalar.h> #include <llvm-c/Transforms/Utils.h> #include <llvm-c/Transforms/Vectorize.h> #include <wembed/module.hpp> #include "wembed.hpp" #ifdef WEMBED_VERBOSE #include <iostream> #endif namespace wembed { module::module(uint8_t *pInput, size_t pLen) { profile_step(" module/ctr"); if (pInput == nullptr || pLen < 4) throw malformed_exception("invalid input"); mCurrent = pInput; mEnd = pInput + pLen; if (parse<uint32_t>() != 0x6d736100) throw malformed_exception("unexpected magic code"); LLVMTypeRef lVoidFuncT = LLVMFunctionType(LLVMVoidType(), nullptr, 0, false); mModule = LLVMModuleCreateWithName("module"); mBaseMemory = LLVMAddGlobal(mModule, LLVMInt8Type(), "wembed.baseMemory"); mContextRef = LLVMAddGlobal(mModule, LLVMInt8Type(), "wembed.ctxRef"); mBuilder = LLVMCreateBuilder(); mStartFunc = LLVMAddFunction(mModule, "wembed.start", lVoidFuncT); mStartInit = LLVMAppendBasicBlock(mStartFunc, "entry"); mStartUser = LLVMAppendBasicBlock(mStartFunc, "callStart"); LLVMPositionBuilderAtEnd(mBuilder, mStartInit); init_intrinsics(); profile_step(" module/init"); switch(parse<uint32_t>()) { // version case 1: parse_sections(); break; default: throw malformed_exception("unexpected version"); } profile_step(" module/parsed"); #ifdef WEMBED_VERBOSE std::cout << "Finalizing module..." << std::endl; #endif for(auto &lNamespace : mImports) for(auto &lImports : lNamespace.second) lImports.second.retreiveNames(); for(auto &lExports : mExports) lExports.second.retreiveNames(); for (auto &lFunc : mFunctions) lFunc.retreiveName(); profile_step(" module/rename"); // finish __wstart LLVMPositionBuilderAtEnd(mBuilder, mStartInit); LLVMBuildBr(mBuilder, mStartUser); LLVMPositionBuilderAtEnd(mBuilder, mStartUser); LLVMBuildRetVoid(mBuilder); LLVMDisposeBuilder(mBuilder); char *lError = nullptr; if (LLVMVerifyModule(mModule, LLVMReturnStatusAction, &lError)) { std::stringstream lMessage; lMessage << "module failed verification: " << lError << "\n\n"; dump_ll(lMessage); LLVMDisposeMessage(lError); throw invalid_exception(lMessage.str()); } LLVMDisposeMessage(lError); profile_step(" module/verified"); } module::~module() { //LLVMDisposeModule(mModule); } void module::dump_ll(std::ostream &os) { char *lCode = LLVMPrintModuleToString(mModule); os << lCode; LLVMDisposeMessage(lCode); } LLVMValueRef module::symbol1(const std::string_view &pName) { auto lFound = mExports.find(std::string(pName)); if (lFound == mExports.end()) throw std::runtime_error("can't find symbol: "s + pName.data()); if (lFound->second.mValues.size() > 1) throw std::runtime_error("more than one value in: "s + pName.data()); return mExports[std::string(pName)].mValues[0]; } void module::pushCFEntry(CFInstr pInstr, LLVMTypeRef pType, LLVMBasicBlockRef pEnd, LLVMValueRef pPhi, LLVMBasicBlockRef pElse) { if (mCFEntries.size()) assert(mCFEntries.back().mReachable); mCFEntries.emplace_back(pInstr, pType, pEnd, pPhi, pElse, mEvalStack.size(), mBlockEntries.size(), true, true); } void module::pushBlockEntry(LLVMTypeRef pType, LLVMBasicBlockRef pBlock, LLVMValueRef pPhi) { mBlockEntries.emplace_back(pType, pBlock, pPhi); } const module::BlockEntry &module::branch_depth(size_t pDepth) { if (pDepth >= mBlockEntries.size()) throw invalid_exception("invalid branch target"); return mBlockEntries[mBlockEntries.size() - pDepth - 1]; } LLVMValueRef module::top() { if (mEvalStack.empty()) throw invalid_exception("topping empty stack"); else if (!mCFEntries.empty() && mEvalStack.size() <= mCFEntries.back().mOuterStackSize) throw invalid_exception("topping stack outside bounds of current context"); return mEvalStack.back(); } LLVMValueRef module::top(LLVMTypeRef pDesired) { LLVMValueRef lVal = top(); if(LLVMTypeOf(lVal) != pDesired) throw invalid_exception("topping wrong type"); return lVal; } void module::push(LLVMValueRef lVal) { assert(lVal); mEvalStack.emplace_back(lVal); } LLVMValueRef module::pop() { if (mEvalStack.empty()) throw invalid_exception("popping empty stack"); else if (!mCFEntries.empty() && mEvalStack.size() <= mCFEntries.back().mOuterStackSize) throw invalid_exception("popping stack outside bounds of current context"); auto lVal = mEvalStack.back(); mEvalStack.pop_back(); return lVal; } LLVMValueRef module::pop(LLVMTypeRef pDesired) { LLVMValueRef lVal = pop(); if(LLVMTypeOf(lVal) != pDesired) { #ifdef WEMBED_VERBOSE char *lExpected = LLVMPrintTypeToString(pDesired); char *lFound = LLVMPrintTypeToString(LLVMTypeOf(lVal)); std::stringstream lError; lError << "popping wrong type, expected " << lExpected << ", got " << lFound; LLVMDisposeMessage(lExpected); LLVMDisposeMessage(lFound); throw invalid_exception(lError.str()); #else throw invalid_exception("popping wrong type"); #endif } return lVal; } LLVMValueRef module::pop_int() { LLVMValueRef lVal = pop(); LLVMTypeRef lType = LLVMTypeOf(lVal); if(lType != LLVMInt32Type() && lType != LLVMInt64Type()) { throw invalid_exception("popping wrong type"); } return lVal; } LLVMValueRef module::init_intrinsic(const std::string &pName, LLVMTypeRef pReturnType, const std::initializer_list<LLVMTypeRef> &pArgTypes) { LLVMTypeRef *lArgTypes = const_cast<LLVMTypeRef*>(pArgTypes.begin()); LLVMTypeRef lType = LLVMFunctionType(pReturnType, lArgTypes, pArgTypes.size(), false); return LLVMAddFunction(mModule, pName.c_str(), lType); } LLVMValueRef module::call_intrinsic(LLVMValueRef pIntrinsic, const std::initializer_list<LLVMValueRef> &pArgs) { LLVMValueRef *lArgs = const_cast<LLVMValueRef*>(pArgs.begin()); return LLVMBuildCall(mBuilder, pIntrinsic, lArgs, pArgs.size(), ""); } LLVMValueRef module::init_mv_intrinsic(const std::string &pName, const std::initializer_list<LLVMTypeRef> &pReturnTypes, const std::initializer_list<LLVMTypeRef> &pArgTypes) { LLVMTypeRef *lArgTypes = const_cast<LLVMTypeRef*>(pArgTypes.begin()); LLVMTypeRef *lReturnTypes = const_cast<LLVMTypeRef*>(pReturnTypes.begin()); LLVMTypeRef lReturnType = LLVMStructType(lReturnTypes, pReturnTypes.size(), false); LLVMTypeRef lType = LLVMFunctionType(lReturnType, lArgTypes, pArgTypes.size(), false); return LLVMAddFunction(mModule, pName.c_str(), lType); } LLVMBasicBlockRef module::trap_if(LLVMValueRef pFunc, LLVMValueRef pCondition, LLVMValueRef pIntrinsic, const std::initializer_list<LLVMValueRef> &pArgs) { LLVMBasicBlockRef lTrapThen = LLVMAppendBasicBlock(pFunc, "trapThen"); LLVMBasicBlockRef lTrapSkip = LLVMAppendBasicBlock(pFunc, "trapSkip"); LLVMBuildCondBr(mBuilder, pCondition, lTrapThen, lTrapSkip); auto lPrevBlock = LLVMGetInsertBlock(mBuilder); LLVMMoveBasicBlockAfter(lTrapSkip, lPrevBlock); LLVMMoveBasicBlockAfter(lTrapThen, lPrevBlock); LLVMPositionBuilderAtEnd(mBuilder, lTrapThen); call_intrinsic(pIntrinsic, pArgs); LLVMBuildUnreachable(mBuilder); LLVMPositionBuilderAtEnd(mBuilder, lTrapSkip); return lTrapSkip; } LLVMBasicBlockRef module::trap_data_copy(LLVMValueRef pFunc, LLVMValueRef pOffset, size_t pSize) { LLVMValueRef lMemorySizePage = LLVMBuildCall(mBuilder, mMemorySize, &mContextRef, 1, "curMemPage"); LLVMValueRef lMemorySizeBytes = LLVMBuildMul(mBuilder, lMemorySizePage, get_const(64 * 1024), "curMemByte"); LLVMValueRef lUnderflow = LLVMBuildICmp(mBuilder, LLVMIntSLT, pOffset, get_zero(LLVMTypeOf(pOffset)), "testOverflow"); LLVMValueRef lTotalOffset = LLVMBuildAdd(mBuilder, pOffset, get_const(i32(pSize)), "endByteOffset"); LLVMValueRef lOverflow = LLVMBuildICmp(mBuilder, LLVMIntUGT, lTotalOffset, lMemorySizeBytes, "testOverflow"); LLVMValueRef lBoundsError = LLVMBuildOr(mBuilder, lUnderflow, lOverflow, "boundsError"); static const char *lErrorString = "data segment does not fit"; return trap_if(pFunc, lBoundsError, mThrowUnlinkable, {get_string(lErrorString)}); } LLVMBasicBlockRef module::trap_elem_copy(LLVMValueRef lFunc, LLVMValueRef pOffset) { LLVMValueRef lTabSize = LLVMBuildCall(mBuilder, mTableSize, &mContextRef, 1, "curTabSize"); LLVMValueRef lOverflow = LLVMBuildICmp(mBuilder, LLVMIntUGE, pOffset, lTabSize, "testOverflow"); static const char *lErrorString = "elements segment does not fit trap_elem_copy"; return trap_if(lFunc, lOverflow, mThrowUnlinkable, {get_string(lErrorString)}); } LLVMBasicBlockRef module::trap_zero_div(LLVMValueRef lFunc, LLVMValueRef pLHS, LLVMValueRef pRHS) { LLVMValueRef lDivZero = LLVMBuildICmp(mBuilder, LLVMIntEQ, pRHS, get_zero(LLVMTypeOf(pRHS)), "divZero"); static const char *lErrorString = "int div by zero"; return trap_if(lFunc, lDivZero, mThrowVMException, {get_string(lErrorString)}); } LLVMBasicBlockRef module::trap_szero_div(LLVMValueRef lFunc, LLVMValueRef pLHS, LLVMValueRef pRHS) { LLVMValueRef lMin, lMinus1; LLVMTypeRef lLType = LLVMTypeOf(pLHS); if (lLType == LLVMInt32Type()) { lMin = get_const(std::numeric_limits<int32_t>::min()); lMinus1 = get_const(int32_t(-1)); } else if (lLType == LLVMInt64Type()) { lMin = get_const(std::numeric_limits<int64_t>::min()); lMinus1 = get_const(int64_t(-1)); } else { throw std::runtime_error("unexpected type in trap_szero_div"); } LLVMValueRef lLHSIsMin = LLVMBuildICmp(mBuilder, LLVMIntEQ, pLHS, lMin, "lhsMin"); LLVMValueRef lRHSIsMinus1 = LLVMBuildICmp(mBuilder, LLVMIntEQ, pRHS, lMinus1, "rhsMinus1"); LLVMValueRef lOverflow = LLVMBuildAnd(mBuilder, lLHSIsMin, lRHSIsMinus1, "overflow"); LLVMValueRef lDivZero = LLVMBuildICmp(mBuilder, LLVMIntEQ, pRHS, get_zero(LLVMTypeOf(pRHS)), "divZero"); LLVMValueRef lSZeroDiv = LLVMBuildOr(mBuilder, lDivZero, lOverflow, "szero_div"); static const char *lErrorString = "int div by zero or overflow"; return trap_if(lFunc, lSZeroDiv, mThrowVMException, {get_string(lErrorString)}); } void module::init_intrinsics() { mMemCpy = init_intrinsic("llvm.memcpy.p0i8.p0i8.i32", LLVMVoidType(), { LLVMPointerType(LLVMInt8Type(), 0), // dest LLVMPointerType(LLVMInt8Type(), 0), // src LLVMInt32Type(), // len LLVMInt1Type() // volatile }); mCtlz_i32 = init_intrinsic("llvm.ctlz.i32", LLVMInt32Type(), { LLVMInt32Type(), // src LLVMInt1Type() // is_zero_undef }); mCtlz_i64 = init_intrinsic("llvm.ctlz.i64", LLVMInt64Type(), { LLVMInt64Type(), // src LLVMInt1Type() // is_zero_undef }); mCttz_i32 = init_intrinsic("llvm.cttz.i32", LLVMInt32Type(), { LLVMInt32Type(), // src LLVMInt1Type() // is_zero_undef }); mCttz_i64 = init_intrinsic("llvm.cttz.i64", LLVMInt64Type(), { LLVMInt64Type(), // src LLVMInt1Type() // is_zero_undef }); mCtpop_i32 = init_intrinsic("llvm.ctpop.i32", LLVMInt32Type(), {LLVMInt32Type()}); mCtpop_i64 = init_intrinsic("llvm.ctpop.i64", LLVMInt64Type(), {LLVMInt64Type()}); mSqrt_f32 = init_intrinsic("llvm.sqrt.f32", LLVMFloatType(), {LLVMFloatType()}); mSqrt_f64 = init_intrinsic("llvm.sqrt.f64", LLVMDoubleType(), {LLVMDoubleType()}); mAbs_f32 = init_intrinsic("llvm.fabs.f32", LLVMFloatType(), {LLVMFloatType()}); mAbs_f64 = init_intrinsic("llvm.fabs.f64", LLVMDoubleType(), {LLVMDoubleType()}); mCopysign_f32 = init_intrinsic("llvm.copysign.f32", LLVMFloatType(), {LLVMFloatType(), LLVMFloatType()}); mCopysign_f64 = init_intrinsic("llvm.copysign.f64", LLVMDoubleType(), {LLVMDoubleType(), LLVMDoubleType()}); mCeil_f32 = init_intrinsic("llvm.ceil.f32", LLVMFloatType(), {LLVMFloatType()}); mCeil_f64 = init_intrinsic("llvm.ceil.f64", LLVMDoubleType(), {LLVMDoubleType()}); mFloor_f32 = init_intrinsic("llvm.floor.f32", LLVMFloatType(), {LLVMFloatType()}); mFloor_f64 = init_intrinsic("llvm.floor.f64", LLVMDoubleType(), {LLVMDoubleType()}); mTrunc_f32 = init_intrinsic("llvm.trunc.f32", LLVMFloatType(), {LLVMFloatType()}); mTrunc_f64 = init_intrinsic("llvm.trunc.f64", LLVMDoubleType(), {LLVMDoubleType()}); mNearest_f32 = init_intrinsic("llvm.nearbyint.f32", LLVMFloatType(), {LLVMFloatType()}); mNearest_f64 = init_intrinsic("llvm.nearbyint.f64", LLVMDoubleType(), {LLVMDoubleType()}); mMin_f32 = init_intrinsic("llvm.minnum.f32", LLVMFloatType(), {LLVMFloatType(), LLVMFloatType()}); mMin_f64 = init_intrinsic("llvm.minnum.f64", LLVMDoubleType(), {LLVMDoubleType(), LLVMDoubleType()}); mMax_f32 = init_intrinsic("llvm.maxnum.f32", LLVMFloatType(), {LLVMFloatType(), LLVMFloatType()}); mMax_f64 = init_intrinsic("llvm.maxnum.f64", LLVMDoubleType(), {LLVMDoubleType(), LLVMDoubleType()}); mUAddWithOverflow_i32 = init_mv_intrinsic("llvm.uadd.with.overflow.i32", {LLVMInt32Type(), LLVMInt1Type()}, {LLVMInt32Type(), LLVMInt32Type()}); mUAddWithOverflow_i64 = init_mv_intrinsic("llvm.uadd.with.overflow.i64", {LLVMInt64Type(), LLVMInt1Type()}, {LLVMInt64Type(), LLVMInt64Type()}); mMemoryGrow = init_intrinsic("wembed.memory.grow", LLVMInt32Type(), { LLVMPointerType(LLVMInt8Type(), 0), LLVMInt32Type() }); mMemorySize = init_intrinsic("wembed.memory.size", LLVMInt32Type(), { LLVMPointerType(LLVMInt8Type(), 0) }); mTableSize = init_intrinsic("wembed.table.size", LLVMInt32Type(), { LLVMPointerType(LLVMInt8Type(), 0) }); mThrowUnlinkable = init_intrinsic("wembed.throw.unlinkable", LLVMVoidType(), {LLVMPointerType(LLVMInt8Type(), 0)}); mThrowVMException = init_intrinsic("wembed.throw.vm_exception", LLVMVoidType(), {LLVMPointerType(LLVMInt8Type(), 0)}); } LLVMValueRef module::i32_to_bool(LLVMValueRef i32) { LLVMValueRef lZero32 = LLVMConstInt(LLVMInt32Type(), 0, true); return LLVMBuildICmp(mBuilder, LLVMIntNE, i32, lZero32, "boolAsI32"); } LLVMValueRef module::bool_to_i32(LLVMValueRef b) { return LLVMBuildZExt(mBuilder, b, LLVMInt32Type(), "i32AsBool"); } LLVMValueRef module::create_phi(LLVMTypeRef pType, LLVMBasicBlockRef pBlock) { if (pType == LLVMVoidType()) return nullptr; auto lBefore = LLVMGetInsertBlock(mBuilder); LLVMPositionBuilderAtEnd(mBuilder, pBlock); auto lInstr = LLVMBuildPhi(mBuilder, pType, "phi"); if(lBefore) LLVMPositionBuilderAtEnd(mBuilder, lBefore); return lInstr; } std::string_view module::parse_str(size_t pSize) { auto lResult = std::string_view((char*)mCurrent, pSize); mCurrent += pSize; return lResult; } elem_type module::parse_elem_type() { return (elem_type)parse<int8_t>(); } resizable_limits module::parse_resizable_limits() { resizable_limits lResult; lResult.mFlags = parse<uint8_t>(); lResult.mInitial = parse_uleb128<uint32_t>(); if (lResult.mFlags & 0x1) { lResult.mMaximum = parse_uleb128<uint32_t>(); if (lResult.mMaximum < lResult.mInitial) throw invalid_exception("maximum shouldn't be smaller than initial"); } return lResult; } table_type module::parse_table_type() { table_type lResult; lResult.mType = parse_elem_type(); lResult.mLimits = parse_resizable_limits(); return lResult; } external_kind module::parse_external_kind() { return (external_kind)parse<uint8_t>(); } void module::parse_sections() { while(mCurrent < mEnd) { uint8_t lId = parse<uint8_t>(); uint32_t lPayloadSize = parse_uleb128<uint32_t>(); switch(lId) { case 0: { uint8_t *lBefore = mCurrent; uint32_t lNameSize = parse_uleb128<uint32_t>(); size_t lNameSizeBytes = mCurrent - lBefore; std::string_view lName = parse_str(lNameSize); size_t lInternalSize = lPayloadSize - lNameSizeBytes - lName.size(); parse_custom_section(lName, lInternalSize); } break; case 1: parse_types(); break; case 2: parse_imports(); break; case 3: parse_functions(); break; case 4: parse_section_table(lPayloadSize); break; case 5: parse_section_memory(lPayloadSize); break; case 6: parse_globals(); break; case 7: parse_exports(); break; case 8: parse_section_start(lPayloadSize); break; case 9: parse_section_element(lPayloadSize); break; case 10: parse_section_code(lPayloadSize); break; case 11: parse_section_data(lPayloadSize); break; default: throw malformed_exception("unknown section ID"); } } } void module::parse_custom_section(const std::string_view &pName, size_t pInternalSize) { if (pName == "name") { // "name" http://webassembly.org/docs/binary-encoding/#name-section parse_names(pInternalSize); mCurrent += pInternalSize; } else if (pName == "dylink") { // TODO https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md mCurrent += pInternalSize; } else { #ifdef WEMBED_VERBOSE std::cout << "Ignoring custom section " << pName << " of size " << pInternalSize << std::endl; #endif mCurrent += pInternalSize; } } void module::parse_names(size_t pInternalSize) { // TODO uint8_t *lEnd = mCurrent + pInternalSize; while (mCurrent < lEnd) { uint8_t lType = parse<uint8_t>(); uint32_t lSectionSize = parse_uleb128<uint32_t>(); switch (lType) { default: mCurrent += lSectionSize; break; case 1: { uint32_t lCount = parse_uleb128<uint32_t>(); for (uint32_t lName = 0; lName < lCount; lName++) { uint32_t lIndex = parse_uleb128<uint32_t>(); uint32_t lNameSize = parse_uleb128<uint32_t>(); auto lNameStr(parse_str(lNameSize)); if (lIndex >= mFunctions.size()) throw invalid_exception("function index out of bounds"); std::stringstream lNewName; lNewName << "wasm.names.func." << lNameStr; std::string lNewNameStr = lNewName.str(); #ifdef WEMBED_VERBOSE std::cout << "Renaming " << mFunctions[lIndex].mValue << " aka " << LLVMGetValueName(mFunctions[lIndex].mValue) << " to " << lNewNameStr << std::endl; #endif LLVMSetValueName2(mFunctions[lIndex].mValue, lNewNameStr.data(), lNewNameStr.size()); } } break; } } } uint8_t module::bit_count(LLVMTypeRef pType) { if (pType == LLVMInt32Type()) return 32; else if (pType == LLVMInt64Type()) return 64; else if (pType == LLVMFloatType()) return 32; else if (pType == LLVMDoubleType()) return 64; else throw malformed_exception("unexpected value type"); } LLVMValueRef module::emit_shift_mask(LLVMTypeRef pType, LLVMValueRef pCount) { auto lTemp = get_const(bit_count(pType) - 1); auto lWidth = LLVMBuildZExt(mBuilder, lTemp, pType, "width"); return LLVMBuildAnd(mBuilder, pCount, lWidth, "mask"); } LLVMValueRef module::emit_rotl(LLVMTypeRef pType, LLVMValueRef pLHS, LLVMValueRef pRHS) { auto lWidth = LLVMBuildZExt(mBuilder, get_const(bit_count(pType)), pType, "width"); auto lBitWidthMinusRight = LLVMBuildSub(mBuilder, lWidth, pRHS, ""); return LLVMBuildOr(mBuilder, LLVMBuildShl(mBuilder, pLHS, emit_shift_mask(pType, pRHS), ""), LLVMBuildLShr(mBuilder, pLHS, emit_shift_mask(pType, lBitWidthMinusRight), ""), "rotl"); } LLVMValueRef module::emit_rotr(LLVMTypeRef pType, LLVMValueRef pLHS, LLVMValueRef pRHS) { auto lWidth = LLVMBuildZExt(mBuilder, get_const(bit_count(pType)), pType, "width"); auto lBitWidthMinusRight = LLVMBuildSub(mBuilder, lWidth, pRHS, ""); return LLVMBuildOr(mBuilder, LLVMBuildShl(mBuilder, pLHS, emit_shift_mask(pType, lBitWidthMinusRight), ""), LLVMBuildLShr(mBuilder, pLHS, emit_shift_mask(pType, pRHS), ""), "rotl"); } LLVMValueRef module::emit_udiv(LLVMTypeRef pType, LLVMValueRef lFunc, LLVMValueRef pLHS, LLVMValueRef pRHS) { trap_zero_div(lFunc, pLHS, pRHS); return LLVMBuildUDiv(mBuilder, pLHS, pRHS, "udiv"); } LLVMValueRef module::emit_sdiv(LLVMTypeRef pType, LLVMValueRef lFunc, LLVMValueRef pLHS, LLVMValueRef pRHS) { trap_szero_div(lFunc, pLHS, pRHS); return LLVMBuildSDiv(mBuilder, pLHS, pRHS, "sdiv"); } LLVMValueRef module::emit_urem(LLVMTypeRef pType, LLVMValueRef lFunc, LLVMValueRef pLHS, LLVMValueRef pRHS) { trap_zero_div(lFunc, pLHS, pRHS); return LLVMBuildURem(mBuilder, pLHS, pRHS, "urem"); } LLVMValueRef module::emit_srem(LLVMTypeRef pType, LLVMValueRef lFunc, LLVMValueRef pLHS, LLVMValueRef pRHS) { trap_zero_div(lFunc, pLHS, pRHS); LLVMBasicBlockRef lPreTest = LLVMGetInsertBlock(mBuilder); LLVMBasicBlockRef lSRemThen = LLVMAppendBasicBlock(lFunc, "sremElse"); LLVMBasicBlockRef lSRemEnd = LLVMAppendBasicBlock(lFunc, "sremEnd"); LLVMValueRef lLeftTest = LLVMBuildICmp(mBuilder, LLVMIntNE, pLHS, pType == LLVMInt32Type() ? get_const(int32_t(INT32_MIN)) : get_const(int64_t(INT64_MIN)), "left"); LLVMValueRef lRightTest = LLVMBuildICmp(mBuilder, LLVMIntNE, pRHS, pType == LLVMInt32Type() ? get_const(int32_t(-1)) : get_const(int64_t(-1)), "right"); LLVMValueRef lNoOverflow = LLVMBuildOr(mBuilder, lLeftTest, lRightTest, "noOverflow"); LLVMBuildCondBr(mBuilder, lNoOverflow, lSRemThen, lSRemEnd); LLVMPositionBuilderAtEnd(mBuilder, lSRemThen); LLVMValueRef lSRem = LLVMBuildSRem(mBuilder, pLHS, pRHS, "rem"); LLVMBuildBr(mBuilder, lSRemEnd); LLVMPositionBuilderAtEnd(mBuilder, lSRemEnd); LLVMValueRef lPhi = LLVMBuildPhi(mBuilder, pType, "sremRes"); LLVMValueRef lValues[] = { lSRem, get_zero(pType) }; LLVMBasicBlockRef lFroms[] = { lSRemThen, lPreTest }; LLVMAddIncoming(lPhi, lValues, lFroms, 2); return lPhi; } LLVMValueRef module::emit_quiet_nan(LLVMValueRef pInput) { LLVMTypeRef lInputType = LLVMTypeOf(pInput); if (lInputType == LLVMFloatType()) { LLVMValueRef lBitcast = LLVMBuildBitCast(mBuilder, pInput, LLVMInt32Type(), "bitcast"); LLVMValueRef lMantissaMask = get_const(~(fp_bits<float>::sMantissaMask)); LLVMValueRef lMasked = LLVMBuildAnd(mBuilder, lBitcast, lMantissaMask, "masked"); LLVMValueRef lQuietNan = get_const(fp_bits<float>::sQuietNan); LLVMValueRef lCorrected = LLVMBuildOr(mBuilder, lMasked, lQuietNan, "quietNaN"); return LLVMBuildBitCast(mBuilder, lCorrected, LLVMFloatType(), "castedBack"); } else if (lInputType == LLVMDoubleType()) { LLVMValueRef lBitcast = LLVMBuildBitCast(mBuilder, pInput, LLVMInt64Type(), "bitcast"); LLVMValueRef lMantissaMask = get_const(~(fp_bits<double>::sMantissaMask)); LLVMValueRef lMasked = LLVMBuildAnd(mBuilder, lBitcast, lMantissaMask, "masked"); LLVMValueRef lQuietNan = get_const(fp_bits<double>::sQuietNan); LLVMValueRef lCorrected = LLVMBuildOr(mBuilder, lMasked, lQuietNan, "quietNaN"); return LLVMBuildBitCast(mBuilder, lCorrected, LLVMDoubleType(), "castedBack"); } throw std::runtime_error("unexpcted type passed to emit_quiet_nan"); } LLVMValueRef module::emit_quiet_nan_or_intrinsic(LLVMValueRef pInput, LLVMValueRef pF32Intr, LLVMValueRef pF64Intr) { LLVMValueRef lNotNan = LLVMBuildFCmp(mBuilder, LLVMRealORD, pInput, pInput, "notNaN"); LLVMTypeRef lInputType = LLVMTypeOf(pInput); assert(lInputType == LLVMFloatType() || lInputType == LLVMDoubleType()); LLVMValueRef lIntrinsic = lInputType == LLVMFloatType() ? pF32Intr : pF64Intr; return LLVMBuildSelect(mBuilder, lNotNan, call_intrinsic(lIntrinsic, {pInput}), emit_quiet_nan(pInput), "quiet_nan_or_ceil"); } LLVMValueRef module::emit_min(LLVMValueRef pLHS, LLVMValueRef pRHS) { LLVMTypeRef lBitcastType; if (LLVMTypeOf(pLHS) == LLVMFloatType() && LLVMTypeOf(pRHS) == LLVMFloatType()) lBitcastType = LLVMInt32Type(); else if (LLVMTypeOf(pLHS) == LLVMDoubleType() && LLVMTypeOf(pRHS) == LLVMDoubleType()) lBitcastType = LLVMInt64Type(); else throw std::runtime_error("unexpected types for emit_min"); LLVMValueRef lBitcastLHS = LLVMBuildBitCast(mBuilder, pLHS, lBitcastType, "bitcastL"); LLVMValueRef lBitcastRHS = LLVMBuildBitCast(mBuilder, pRHS, lBitcastType, "bitcastR"); LLVMValueRef lBitcastCmp = LLVMBuildICmp(mBuilder, LLVMIntUGT, lBitcastLHS, lBitcastRHS, "bitcastCmp"); LLVMValueRef lRCmp = LLVMBuildFCmp(mBuilder, LLVMRealOGT, pLHS, pRHS, "RCmp"); LLVMValueRef lLCmp = LLVMBuildFCmp(mBuilder, LLVMRealOLT, pLHS, pRHS, "LCmp"); LLVMValueRef lLNan = LLVMBuildFCmp(mBuilder, LLVMRealUNO, pLHS, pLHS, "LNaN"); LLVMValueRef lRNan = LLVMBuildFCmp(mBuilder, LLVMRealUNO, pRHS, pRHS, "RNaN"); return LLVMBuildSelect(mBuilder, lRNan, emit_quiet_nan(pRHS), LLVMBuildSelect(mBuilder, lLNan, emit_quiet_nan(pLHS), LLVMBuildSelect(mBuilder, lLCmp, pLHS, LLVMBuildSelect(mBuilder, lRCmp, pRHS, LLVMBuildSelect(mBuilder, lBitcastCmp, pLHS, pRHS, "stepBitcast"), "stepRCmp"), "stepLCmp"), "cleanLHS"), "cleanRHS"); } LLVMValueRef module::emit_max(LLVMValueRef pLHS, LLVMValueRef pRHS) { LLVMTypeRef lBitcastType; if (LLVMTypeOf(pLHS) == LLVMFloatType() && LLVMTypeOf(pRHS) == LLVMFloatType()) lBitcastType = LLVMInt32Type(); else if (LLVMTypeOf(pLHS) == LLVMDoubleType() && LLVMTypeOf(pRHS) == LLVMDoubleType()) lBitcastType = LLVMInt64Type(); else throw std::runtime_error("unexpected types for emit_max"); LLVMValueRef lBitcastLHS = LLVMBuildBitCast(mBuilder, pLHS, lBitcastType, "bitcastL"); LLVMValueRef lBitcastRHS = LLVMBuildBitCast(mBuilder, pRHS, lBitcastType, "bitcastR"); LLVMValueRef lBitcastCmp = LLVMBuildICmp(mBuilder, LLVMIntULT, lBitcastLHS, lBitcastRHS, "bitcastCmp"); LLVMValueRef lRCmp = LLVMBuildFCmp(mBuilder, LLVMRealOLT, pLHS, pRHS, "RCmp"); LLVMValueRef lLCmp = LLVMBuildFCmp(mBuilder, LLVMRealOGT, pLHS, pRHS, "LCmp"); LLVMValueRef lLNan = LLVMBuildFCmp(mBuilder, LLVMRealUNO, pLHS, pLHS, "LNaN"); LLVMValueRef lRNan = LLVMBuildFCmp(mBuilder, LLVMRealUNO, pRHS, pRHS, "RNaN"); return LLVMBuildSelect(mBuilder, lRNan, emit_quiet_nan(pRHS), LLVMBuildSelect(mBuilder, lLNan, emit_quiet_nan(pLHS), LLVMBuildSelect(mBuilder, lLCmp, pLHS, LLVMBuildSelect(mBuilder, lRCmp, pRHS, LLVMBuildSelect(mBuilder, lBitcastCmp, pLHS, pRHS, "stepBitcast"), "stepRCmp"), "stepLCmp"), "cleanLHS"), "cleanRHS"); } LLVMTypeRef module::parse_llvm_btype() { int8_t lType = parse<int8_t>(); switch (lType) { case bt_i32: return LLVMInt32Type(); case bt_i64: return LLVMInt64Type(); case bt_f32: return LLVMFloatType(); case bt_f64: return LLVMDoubleType(); case bt_void: return LLVMVoidType(); default: throw malformed_exception("unexpected value type"); } } LLVMTypeRef module::parse_llvm_vtype() { int8_t lType = parse<int8_t>(); switch (lType) { case vt_i32: return LLVMInt32Type(); case vt_i64: return LLVMInt64Type(); case vt_f32: return LLVMFloatType(); case vt_f64: return LLVMDoubleType(); default: throw malformed_exception("unexpected value type"); } } std::function<LLVMValueRef()> module::parse_llvm_init(LLVMTypeRef pType) { std::function<LLVMValueRef()> lResult; uint8_t lInstr = parse<uint8_t>(); switch (lInstr) { case o_const_i32: { if (pType != LLVMInt32Type()) throw invalid_exception("init i32, expected other type"); int32_t lValue = parse_sleb128<int32_t>(); lResult = [lValue] { return LLVMConstInt(LLVMInt32Type(), lValue, true); }; } break; case o_const_i64: { if (pType != LLVMInt64Type()) throw invalid_exception("init i64, expected other type"); int64_t lValue = parse_sleb128<int64_t>(); lResult = [lValue] { return LLVMConstInt(LLVMInt64Type(), lValue, true); }; } break; case o_const_f32: { if (pType != LLVMFloatType()) throw invalid_exception("init f32, expected other type"); float lValue = parse<float>(); lResult = [lValue] { return LLVMConstReal(LLVMFloatType(), lValue); }; } break; case o_const_f64: { if (pType != LLVMDoubleType()) throw invalid_exception("init f64, expected other type"); double lValue = parse<double>(); lResult = [lValue] { return LLVMConstReal(LLVMDoubleType(), lValue); }; } break; case o_get_global: { uint32_t lIndex = parse_sleb128<uint32_t>(); if (lIndex >= mGlobals.size()) throw invalid_exception("global index out of bounds"); if (pType != LLVMGetElementType(LLVMTypeOf(mGlobals[lIndex]))) { throw invalid_exception("init global, expected other type"); } lResult = [this, lIndex] { return LLVMBuildLoad(mBuilder, mGlobals[lIndex], "globalInit"); }; } break; default: throw invalid_exception("unsupported init expr instr"); } uint8_t lEnd = parse<uint8_t>(); if (lEnd != o_end) throw invalid_exception("expected end after init expr"); assert(lResult); return lResult; } LLVMValueRef module::get_zero(LLVMTypeRef pType) { if (pType == LLVMInt32Type()) return LLVMConstInt(LLVMInt32Type(), 0, true); else if (pType == LLVMInt64Type()) return LLVMConstInt(LLVMInt64Type(), 0, true); else if (pType == LLVMFloatType()) return LLVMConstReal(LLVMFloatType(), 0); else if (pType == LLVMDoubleType()) return LLVMConstReal(LLVMDoubleType(), 0); else throw std::runtime_error("unexpected value type"); } LLVMValueRef module::get_string(const char *pString) { return LLVMBuildIntToPtr(mBuilder, get_const(i64(pString)), LLVMPointerType(LLVMInt8Type(), 0), "string"); } LLVMValueRef module::clear_nan_internal(LLVMTypeRef pInputType, LLVMTypeRef pIntType, LLVMValueRef pInput, LLVMValueRef pConstMaskSignificand, LLVMValueRef pConstMaskExponent, LLVMValueRef pConstNanBit) { LLVMValueRef lRaw = LLVMBuildBitCast(mBuilder, pInput, pIntType, "raw"); LLVMValueRef lSignificand = LLVMBuildAnd(mBuilder, lRaw, pConstMaskSignificand, "significand"); LLVMValueRef lNotInf = LLVMBuildICmp(mBuilder, LLVMIntNE, lSignificand, get_zero(pIntType), "notInf"); LLVMValueRef lExponent = LLVMBuildAnd(mBuilder, lRaw, pConstMaskExponent, "exponent"); LLVMValueRef lMaxExp = LLVMBuildICmp(mBuilder, LLVMIntEQ, lExponent, pConstMaskExponent, "maxExp"); LLVMValueRef lIsNan = LLVMBuildAnd(mBuilder, lNotInf, lMaxExp, "isNan"); LLVMValueRef lCleanedNan = LLVMBuildOr(mBuilder, lRaw, pConstNanBit, "cleanedNan"); LLVMValueRef lRawResult = LLVMBuildSelect(mBuilder, lIsNan, lCleanedNan, lRaw, "select_nan"); return LLVMBuildBitCast(mBuilder, lRawResult, pInputType, "result"); } LLVMValueRef module::clear_nan(LLVMValueRef pInput) { LLVMTypeRef lType = LLVMTypeOf(pInput); if (lType == LLVMFloatType()) { LLVMValueRef lSignificandMask = LLVMConstInt(LLVMInt32Type(), 8388607ULL, false); LLVMValueRef lExponentMask = LLVMConstInt(LLVMInt32Type(), 2139095040ULL, false); LLVMValueRef lConstNanBit = LLVMConstInt(LLVMInt32Type(), 4194304ULL, false); return clear_nan_internal(lType, LLVMInt32Type(), pInput, lSignificandMask, lExponentMask, lConstNanBit); } else if (lType == LLVMDoubleType()) { LLVMValueRef lSignificandMask = LLVMConstInt(LLVMInt64Type(), 4503599627370495ULL, false); LLVMValueRef lExponentMask = LLVMConstInt(LLVMInt64Type(), 9218868437227405312ULL, false); LLVMValueRef lConstNanBit = LLVMConstInt(LLVMInt64Type(), 2251799813685248ULL, false); return clear_nan_internal(lType, LLVMInt64Type(), pInput, lSignificandMask, lExponentMask, lConstNanBit); } else { throw std::runtime_error("wrong type while clearing nan"); } } void module::parse_types() { uint32_t lCount = parse_uleb128<uint32_t>(); mTypes.resize(lCount); for (size_t lType = 0; lType < lCount; lType++) { parse<uint8_t>(); // "form", should always be 0x60 const size_t lParamTypeCount = parse_uleb128<uint32_t>(); LLVMTypeRef lParamTypes[lParamTypeCount]; for (size_t lParamType = 0; lParamType < lParamTypeCount; lParamType++) lParamTypes[lParamType] = parse_llvm_vtype(); const size_t lReturnTypesCount = parse_uleb128<uint32_t>(); if (lReturnTypesCount > 1) throw invalid_exception("only one return type supported"); LLVMTypeRef lReturnType = lReturnTypesCount ? parse_llvm_vtype() : LLVMVoidType(); mTypes[lType] = LLVMFunctionType(lReturnType, lParamTypes, uint(lParamTypeCount), false); } profile_step(" module/types"); } void module::parse_imports() { uint32_t lCount = parse_uleb128<uint32_t>(); for (size_t lImport = 0; lImport < lCount; lImport++) { uint32_t lSize = parse_uleb128<uint32_t>(); std::string_view lModule = parse_str(lSize); lSize = parse_uleb128<uint32_t>(); std::string_view lField = parse_str(lSize); external_kind lKind = (external_kind)parse<uint8_t>(); std::stringstream lName; lName << "__wimport_" << lModule << '_' << lField; switch (lKind) { case ek_function: { uint32_t lTypeIndex = parse_uleb128<uint32_t>(); if (lTypeIndex >= mTypes.size()) throw invalid_exception("invalid type index"); LLVMTypeRef lType = mTypes[lTypeIndex]; // Add base memory as parameter size_t lParamCount = LLVMCountParamTypes(lType); std::vector<LLVMTypeRef> lParams(lParamCount); LLVMGetParamTypes(lType, lParams.data()); LLVMValueRef lFunction = LLVMAddFunction(mModule, "wembed.func", lType); LLVMSetLinkage(lFunction, LLVMLinkage::LLVMExternalLinkage); const uint64_t lTypeHash = hash_fn_type(lType); mFunctions.emplace_back(lFunction, lTypeHash); mImports[std::string(lModule)].emplace(std::string(lField), symbol_t{ek_function, hash_fn_type(lType), lFunction}); #ifdef WEMBED_VERBOSE std::cout << "Import func " << mFunctions.size() << ": " << LLVMPrintTypeToString(lType) << ", hash:" << hash_fn_type(lType) << std::endl; #endif } break; case ek_global: { LLVMTypeRef lType = parse_llvm_vtype(); uint8_t lMutable = parse<uint8_t>(); LLVMValueRef lGlobal = LLVMAddGlobal(mModule, lType, "wembed.glob"); LLVMSetLinkage(lGlobal, LLVMLinkage::LLVMExternalLinkage); LLVMSetGlobalConstant(lGlobal, !lMutable); #ifdef WEMBED_VERBOSE std::cout << "Import global " << mGlobals.size() << ": " << LLVMPrintTypeToString(lType) << ", hash:" << hash_type(lType) << std::endl; #endif mGlobals.emplace_back(lGlobal); mImports[std::string(lModule)].emplace(std::string(lField), symbol_t{ek_global, hash_type(lType, !lMutable), lGlobal}); } break; case ek_table: { mTableImport.mModule = lModule; mTableImport.mField = lField; if (!mTables.empty()) throw invalid_exception("multiple tables not supported"); table_type lType = parse_table_type(); LLVMTypeRef lContainerType = LLVMPointerType(LLVMInt8Type(), 0); LLVMValueRef lPointers = LLVMAddGlobal(mModule, lContainerType, "wembed.tablePtrs"); LLVMValueRef lTypes = LLVMAddGlobal(mModule, LLVMInt64Type(), "wembed.tableTypes"); mTables.emplace_back(lType, lPointers, lTypes); LLVMSetLinkage(lPointers, LLVMLinkage::LLVMExternalLinkage); LLVMSetLinkage(lTypes, LLVMLinkage::LLVMExternalLinkage); mImports[std::string(lModule)].emplace(std::string(lField), symbol_t{ek_table, WEMBED_HASH_TABLE, {lPointers, lTypes}}); } break; case ek_memory: { if (!mMemoryTypes.empty()) throw invalid_exception("multiple memories"); mMemoryImport.mModule = lModule; mMemoryImport.mField = lField; memory_type lMemType; lMemType.mLimits = parse_resizable_limits(); if (lMemType.mLimits.mInitial > 65536 || (lMemType.mLimits.mFlags && lMemType.mLimits.mMaximum > 65536)) throw invalid_exception("memory size too big, max 65536 pages"); mMemoryTypes.emplace_back(lMemType); mImports[std::string(lModule)].emplace(std::string(lField), symbol_t{ek_memory, WEMBED_HASH_MEMORY, mBaseMemory}); } break; default: throw malformed_exception("unexpected import kind"); } } mImportFuncOffset = mFunctions.size(); profile_step(" module/imports"); } void module::parse_functions() { mImportFuncOffset = mFunctions.size(); uint32_t lCount = parse_uleb128<uint32_t>(); for (size_t lFunc = 0; lFunc < lCount; lFunc++) { uint32_t lTIndex = parse_uleb128<uint32_t>(); if (lTIndex >= mTypes.size()) throw invalid_exception("type index out of range"); LLVMValueRef lFuncRef = LLVMAddFunction(mModule, "wembed.func", mTypes[lTIndex]); mFunctions.emplace_back(lFuncRef, hash_fn_type(mTypes[lTIndex])); } profile_step(" module/functions"); } void module::parse_section_table(uint32_t pSectionSize) { uint32_t lCount = parse_uleb128<uint32_t>(); for (size_t lI = 0; lI < lCount; lI++) { if (!mTables.empty()) throw invalid_exception("multiple tables not supported"); table_type lType = parse_table_type(); LLVMTypeRef lContainerType = LLVMPointerType(LLVMInt8Type(), 0); LLVMValueRef lPointers = LLVMAddGlobal(mModule, lContainerType, "wembed.tablePtrs"); LLVMValueRef lTypes = LLVMAddGlobal(mModule, LLVMInt64Type(), "wembed.tableTypes"); mTables.emplace_back(lType, lPointers, lTypes); } profile_step(" module/tables"); } void module::parse_section_memory(uint32_t pSectionSize) { uint32_t lCount = parse_uleb128<uint32_t>(); if (lCount > 1) throw invalid_exception("only one memory region supported"); if (!mMemoryTypes.empty() && lCount > 0) throw invalid_exception("multiple memories"); for (size_t lI = 0; lI < lCount; lI++) { memory_type lResult; lResult.mLimits = parse_resizable_limits(); if (lResult.mLimits.mInitial > 65536 || (lResult.mLimits.mFlags && lResult.mLimits.mMaximum > 65536)) throw invalid_exception("memory size too big, max 65536 pages"); mMemoryTypes.emplace_back(lResult); } profile_step(" module/memories"); } void module::parse_globals() { LLVMValueRef lInit = LLVMAddFunction(mModule, "wembed.start.globals", LLVMFunctionType(LLVMVoidType(), nullptr, 0, false)); LLVMBasicBlockRef lBlock = LLVMAppendBasicBlock(lInit, "entry"); LLVMPositionBuilderAtEnd(mBuilder, lBlock); uint32_t lCount = parse_uleb128<uint32_t>(); for (size_t lI = 0; lI < lCount; lI++) { LLVMTypeRef lType = parse_llvm_vtype(); uint8_t lMutable = parse<uint8_t>(); auto lInitValue = parse_llvm_init(lType); auto lValue = lInitValue(); #ifdef WEMBED_VERBOSE std::cout << "Global " << mGlobals.size() << " " << LLVMPrintTypeToString(lType) << ": " << LLVMPrintValueToString(lValue) << std::endl; #endif LLVMValueRef lGlobal = LLVMAddGlobal(mModule, lType, "wembed.global"); LLVMSetGlobalConstant(lGlobal, !lMutable); if (LLVMIsConstant(lValue)) { LLVMSetInitializer(lGlobal, lValue); } else { LLVMSetInitializer(lGlobal, get_zero(lType)); LLVMBuildStore(mBuilder, lValue, lGlobal); LLVMSetGlobalConstant(lGlobal, false); } mGlobals.emplace_back(lGlobal); } LLVMBuildRetVoid(mBuilder); LLVMPositionBuilderAtEnd(mBuilder, mStartInit); LLVMBuildCall(mBuilder, lInit, nullptr, 0, ""); profile_step(" module/globals"); } void module::parse_exports() { uint32_t lCount = parse_uleb128<uint32_t>(); for (size_t lI = 0; lI < lCount; lI++) { uint32_t lSize = parse_uleb128<uint32_t>(); std::string_view lName = parse_str(lSize); if (mExports.find(std::string(lName)) != mExports.end()) throw invalid_exception("duplicate export name"); external_kind lKind = parse_external_kind(); uint32_t lIndex = parse_uleb128<uint32_t>(); switch (lKind) { case ek_function: { if (lIndex >= mFunctions.size()) throw invalid_exception("function index out of bounds"); auto lFuncDef = mFunctions[lIndex]; mExports.emplace(std::string(lName), symbol_t{lKind, lFuncDef.mType, {mFunctions[lIndex].mValue}}); //LLVMSetLinkage(mFunctions[lIndex], LLVMInternalLinkage); #ifdef WEMBED_VERBOSE std::cout << "Export func " << lIndex << ": " << LLVMPrintTypeToString(LLVMTypeOf(lFuncDef.mValue)) << ", hash:" << lFuncDef.mType << std::endl; #endif } break; case ek_global: { if (lIndex >= mGlobals.size()) throw invalid_exception("global index out of bounds"); LLVMTypeRef lType = LLVMGetElementType(LLVMTypeOf(mGlobals[lIndex])); mExports.emplace(lName, symbol_t{lKind, hash_type(lType, LLVMIsGlobalConstant(mGlobals[lIndex]) != 0), {mGlobals[lIndex]}}); //LLVMSetLinkage(mGlobals[lIndex], LLVMInternalLinkage); #ifdef WEMBED_VERBOSE std::cout << "Export global " << lIndex << ": " << LLVMPrintTypeToString(lType) << ", hash:" << hash_type(lType) << std::endl; #endif } break; case ek_table: { if (lIndex >= mTables.size()) throw invalid_exception("table index out of bounds"); mExports.emplace(lName, symbol_t{lKind, WEMBED_HASH_TABLE, {mTables[0].mPointers, mTables[0].mTypes}}); //LLVMSetLinkage(mTables[0].mPointers, LLVMInternalLinkage); //LLVMSetLinkage(mTables[0].mTypes, LLVMInternalLinkage); } break; case ek_memory: { if (lIndex >= mMemoryTypes.size()) throw invalid_exception("memory index out of bounds"); mExports.emplace(lName, symbol_t{lKind, WEMBED_HASH_MEMORY, {mBaseMemory}}); //(mBaseMemory, LLVMInternalLinkage); } break; default: throw std::runtime_error("unsupported export type"); break; } } profile_step(" module/exports"); } void module::parse_section_start(uint32_t pSectionSize) { LLVMPositionBuilderAtEnd(mBuilder, mStartUser); uint32_t lIndex = parse_uleb128<uint32_t>(); if (lIndex >= mFunctions.size()) throw invalid_exception("function index out of bounds"); LLVMTypeRef lStartSignature = LLVMGetElementType(LLVMTypeOf(mFunctions[lIndex].mValue)); if (LLVMGetReturnType(lStartSignature) != LLVMVoidType()) throw invalid_exception("start function required to return void"); if (LLVMCountParamTypes(lStartSignature) > 0) throw invalid_exception("start function require no input param"); LLVMBuildCall(mBuilder, mFunctions[lIndex].mValue, nullptr, 0, ""); profile_step(" module/start"); } void module::parse_section_element(uint32_t pSectionSize) { LLVMValueRef lInit = LLVMAddFunction(mModule, "wembed.start.element", LLVMFunctionType(LLVMVoidType(), nullptr, 0, false)); LLVMBasicBlockRef lChecks = LLVMAppendBasicBlock(lInit, "checks"); LLVMBasicBlockRef lCopies = LLVMAppendBasicBlock(lInit, "copies"); uint32_t lCount = parse_uleb128<uint32_t>(); for (size_t lI = 0; lI < lCount; lI++) { uint32_t lIndex = parse_uleb128<uint32_t>(); if (lIndex >= mTables.size()) throw invalid_exception("table index out of bounds"); const Table &lTable = mTables[lIndex]; LLVMPositionBuilderAtEnd(mBuilder, lChecks); auto lOffsetInit = parse_llvm_init(LLVMInt32Type()); { LLVMValueRef lOffset = lOffsetInit(); LLVMValueRef lTabSize = LLVMBuildCall(mBuilder, mTableSize, &mContextRef, 1, "curTabSize"); LLVMValueRef lOffsetOverflow = LLVMBuildICmp(mBuilder, LLVMIntUGT, lOffset, lTabSize, "offsetOverflow"); static const char *lErrorString = "elements segment does not fit"; lChecks = trap_if(lInit, lOffsetOverflow, mThrowUnlinkable, {get_string(lErrorString)}); } if (lTable.mType.mType == e_anyfunc) { uint32_t lElemCount = parse_uleb128<uint32_t>(); for (uint32_t lElemIndex = 0; lElemIndex < lElemCount; lElemIndex++) { uint32_t lFuncIndex = parse_uleb128<uint32_t>(); if (lFuncIndex >= mFunctions.size()) throw invalid_exception("function index out of bounds"); LLVMPositionBuilderAtEnd(mBuilder, lChecks); { LLVMValueRef lOffset = lOffsetInit(); LLVMValueRef lTotalOffset = LLVMBuildAdd(mBuilder, lOffset, get_const(lElemIndex), "totalOffset"); lChecks = trap_elem_copy(lInit, lTotalOffset); } LLVMPositionBuilderAtEnd(mBuilder, lCopies); { LLVMValueRef lOffset = lOffsetInit(); LLVMValueRef lTotalOffset = LLVMBuildAdd(mBuilder, lOffset, get_const(lElemIndex), "totalOffset"); LLVMValueRef lTablePtr = LLVMBuildPointerCast(mBuilder, lTable.mPointers, LLVMPointerType(LLVMPointerType(LLVMInt8Type(), 0), 0), "table"); LLVMValueRef lPointer = LLVMBuildInBoundsGEP(mBuilder, lTablePtr, &lTotalOffset, 1, "gep"); // Stores the indices, it's the context that will replace them to func ptr LLVMBuildStore(mBuilder, LLVMBuildIntToPtr(mBuilder, get_const(lFuncIndex + 1), LLVMPointerType(LLVMInt8Type(), 0), "cast"), lPointer); } } } } LLVMPositionBuilderAtEnd(mBuilder, lChecks); LLVMBuildBr(mBuilder, lCopies); LLVMPositionBuilderAtEnd(mBuilder, lCopies); LLVMBuildRetVoid(mBuilder); LLVMPositionBuilderAtEnd(mBuilder, mStartInit); LLVMBuildCall(mBuilder, lInit, nullptr, 0, ""); profile_step(" module/elements"); } void module::parse_section_data(uint32_t pSectionSize) { if (mMemoryTypes.empty()) throw invalid_exception("data provided without memory section"); LLVMValueRef lInit = LLVMAddFunction(mModule, "wembed.start.data", LLVMFunctionType(LLVMVoidType(), nullptr, 0, false)); LLVMBasicBlockRef lChecks = LLVMAppendBasicBlock(lInit, "checks"); LLVMBasicBlockRef lCopies = LLVMAppendBasicBlock(lInit, "copies"); LLVMPositionBuilderAtEnd(mBuilder, lChecks); uint32_t lCount = parse_uleb128<uint32_t>(); for (size_t lI = 0; lI < lCount; lI++) { uint32_t lIndex = parse_uleb128<uint32_t>(); if (lIndex != 0) throw invalid_exception("multiple memory block not supported"); auto lOffsetInit = parse_llvm_init(LLVMInt32Type()); LLVMValueRef lOffset = lOffsetInit(); uint32_t lSize = parse_uleb128<uint32_t>(); LLVMPositionBuilderAtEnd(mBuilder, lChecks); lChecks = trap_data_copy(lInit, lOffset, lSize); if (lSize > 0) { LLVMPositionBuilderAtEnd(mBuilder, lCopies); call_intrinsic(mMemCpy, { LLVMBuildInBoundsGEP(mBuilder, mBaseMemory, &lOffset, 1, "offseted"), LLVMConstIntToPtr(LLVMConstInt(LLVMInt64Type(), ull_t(mCurrent), false), LLVMPointerType(LLVMInt8Type(), 0)), LLVMConstInt(LLVMInt32Type(), lSize, false), LLVMConstInt(LLVMInt1Type(), 1, false), }); mCurrent += lSize; #ifdef WEMBED_VERBOSE std::cout << "data copy from " << ull_t(mCurrent) << " to " << LLVMPrintValueToString(lOffset) << std::endl; #endif } } LLVMPositionBuilderAtEnd(mBuilder, lChecks); LLVMBuildBr(mBuilder, lCopies); LLVMPositionBuilderAtEnd(mBuilder, lCopies); LLVMBuildRetVoid(mBuilder); LLVMPositionBuilderAtEnd(mBuilder, mStartInit); LLVMBuildCall(mBuilder, lInit, nullptr, 0, ""); profile_step(" module/data"); } void module::skip_unreachable(uint8_t *pPastEnd) { auto &up = mCFEntries.back(); if (up.mOuterStackSize > mEvalStack.size()) throw invalid_exception("invalid stack state"); mEvalStack.resize(up.mOuterStackSize); up.mReachable = false; mUnreachableDepth = 0; } void module::parse_section_code(uint32_t pSectionSize) { uint32_t lCount = parse_uleb128<uint32_t>(); for (size_t lCode = 0; lCode < lCount; lCode++) { size_t lFIndex = mImportFuncOffset + lCode; if (lFIndex >= mFunctions.size()) throw invalid_exception("function index out of bounds"); LLVMValueRef lFunc = mFunctions[lFIndex].mValue; LLVMTypeRef lFuncType = LLVMGetElementType(LLVMTypeOf(lFunc)); LLVMTypeRef lReturnType = LLVMGetReturnType(lFuncType); std::vector<LLVMValueRef> lParams(LLVMCountParams(lFunc)); LLVMGetParams(lFunc, lParams.data()); std::vector<LLVMTypeRef> lParamTypes(LLVMCountParamTypes(lFuncType)); LLVMGetParamTypes(lFuncType, lParamTypes.data()); LLVMBasicBlockRef lFuncEnd = LLVMAppendBasicBlock(lFunc, "fEnd"); LLVMValueRef lReturnPhi = create_phi(lReturnType, lFuncEnd); pushCFEntry(cf_function, lReturnType, lFuncEnd, lReturnPhi); pushBlockEntry(lReturnType, lFuncEnd, lReturnPhi); LLVMBasicBlockRef lFuncEntry = LLVMAppendBasicBlock(lFunc, "fEntry"); LLVMPositionBuilderAtEnd(mBuilder, lFuncEntry); std::vector<LLVMValueRef> lLocals; std::vector<LLVMTypeRef> lLocalTypes; for(size_t lIndexArg = 0; lIndexArg < lParams.size(); lIndexArg++) { LLVMValueRef lAlloc = LLVMBuildAlloca(mBuilder, lParamTypes[lIndexArg], "param"); LLVMBuildStore(mBuilder, lParams[lIndexArg], lAlloc); lLocals.emplace_back(lAlloc); lLocalTypes.emplace_back(LLVMTypeOf(lAlloc)); } uint32_t lBodySize = parse_uleb128<uint32_t>(); uint8_t *lBefore = mCurrent; #ifdef WEMBED_VERBOSE std::cout << "At PC 0x" << std::hex << (mCurrent - lCodeSectionStart) << std::dec << " parsing code for func " << lFIndex << ": " << LLVMGetValueName(lFunc) << ", type " << LLVMPrintTypeToString(lFuncType) << std::endl; #endif uint32_t lGroupCount = parse_uleb128<uint32_t>(); for (size_t lLocalBlock = 0; lLocalBlock < lGroupCount; lLocalBlock++) { uint32_t lLocalsCount = parse_uleb128<uint32_t>(); LLVMTypeRef lType = parse_llvm_vtype(); LLVMValueRef lZero = get_zero(lType); for (size_t lLocal = 0; lLocal < lLocalsCount; lLocal++) { LLVMValueRef lAlloc = LLVMBuildAlloca(mBuilder, lType, "local"); lLocals.emplace_back(lAlloc); lLocalTypes.emplace_back(LLVMTypeOf(lAlloc)); LLVMBuildStore(mBuilder, lZero, lAlloc); } } size_t lCodeSize = lBodySize - (mCurrent - lBefore); uint8_t *lEndPos = mCurrent + lCodeSize; while (mCurrent < lEndPos && !mCFEntries.empty()) { #if defined(WEMBED_VERBOSE) && 0 std::cout << "At PC 0x" << std::hex << (mCurrent - lCodeSectionStart) << ", instruction 0x" << (uint32_t)*mCurrent << std::dec << ", reachable: " << mCFEntries.back().mReachable << ", depth: " << mUnreachableDepth << std::endl; #endif uint8_t lInstr = *mCurrent++; if (!mCFEntries.back().mReachable) { switch (lInstr) { case o_block: case o_loop: case o_if: mUnreachableDepth++; parse_llvm_btype(); continue; case o_else: if (!mUnreachableDepth) break; continue; case o_end: if (!mUnreachableDepth) break; else mUnreachableDepth--; continue; case o_memory_grow: case o_memory_size: mCurrent++; continue; case o_br: case o_const_i32: case o_get_local: case o_set_local: case o_tee_local: case o_get_global: case o_set_global: case o_call: case o_br_if: parse_uleb128<uint32_t>(); continue; case o_const_i64: parse_uleb128<uint64_t>(); continue; case o_const_f32: parse<float>(); continue; case o_const_f64: parse<double>(); continue; case o_call_indirect: parse_uleb128<uint32_t>(); mCurrent++; continue; case o_store_f32: case o_store_i32: case o_load_f32: case o_load_i32: case o_load8_si32: case o_load16_si32: case o_load8_ui32: case o_load16_ui32: case o_store8_i32: case o_store16_i32: parse_uleb128<uint32_t>(); parse_uleb128<uint32_t>(); continue; case o_store_f64: case o_store_i64: case o_load_f64: case o_load_i64: case o_load8_si64: case o_load16_si64: case o_load32_si64: case o_load8_ui64: case o_load16_ui64: case o_load32_ui64: case o_store8_i64: case o_store16_i64: case o_store32_i64: parse_uleb128<uint32_t>(); parse_uleb128<uint64_t>(); continue; case o_br_table: { uint32_t lTargetCount = parse_uleb128<uint32_t>(); for (size_t i = 0; i < lTargetCount; i++) parse_uleb128<uint32_t>(); parse_uleb128<uint32_t>(); continue; } case o_prefix_numeric: mCurrent++; continue; default: continue; } } switch (lInstr) { case o_nop: break; case o_drop: pop(); break; case o_block: { LLVMTypeRef lType = parse_llvm_btype(); auto lBlockEnd = LLVMAppendBasicBlock(lFunc, "bEnd"); LLVMValueRef lPhi = create_phi(lType, lBlockEnd); pushCFEntry(cf_block, lType, lBlockEnd, lPhi); pushBlockEntry(lType, lBlockEnd, lPhi); } break; case o_loop: { LLVMTypeRef lType = parse_llvm_btype(); LLVMBasicBlockRef lLoop = LLVMAppendBasicBlock(lFunc, "lEntry"); LLVMBasicBlockRef lEnd = LLVMAppendBasicBlock(lFunc, "lEnd"); LLVMValueRef lPhi = create_phi(lType, lEnd); LLVMBuildBr(mBuilder, lLoop); LLVMPositionBuilderAtEnd(mBuilder, lLoop); pushCFEntry(cf_loop, lType, lEnd, lPhi); pushBlockEntry(LLVMVoidType(), lLoop, nullptr); } break; case o_if: { LLVMTypeRef lType = parse_llvm_btype(); LLVMBasicBlockRef lThen = LLVMAppendBasicBlock(lFunc, "iThen"); LLVMBasicBlockRef lElse = LLVMAppendBasicBlock(lFunc, "iElse"); LLVMBasicBlockRef lEnd = LLVMAppendBasicBlock(lFunc, "iEnd"); LLVMValueRef lPhi = create_phi(lType, lEnd); LLVMBuildCondBr(mBuilder, i32_to_bool(pop(LLVMInt32Type())), lThen, lElse); LLVMPositionBuilderAtEnd(mBuilder, lThen); pushCFEntry(cf_if, lType, lEnd, lPhi, lElse); pushBlockEntry(lType, lEnd, lPhi); } break; case o_else: { assert(mCFEntries.size() && "empty control flow"); CFEntry &lEntry = mCFEntries.back(); if (lEntry.mReachable) { if (lEntry.mSignature != LLVMVoidType()) { auto lValue = pop(lEntry.mSignature); auto lWhere = LLVMGetInsertBlock(mBuilder); LLVMAddIncoming(lEntry.mPhi, &lValue, &lWhere, 1); } LLVMBuildBr(mBuilder, lEntry.mEnd); } if (mEvalStack.size() != lEntry.mOuterStackSize) throw invalid_exception("wrong stack size after block end"); assert(lEntry.mElse); assert(lEntry.mInstr == cf_if); auto lCurrentBlock = LLVMGetInsertBlock(mBuilder); LLVMMoveBasicBlockAfter(lEntry.mElse, lCurrentBlock); LLVMPositionBuilderAtEnd(mBuilder, lEntry.mElse); lEntry.mInstr = cf_else; lEntry.mReachable = lEntry.mElseReachable; lEntry.mElse = nullptr; } break; case o_end: { assert(mCFEntries.size() && "empty control flow"); const CFEntry &lEntry = mCFEntries.back(); if (lEntry.mReachable) { if (lEntry.mSignature != LLVMVoidType()) { auto lValue = pop(LLVMTypeOf(lEntry.mPhi)); auto lWhere = LLVMGetInsertBlock(mBuilder); LLVMAddIncoming(lEntry.mPhi, &lValue, &lWhere, 1); } LLVMBuildBr(mBuilder, lEntry.mEnd); } if (mEvalStack.size() != lEntry.mOuterStackSize) throw invalid_exception("wrong stack size after block end"); if (lEntry.mElse) { auto lCurrentBlock = LLVMGetInsertBlock(mBuilder); LLVMMoveBasicBlockAfter(lEntry.mElse, lCurrentBlock); LLVMPositionBuilderAtEnd(mBuilder, lEntry.mElse); LLVMBuildBr(mBuilder, lEntry.mEnd); } auto lCurrentBlock = LLVMGetInsertBlock(mBuilder); LLVMMoveBasicBlockAfter(lEntry.mEnd, lCurrentBlock); LLVMPositionBuilderAtEnd(mBuilder, lEntry.mEnd); if (lEntry.mPhi) { if(LLVMCountIncoming(lEntry.mPhi)) { push(lEntry.mPhi); } else { LLVMInstructionEraseFromParent(lEntry.mPhi); assert(lEntry.mSignature != LLVMVoidType()); push(get_zero(lEntry.mSignature)); } } assert(lEntry.mOuterBlockDepth <= mBlockEntries.size()); mBlockEntries.resize(lEntry.mOuterBlockDepth); mCFEntries.pop_back(); } break; case o_unreachable: { const char *lErrorString = "unreachable reached"; trap_if(lFunc, get_const(true), mThrowVMException, {get_string(lErrorString)}); LLVMBuildUnreachable(mBuilder); skip_unreachable(lEndPos); } break; case o_br: { uint32_t lDepth = parse_uleb128<uint32_t>(); const BlockEntry &lTarget = branch_depth(lDepth); if (lTarget.mSignature != LLVMVoidType()) { LLVMValueRef lResult = pop(lTarget.mSignature); auto lWhere = LLVMGetInsertBlock(mBuilder); LLVMAddIncoming(lTarget.mPhi, &lResult, &lWhere, 1); } LLVMBuildBr(mBuilder, lTarget.mBlock); skip_unreachable(lEndPos); } break; case o_br_if: { auto lCond = pop(LLVMInt32Type()); uint32_t lDepth = parse_uleb128<uint32_t>(); const BlockEntry &lTarget = branch_depth(lDepth); if (lTarget.mSignature != LLVMVoidType()) { LLVMValueRef lResult = top(lTarget.mSignature); auto lWhere = LLVMGetInsertBlock(mBuilder); LLVMAddIncoming(lTarget.mPhi, &lResult, &lWhere, 1); } LLVMBasicBlockRef lElse = LLVMAppendBasicBlock(lFunc, "afterBrIf"); LLVMBuildCondBr(mBuilder, i32_to_bool(lCond), lTarget.mBlock, lElse); LLVMPositionBuilderAtEnd(mBuilder, lElse); } break; case o_br_table: { auto lIndex = pop(LLVMInt32Type()); uint32_t lTargetCount = parse_uleb128<uint32_t>(); std::vector<uint32_t> lTargets(lTargetCount); for (size_t i = 0; i < lTargetCount; i++) { lTargets[i] = parse_uleb128<uint32_t>(); } uint32_t lDefault = parse_uleb128<uint32_t>(); const BlockEntry &lDefaultTarget = branch_depth(lDefault); LLVMValueRef lResult = nullptr; if (lDefaultTarget.mSignature != LLVMVoidType()) { lResult = pop(lDefaultTarget.mSignature); auto lWhere = LLVMGetInsertBlock(mBuilder); LLVMAddIncoming(lDefaultTarget.mPhi, &lResult, &lWhere, 1); } LLVMValueRef lSwitch = LLVMBuildSwitch(mBuilder, lIndex, lDefaultTarget.mBlock, lTargets.size()); for (size_t i = 0; i < lTargets.size(); i++) { const BlockEntry &lTarget = branch_depth(lTargets[i]); if (lTarget.mSignature != lDefaultTarget.mSignature) throw invalid_exception("br_table type mismatch"); LLVMAddCase(lSwitch, get_const((uint32_t)i), lTarget.mBlock); if (lResult != nullptr) { auto lWhere = LLVMGetInsertBlock(mBuilder); LLVMAddIncoming(lTarget.mPhi, &lResult, &lWhere, 1); } } skip_unreachable(lEndPos); } break; case o_return: { if (lReturnType != LLVMVoidType()) { auto lValue = pop(lReturnType); auto lWhere = LLVMGetInsertBlock(mBuilder); LLVMAddIncoming(mCFEntries[0].mPhi, &lValue, &lWhere, 1); } LLVMBuildBr(mBuilder, mCFEntries[0].mEnd); skip_unreachable(lEndPos); } break; case o_call: { uint32_t lCalleeIndex = parse_uleb128<uint32_t>(); if (lCalleeIndex >= mFunctions.size()) throw invalid_exception("function index out of bounds"); LLVMValueRef lCallee = mFunctions[lCalleeIndex].mValue; LLVMTypeRef lCalleeType = LLVMGetElementType(LLVMTypeOf(lCallee)); size_t lCalleeParamCount = LLVMCountParams(lCallee); if (lCalleeParamCount > mEvalStack.size()) throw invalid_exception("not enough args in stack"); std::vector<LLVMValueRef> lCalleeParams(lCalleeParamCount); std::copy(mEvalStack.end() - lCalleeParamCount, mEvalStack.end(), lCalleeParams.begin()); mEvalStack.resize(mEvalStack.size() - lCalleeParamCount); std::vector<LLVMTypeRef> lArgTypes(LLVMCountParamTypes(lCalleeType)); LLVMGetParamTypes(lCalleeType, lArgTypes.data()); for (size_t i = 0; i < lCalleeParamCount; i++) { if (LLVMTypeOf(lCalleeParams[i]) != lArgTypes[i]) throw invalid_exception("arg type mismatch"); } bool lCalleeReturnValue = LLVMGetReturnType(lCalleeType) != LLVMVoidType(); auto lResult = LLVMBuildCall(mBuilder, lCallee, lCalleeParams.data(), lCalleeParams.size(), lCalleeReturnValue ? "call" : ""); if(lCalleeReturnValue) { push(lResult); } } break; case o_call_indirect: { if (mTables.empty()) throw invalid_exception("can't use call indirect without table"); uint32_t lSignature = parse_uleb128<uint32_t>(); /*uint8_t lReserved =*/ parse_uleb128<uint8_t>(); LLVMValueRef lCalleeIndice = pop(LLVMInt32Type()); if (lSignature >= mTypes.size()) throw invalid_exception("invalid type index"); LLVMTypeRef lCalleeType = mTypes[lSignature]; LLVMTypeRef lCalleePtr = LLVMPointerType(lCalleeType, 0); size_t lCalleeParamCount = LLVMCountParamTypes(lCalleeType); if (lCalleeParamCount > mEvalStack.size()) throw invalid_exception("not enough args in stack"); std::vector<LLVMValueRef> lCalleeParams(lCalleeParamCount); std::copy(mEvalStack.end() - lCalleeParamCount, mEvalStack.end(), lCalleeParams.begin()); mEvalStack.resize(mEvalStack.size() - lCalleeParamCount); std::vector<LLVMTypeRef> lArgTypes(lCalleeParamCount); LLVMGetParamTypes(lCalleeType, lArgTypes.data()); for (size_t i = 0; i < lCalleeParamCount; i++) { if (LLVMTypeOf(lCalleeParams[i]) != lArgTypes[i]) throw invalid_exception("arg type mismatch"); } bool lCalleeReturnValue = LLVMGetReturnType(lCalleeType) != LLVMVoidType(); const Table &lTable = mTables[0]; uint64_t lTypeHash = hash_fn_type(lCalleeType); LLVMValueRef lTableTypes = LLVMBuildPointerCast(mBuilder, lTable.mTypes, LLVMPointerType(LLVMInt64Type(), 0), "tableType"); LLVMValueRef lTableTypePtr = LLVMBuildInBoundsGEP(mBuilder, lTableTypes, &lCalleeIndice, 1, "gep"); LLVMValueRef lType = LLVMBuildLoad(mBuilder, lTableTypePtr, "loadPtr"); LLVMValueRef lTestType = LLVMBuildICmp(mBuilder, LLVMIntNE, get_const(lTypeHash), lType, "testType"); static const char *lErrorString = "call to uninitialized table element"; trap_if(lFunc, lTestType, mThrowVMException, {get_string(lErrorString)}); LLVMValueRef lTablePtr = LLVMBuildPointerCast(mBuilder, lTable.mPointers, LLVMPointerType(LLVMPointerType(LLVMInt8Type(), 0), 0), "tablePtr"); LLVMValueRef lPointer = LLVMBuildInBoundsGEP(mBuilder, lTablePtr, &lCalleeIndice, 1, "gep"); LLVMValueRef lRawFuncPtr = LLVMBuildLoad(mBuilder, lPointer, "loadPtr"); LLVMValueRef lFuncPtr = LLVMBuildPointerCast(mBuilder, lRawFuncPtr, lCalleePtr, "cast"); auto lResult = LLVMBuildCall(mBuilder, lFuncPtr, lCalleeParams.data(), lCalleeParams.size(), lCalleeReturnValue ? "call" : ""); if(lCalleeReturnValue) { push(lResult); } } break; case o_select: { LLVMValueRef lCondition = pop(LLVMInt32Type()); LLVMValueRef lFalse = pop(); LLVMValueRef lTrue = pop(LLVMTypeOf(lFalse)); push(LLVMBuildSelect(mBuilder, i32_to_bool(lCondition), lTrue, lFalse, "select")); } break; case o_eqz_i32: { LLVMValueRef lZero32 = LLVMConstInt(LLVMInt32Type(), 0, true); LLVMValueRef lCond = LLVMBuildICmp(mBuilder, LLVMIntEQ, pop(LLVMInt32Type()), lZero32, "eq"); push(bool_to_i32(lCond)); } break; case o_eqz_i64: { LLVMValueRef lZero64 = LLVMConstInt(LLVMInt64Type(), 0, true); LLVMValueRef lCond = LLVMBuildICmp(mBuilder, LLVMIntEQ, pop(LLVMInt64Type()), lZero64, "eq"); push(bool_to_i32(lCond)); } break; case o_get_local: { uint32_t lLocalIndex = parse_uleb128<uint32_t>(); if (lLocalIndex >= lLocals.size()) throw invalid_exception("local index out of bounds"); push(LLVMBuildLoad(mBuilder, lLocals[lLocalIndex], "getLocal")); } break; case o_set_local: { uint32_t lLocalIndex = parse_uleb128<uint32_t>(); if (lLocalIndex >= lLocals.size()) throw invalid_exception("local index out of bounds"); auto lValueType = LLVMGetElementType(lLocalTypes[lLocalIndex]); auto lValue = LLVMBuildIntToPtr(mBuilder, pop(lValueType), lValueType, "setLocal"); LLVMBuildStore(mBuilder, lValue, lLocals[lLocalIndex]); } break; case o_tee_local: { uint32_t lLocalIndex = parse_uleb128<uint32_t>(); if (lLocalIndex >= lLocals.size()) throw invalid_exception("local index out of bounds"); auto lValueType = LLVMGetElementType(lLocalTypes[lLocalIndex]); auto lValue = LLVMBuildIntToPtr(mBuilder, top(lValueType), lValueType, "teeLocal"); LLVMBuildStore(mBuilder, lValue, lLocals[lLocalIndex]); } break; case o_get_global: { uint32_t lGlobalIndex = parse_uleb128<uint32_t>(); if (lGlobalIndex >= mGlobals.size()) throw invalid_exception("global index out of bounds"); push(LLVMBuildLoad(mBuilder, mGlobals[lGlobalIndex], "getGlobal")); } break; case o_set_global: { uint32_t lGlobalIndex = parse_uleb128<uint32_t>(); if (lGlobalIndex >= mGlobals.size()) throw invalid_exception("global index out of bounds"); auto lValueType = LLVMGetElementType(LLVMTypeOf(mGlobals[lGlobalIndex])); auto lValue = LLVMBuildIntToPtr(mBuilder, pop(lValueType), lValueType, "setGlobal"); LLVMBuildStore(mBuilder, lValue, mGlobals[lGlobalIndex]); } break; case o_memory_grow: { if (mMemoryTypes.empty()) throw invalid_exception("grow_memory without memory block"); /*uint8_t lReserved =*/ parse_uleb128<uint8_t>(); LLVMValueRef lArgs[] = { mContextRef, pop_int() }; push(LLVMBuildCall(mBuilder, mMemoryGrow, lArgs, 2, "growMem")); } break; case o_memory_size: { if (mMemoryTypes.empty()) throw invalid_exception("current_memory without memory block"); /*uint8_t lReserved =*/ parse_uleb128<uint8_t>(); push(LLVMBuildCall(mBuilder, mMemorySize, &mContextRef, 1, "curMem")); } break; #define WEMBED_CONST(OPCODE, PARSEOP) case OPCODE: { \ push(PARSEOP); \ } break; WEMBED_CONST(o_const_i32, LLVMConstInt(LLVMInt32Type(), static_cast<ull_t>(parse_sleb128<int32_t>()), true)) WEMBED_CONST(o_const_i64, LLVMConstInt(LLVMInt64Type(), static_cast<ull_t>(parse_sleb128<int64_t>()), true)) case o_const_f32: { fp_bits<float> components(parse<float>()); push(LLVMConstBitCast(LLVMConstInt(LLVMInt32Type(), static_cast<ull_t>(components.mRaw), false), LLVMFloatType())); } break; WEMBED_CONST(o_const_f64, LLVMConstReal(LLVMDoubleType(), parse<double>())) #define WEMBED_TRUNC(OPCODE, OPCONV, ITYPE, OTYPE, ICTYPE, FBITSTYPE, OMIN, OMAX) case OPCODE: { \ LLVMValueRef lValue = pop(ITYPE); \ LLVMValueRef lBitcast = LLVMBuildBitCast(mBuilder, lValue, FBITSTYPE, "bitcast"); \ LLVMValueRef lExponent = LLVMBuildAnd(mBuilder, lBitcast, get_const(fp_bits<ICTYPE>::sExponentMask), "exponent"); \ LLVMValueRef lExponentTest = LLVMBuildICmp(mBuilder, LLVMIntEQ, lExponent, get_const(fp_bits<ICTYPE>::sExponentMask), "exponentTest"); \ LLVMValueRef lMinBoundsTest = LLVMBuildFCmp(mBuilder, LLVMRealOLE, lValue, get_const(OMIN), "minBounds"); \ LLVMValueRef lMaxBoundsTest = LLVMBuildFCmp(mBuilder, LLVMRealOGE, lValue, get_const(OMAX), "maxBounds"); \ LLVMValueRef lBoundsTest = LLVMBuildOr(mBuilder, lMinBoundsTest, lMaxBoundsTest, "boundsTest"); \ LLVMValueRef lInvalid = LLVMBuildOr(mBuilder, lBoundsTest, lExponentTest, "validTruncate"); \ const char *lErrorString = "invalid truncate"; \ trap_if(lFunc, lInvalid, mThrowVMException, {get_string(lErrorString)}); \ push(OPCONV(mBuilder, lValue, OTYPE, #OPCODE)); \ } break; WEMBED_TRUNC(o_trunc_f32_si32, LLVMBuildFPToSI, LLVMFloatType(), LLVMInt32Type(), float, LLVMInt32Type(), -2147483904.0f, 2147483648.0f); WEMBED_TRUNC(o_trunc_f64_si32, LLVMBuildFPToSI, LLVMDoubleType(), LLVMInt32Type(), double, LLVMInt64Type(), -2147483649.0, 2147483648.0); WEMBED_TRUNC(o_trunc_f32_ui32, LLVMBuildFPToUI, LLVMFloatType(), LLVMInt32Type(), float, LLVMInt32Type(), -1.0f, 4294967296.0f); WEMBED_TRUNC(o_trunc_f64_ui32, LLVMBuildFPToUI, LLVMDoubleType(), LLVMInt32Type(), double, LLVMInt64Type(), -1.0, 4294967296.0); WEMBED_TRUNC(o_trunc_f32_si64, LLVMBuildFPToSI, LLVMFloatType(), LLVMInt64Type(), float, LLVMInt32Type(), -9223373136366403584.0f, 9223372036854775808.0f); WEMBED_TRUNC(o_trunc_f64_si64, LLVMBuildFPToSI, LLVMDoubleType(), LLVMInt64Type(), double, LLVMInt64Type(), -9223372036854777856.0, 9223372036854775808.0); WEMBED_TRUNC(o_trunc_f32_ui64, LLVMBuildFPToUI, LLVMFloatType(), LLVMInt64Type(), float, LLVMInt32Type(), -1.0f, 18446744073709551616.0f); WEMBED_TRUNC(o_trunc_f64_ui64, LLVMBuildFPToUI, LLVMDoubleType(), LLVMInt64Type(), double, LLVMInt64Type(), -1.0, 18446744073709551616.0); #define WEMBED_LOAD(OPCODE, TYPE, BYTES, CONVOP) case OPCODE: { \ if (mMemoryTypes.empty()) throw invalid_exception("load without memory block"); \ LLVMTypeRef lPtrType = LLVMPointerType(TYPE, 0); \ uint32_t lFlags = parse_uleb128<uint32_t>(); \ LLVMValueRef lOffset = LLVMConstInt(LLVMInt32Type(), static_cast<ull_t>(parse_uleb128<uint32_t>()), false); \ auto lTotalOffsetResult = call_mv_intrinsic<2>(mUAddWithOverflow_i32, {pop_int(), lOffset}); \ static const char *lErrorString = "load addr overflow"; \ trap_if(lFunc, lTotalOffsetResult[1], mThrowVMException, {get_string(lErrorString)}); \ LLVMValueRef lTotalOffset = lTotalOffsetResult[0]; \ LLVMValueRef lOffseted = LLVMBuildInBoundsGEP(mBuilder, mBaseMemory, &lTotalOffset, 1, "offseted"); \ LLVMValueRef lCasted = LLVMBuildPointerCast(mBuilder, lOffseted, lPtrType, "casted"); \ LLVMValueRef lLoad = LLVMBuildLoad(mBuilder, lCasted, "load"); \ uint lAlign = 1<<lFlags; \ if (lAlign > BYTES) throw invalid_exception("unnatural alignment"); \ LLVMSetAlignment(lLoad, lAlign); \ LLVMSetVolatile(lLoad, true); \ push(CONVOP); \ } break; WEMBED_LOAD(o_load_i32, LLVMInt32Type(), 4, lLoad) WEMBED_LOAD(o_load_i64, LLVMInt64Type(), 8, lLoad) WEMBED_LOAD(o_load_f32, LLVMFloatType(), 4, lLoad) WEMBED_LOAD(o_load_f64, LLVMDoubleType(), 8, lLoad) WEMBED_LOAD(o_load8_si32, LLVMInt8Type(), 1, LLVMBuildSExt(mBuilder, lLoad, LLVMInt32Type(), "sext")) WEMBED_LOAD(o_load16_si32, LLVMInt16Type(), 2, LLVMBuildSExt(mBuilder, lLoad, LLVMInt32Type(), "sext")) WEMBED_LOAD(o_load8_si64, LLVMInt8Type(), 1, LLVMBuildSExt(mBuilder, lLoad, LLVMInt64Type(), "sext")) WEMBED_LOAD(o_load16_si64, LLVMInt16Type(), 2, LLVMBuildSExt(mBuilder, lLoad, LLVMInt64Type(), "sext")) WEMBED_LOAD(o_load32_si64, LLVMInt32Type(), 4, LLVMBuildSExt(mBuilder, lLoad, LLVMInt64Type(), "sext")) WEMBED_LOAD(o_load8_ui32, LLVMInt8Type(), 1, LLVMBuildZExt(mBuilder, lLoad, LLVMInt32Type(), "zext")) WEMBED_LOAD(o_load16_ui32, LLVMInt16Type(), 2, LLVMBuildZExt(mBuilder, lLoad, LLVMInt32Type(), "zext")) WEMBED_LOAD(o_load8_ui64, LLVMInt8Type(), 1, LLVMBuildZExt(mBuilder, lLoad, LLVMInt64Type(), "zext")) WEMBED_LOAD(o_load16_ui64, LLVMInt16Type(), 2, LLVMBuildZExt(mBuilder, lLoad, LLVMInt64Type(), "zext")) WEMBED_LOAD(o_load32_ui64, LLVMInt32Type(), 4, LLVMBuildZExt(mBuilder, lLoad, LLVMInt64Type(), "zext")) #define WEMBED_STORE(OPCODE, ITYPE, BYTES, OTYPE, CONVOP) case OPCODE: { \ if (mMemoryTypes.empty()) throw invalid_exception("store without memory block"); \ LLVMTypeRef lPtrType = LLVMPointerType(OTYPE, 0); \ uint32_t lFlags = parse_uleb128<uint32_t>(); \ LLVMValueRef lOffset = LLVMConstInt(LLVMInt32Type(), static_cast<ull_t>(parse_uleb128<uint32_t>()), false); \ LLVMValueRef lValue = pop(ITYPE); \ auto lTotalOffsetResult = call_mv_intrinsic<2>(mUAddWithOverflow_i32, {pop_int(), lOffset}); \ static const char *lErrorString = "store addr overflow"; \ trap_if(lFunc, lTotalOffsetResult[1], mThrowVMException, {get_string(lErrorString)}); \ LLVMValueRef lTotalOffset = lTotalOffsetResult[0]; \ LLVMValueRef lOffseted = LLVMBuildInBoundsGEP(mBuilder, mBaseMemory, &lTotalOffset, 1, "offseted"); \ LLVMValueRef lCasted = LLVMBuildPointerCast(mBuilder, lOffseted, lPtrType, "casted"); \ LLVMValueRef lStore = LLVMBuildStore(mBuilder, CONVOP, lCasted); \ uint lAlign = 1<<lFlags; \ if (lAlign > BYTES) throw invalid_exception("unnatural alignment"); \ LLVMSetAlignment(lStore, lAlign); \ LLVMSetVolatile(lStore, true); \ } break; WEMBED_STORE(o_store_i32, LLVMInt32Type(), 4, LLVMInt32Type(), lValue) WEMBED_STORE(o_store_i64, LLVMInt64Type(), 8, LLVMInt64Type(), lValue) WEMBED_STORE(o_store_f32, LLVMFloatType(), 4, LLVMFloatType(), lValue) WEMBED_STORE(o_store_f64, LLVMDoubleType(), 8, LLVMDoubleType(), lValue) WEMBED_STORE(o_store8_i32, LLVMInt32Type(), 1, LLVMInt8Type(), LLVMBuildTrunc(mBuilder, lValue, LLVMInt8Type(), "trunc")) WEMBED_STORE(o_store16_i32, LLVMInt32Type(), 2, LLVMInt16Type(), LLVMBuildTrunc(mBuilder, lValue, LLVMInt16Type(), "trunc")) WEMBED_STORE(o_store8_i64, LLVMInt64Type(), 1, LLVMInt8Type(), LLVMBuildTrunc(mBuilder, lValue, LLVMInt8Type(), "trunc")) WEMBED_STORE(o_store16_i64, LLVMInt64Type(), 2, LLVMInt16Type(), LLVMBuildTrunc(mBuilder, lValue, LLVMInt16Type(), "trunc")) WEMBED_STORE(o_store32_i64, LLVMInt64Type(), 4, LLVMInt32Type(), LLVMBuildTrunc(mBuilder, lValue, LLVMInt32Type(), "trunc")) #define WEMBED_ICMP(OPCODE, OPCOMP) case OPCODE##i32: { \ LLVMValueRef rhs = pop(); \ LLVMValueRef lhs = pop(LLVMTypeOf(rhs)); \ push(bool_to_i32(LLVMBuildICmp(mBuilder, OPCOMP, lhs, rhs, #OPCOMP))); \ } break; \ case OPCODE##i64: { \ LLVMValueRef rhs = pop(); \ LLVMValueRef lhs = pop(LLVMTypeOf(rhs)); \ push(bool_to_i32(LLVMBuildICmp(mBuilder, OPCOMP, lhs, rhs, #OPCOMP))); \ } break; WEMBED_ICMP(o_eq_, LLVMIntEQ) WEMBED_ICMP(o_ne_, LLVMIntNE) WEMBED_ICMP(o_lt_s, LLVMIntSLT) WEMBED_ICMP(o_lt_u, LLVMIntULT) WEMBED_ICMP(o_le_s, LLVMIntSLE) WEMBED_ICMP(o_le_u, LLVMIntULE) WEMBED_ICMP(o_gt_s, LLVMIntSGT) WEMBED_ICMP(o_gt_u, LLVMIntUGT) WEMBED_ICMP(o_ge_s, LLVMIntSGE) WEMBED_ICMP(o_ge_u, LLVMIntUGE) #define WEMBED_FCMP(OPCODE, OPCOMP) case OPCODE##f32: { \ LLVMValueRef rhs = pop(); \ LLVMValueRef lhs = pop(LLVMTypeOf(rhs)); \ push(bool_to_i32(LLVMBuildFCmp(mBuilder, OPCOMP, lhs, rhs, #OPCOMP))); \ } break; \ case OPCODE##f64: { \ LLVMValueRef rhs = pop(); \ LLVMValueRef lhs = pop(LLVMTypeOf(rhs)); \ push(bool_to_i32(LLVMBuildFCmp(mBuilder, OPCOMP, lhs, rhs, #OPCOMP))); \ } break; WEMBED_FCMP(o_eq_, LLVMRealOEQ) WEMBED_FCMP(o_ne_, LLVMRealUNE) WEMBED_FCMP(o_lt_, LLVMRealOLT) WEMBED_FCMP(o_le_, LLVMRealOLE) WEMBED_FCMP(o_gt_, LLVMRealOGT) WEMBED_FCMP(o_ge_, LLVMRealOGE) #define WEMBED_BINARY(OPCODE, INSTR) case OPCODE: { \ LLVMValueRef rhs = pop(); \ LLVMValueRef lhs = pop(LLVMTypeOf(rhs)); \ push(INSTR); \ } break; #define WEMBED_BINARY_MULTI(OPCODE, INSTR) WEMBED_BINARY(OPCODE##32, INSTR) WEMBED_BINARY(OPCODE##64, INSTR) #define WEMBED_BINARY_LLVM(OPCODE, INSTR) WEMBED_BINARY_MULTI(OPCODE, INSTR(mBuilder, lhs, rhs, #INSTR)) WEMBED_BINARY_LLVM(o_add_i, LLVMBuildAdd) WEMBED_BINARY_LLVM(o_sub_i, LLVMBuildSub) WEMBED_BINARY_LLVM(o_mul_i, LLVMBuildMul) WEMBED_BINARY(o_div_ui32, emit_udiv(LLVMInt32Type(), lFunc, lhs, rhs)) WEMBED_BINARY(o_div_ui64, emit_udiv(LLVMInt64Type(), lFunc, lhs, rhs)) WEMBED_BINARY(o_div_si32, emit_sdiv(LLVMInt32Type(), lFunc, lhs, rhs)) WEMBED_BINARY(o_div_si64, emit_sdiv(LLVMInt64Type(), lFunc, lhs, rhs)) WEMBED_BINARY(o_rem_ui32, emit_urem(LLVMInt32Type(), lFunc, lhs, rhs)) WEMBED_BINARY(o_rem_ui64, emit_urem(LLVMInt64Type(), lFunc, lhs, rhs)) WEMBED_BINARY(o_rem_si32, emit_srem(LLVMInt32Type(), lFunc, lhs, rhs)) WEMBED_BINARY(o_rem_si64, emit_srem(LLVMInt64Type(), lFunc, lhs, rhs)) WEMBED_BINARY_MULTI(o_add_f, clear_nan(LLVMBuildFAdd(mBuilder, lhs, rhs, "fadd"))) WEMBED_BINARY_MULTI(o_sub_f, clear_nan(LLVMBuildFSub(mBuilder, lhs, rhs, "fsub"))) WEMBED_BINARY_MULTI(o_mul_f, clear_nan(LLVMBuildFMul(mBuilder, lhs, rhs, "fadd"))) WEMBED_BINARY_MULTI(o_div_f, clear_nan(LLVMBuildFDiv(mBuilder, lhs, rhs, "fsub"))) WEMBED_BINARY_LLVM(o_and_i, LLVMBuildAnd) WEMBED_BINARY_LLVM(o_or_i, LLVMBuildOr) WEMBED_BINARY_LLVM(o_xor_i, LLVMBuildXor) WEMBED_BINARY(o_rotl_i32, emit_rotl(LLVMInt32Type(), lhs, rhs)) WEMBED_BINARY(o_rotl_i64, emit_rotl(LLVMInt64Type(), lhs, rhs)) WEMBED_BINARY(o_rotr_i32, emit_rotr(LLVMInt32Type(), lhs, rhs)) WEMBED_BINARY(o_rotr_i64, emit_rotr(LLVMInt64Type(), lhs, rhs)) WEMBED_BINARY(o_shl_i32, LLVMBuildShl(mBuilder, lhs, emit_shift_mask(LLVMInt32Type(), rhs), "shl")) WEMBED_BINARY(o_shl_i64, LLVMBuildShl(mBuilder, lhs, emit_shift_mask(LLVMInt64Type(), rhs), "shl")) WEMBED_BINARY(o_shr_si32, LLVMBuildAShr(mBuilder, lhs, emit_shift_mask(LLVMInt32Type(), rhs), "shrs")) WEMBED_BINARY(o_shr_si64, LLVMBuildAShr(mBuilder, lhs, emit_shift_mask(LLVMInt64Type(), rhs), "shrs")) WEMBED_BINARY(o_shr_ui32, LLVMBuildLShr(mBuilder, lhs, emit_shift_mask(LLVMInt32Type(), rhs), "shru")) WEMBED_BINARY(o_shr_ui64, LLVMBuildLShr(mBuilder, lhs, emit_shift_mask(LLVMInt64Type(), rhs), "shru")) #define WEMBED_INTRINSIC(OPCODE, INTRINSIC, ...) case OPCODE: { \ push(call_intrinsic(INTRINSIC, {__VA_ARGS__})); \ } break; WEMBED_INTRINSIC(o_ctz_i32, mCttz_i32, pop(LLVMInt32Type()), get_const(false)) WEMBED_INTRINSIC(o_ctz_i64, mCttz_i64, pop(LLVMInt64Type()), get_const(false)) WEMBED_INTRINSIC(o_clz_i32, mCtlz_i32, pop(LLVMInt32Type()), get_const(false)) WEMBED_INTRINSIC(o_clz_i64, mCtlz_i64, pop(LLVMInt64Type()), get_const(false)) WEMBED_INTRINSIC(o_popcnt_i32, mCtpop_i32, pop(LLVMInt32Type())) WEMBED_INTRINSIC(o_popcnt_i64, mCtpop_i64, pop(LLVMInt64Type())) WEMBED_INTRINSIC(o_sqrt_f32, mSqrt_f32, pop(LLVMFloatType())) WEMBED_INTRINSIC(o_sqrt_f64, mSqrt_f64, pop(LLVMDoubleType())) WEMBED_INTRINSIC(o_abs_f32, mAbs_f32, pop(LLVMFloatType())) WEMBED_INTRINSIC(o_abs_f64, mAbs_f64, pop(LLVMDoubleType())) case o_ceil_f32: { push(emit_quiet_nan_or_intrinsic(pop(LLVMFloatType()), mCeil_f32, mCeil_f64)); } break; case o_ceil_f64: { push(emit_quiet_nan_or_intrinsic(pop(LLVMDoubleType()), mCeil_f32, mCeil_f64)); } break; case o_floor_f32: { push(emit_quiet_nan_or_intrinsic(pop(LLVMFloatType()), mFloor_f32, mFloor_f64)); } break; case o_floor_f64: { push(emit_quiet_nan_or_intrinsic(pop(LLVMDoubleType()), mFloor_f32, mFloor_f64)); } break; case o_trunc_f32: { push(emit_quiet_nan_or_intrinsic(pop(LLVMFloatType()), mTrunc_f32, mTrunc_f64)); } break; case o_trunc_f64: { push(emit_quiet_nan_or_intrinsic(pop(LLVMDoubleType()), mTrunc_f32, mTrunc_f64)); } break; case o_nearest_f32: { push(emit_quiet_nan_or_intrinsic(pop(LLVMFloatType()), mNearest_f32, mNearest_f64)); } break; case o_nearest_f64: { push(emit_quiet_nan_or_intrinsic(pop(LLVMDoubleType()), mNearest_f32, mNearest_f64)); } break; #define WEMBED_INTRINSIC_BINARY(OPCODE, INTRINSIC, ...) WEMBED_BINARY(OPCODE, call_intrinsic(INTRINSIC, {lhs, rhs, __VA_ARGS__})); #define WEMBED_INTRINSIC_BINARY_MULTI(OPCODE, INTRINSIC, ...) WEMBED_INTRINSIC_BINARY(OPCODE##32, INTRINSIC##32, __VA_ARGS__) \ WEMBED_INTRINSIC_BINARY(OPCODE##64, INTRINSIC##64, __VA_ARGS__) case o_min_f32: { LLVMValueRef rhs = pop(LLVMFloatType()); LLVMValueRef lhs = pop(LLVMFloatType()); push(emit_min(lhs, rhs)); } break; case o_min_f64: { LLVMValueRef rhs = pop(LLVMDoubleType()); LLVMValueRef lhs = pop(LLVMDoubleType()); push(emit_min(lhs, rhs)); } break; case o_max_f32: { LLVMValueRef rhs = pop(LLVMFloatType()); LLVMValueRef lhs = pop(LLVMFloatType()); push(emit_max(lhs, rhs)); } break; case o_max_f64: { LLVMValueRef rhs = pop(LLVMDoubleType()); LLVMValueRef lhs = pop(LLVMDoubleType()); push(emit_max(lhs, rhs)); } break; WEMBED_INTRINSIC_BINARY_MULTI(o_copysign_f, mCopysign_f) case o_neg_f32: { push(LLVMBuildFNeg(mBuilder, pop(LLVMFloatType()), "neg")); } break; case o_neg_f64: { push(LLVMBuildFNeg(mBuilder, pop(LLVMDoubleType()), "neg")); } break; #define WEMBED_CAST(OPCODE, INSTR, ITYPE, OTYPE) case OPCODE: { \ push(INSTR(mBuilder, pop(ITYPE), OTYPE, #INSTR)); \ } break; WEMBED_CAST(o_wrap_i64, LLVMBuildTrunc, LLVMInt64Type(), LLVMInt32Type()) WEMBED_CAST(o_extend_si32, LLVMBuildSExt, LLVMInt32Type(), LLVMInt64Type()) WEMBED_CAST(o_extend_ui32, LLVMBuildZExt, LLVMInt32Type(), LLVMInt64Type()) #define WEMBED_SIGN_EXT(OPCODE, INSTR, ITYPE, OTYPE) case OPCODE: { \ push(INSTR(mBuilder, LLVMBuildTrunc(mBuilder, pop(), ITYPE, #INSTR"-signext"), OTYPE, #INSTR)); \ } break; WEMBED_SIGN_EXT(o_extend_i32_s8, LLVMBuildSExt, LLVMInt8Type(), LLVMInt32Type()) WEMBED_SIGN_EXT(o_extend_i32_s16, LLVMBuildSExt, LLVMInt16Type(), LLVMInt32Type()) WEMBED_SIGN_EXT(o_extend_i64_s8, LLVMBuildSExt, LLVMInt8Type(), LLVMInt64Type()) WEMBED_SIGN_EXT(o_extend_i64_s16, LLVMBuildSExt, LLVMInt16Type(), LLVMInt64Type()) WEMBED_SIGN_EXT(o_extend_i64_s32, LLVMBuildSExt, LLVMInt32Type(), LLVMInt64Type()) case o_demote_f64: { push(clear_nan(LLVMBuildFPTrunc(mBuilder, pop(LLVMDoubleType()), LLVMFloatType(), "demote"))); } break; case o_promote_f32: { push(clear_nan(LLVMBuildFPExt(mBuilder, pop(LLVMFloatType()), LLVMDoubleType(), "promote"))); } break; WEMBED_CAST(o_convert_f32_si32, LLVMBuildSIToFP, LLVMInt32Type(), LLVMFloatType()) WEMBED_CAST(o_convert_f32_si64, LLVMBuildSIToFP, LLVMInt64Type(), LLVMFloatType()) WEMBED_CAST(o_convert_f64_si32, LLVMBuildSIToFP, LLVMInt32Type(), LLVMDoubleType()) WEMBED_CAST(o_convert_f64_si64, LLVMBuildSIToFP, LLVMInt64Type(), LLVMDoubleType()) WEMBED_CAST(o_convert_f32_ui32, LLVMBuildUIToFP, LLVMInt32Type(), LLVMFloatType()) WEMBED_CAST(o_convert_f32_ui64, LLVMBuildUIToFP, LLVMInt64Type(), LLVMFloatType()) WEMBED_CAST(o_convert_f64_ui32, LLVMBuildUIToFP, LLVMInt32Type(), LLVMDoubleType()) WEMBED_CAST(o_convert_f64_ui64, LLVMBuildUIToFP, LLVMInt64Type(), LLVMDoubleType()) WEMBED_CAST(o_reinterpret_i32_f32, LLVMBuildBitCast, LLVMFloatType(), LLVMInt32Type()) WEMBED_CAST(o_reinterpret_i64_f64, LLVMBuildBitCast, LLVMDoubleType(), LLVMInt64Type()) WEMBED_CAST(o_reinterpret_f32_i32, LLVMBuildBitCast, LLVMInt32Type(), LLVMFloatType()) WEMBED_CAST(o_reinterpret_f64_i64, LLVMBuildBitCast, LLVMInt64Type(), LLVMDoubleType()) case o_prefix_numeric: { switch(*mCurrent++) { #define WEMBED_SAT_TRUNC(OPCODE, OPCONV, ITYPE, OTYPE, ICTYPE, OCTYPE, FBITSTYPE, OMIN, OMAX) case OPCODE: { \ LLVMValueRef lValue = pop(ITYPE); \ LLVMValueRef lBitcast = LLVMBuildBitCast(mBuilder, lValue, FBITSTYPE, "bitcast"); \ LLVMValueRef lExponent = LLVMBuildAnd(mBuilder, lBitcast, get_const(fp_bits<ICTYPE>::sExponentMask), "exponent"); \ LLVMValueRef lExponentTest = LLVMBuildICmp(mBuilder, LLVMIntEQ, lExponent, get_const(fp_bits<ICTYPE>::sExponentMask), "exponentTest"); \ LLVMValueRef lMantissa = LLVMBuildAnd(mBuilder, lBitcast, get_const(fp_bits<ICTYPE>::sMantissaMask), "mantissa"); \ LLVMValueRef lMantissaTest = LLVMBuildICmp(mBuilder, LLVMIntNE, lMantissa, get_zero(FBITSTYPE), "mantissaTest"); \ LLVMValueRef lNan = LLVMBuildAnd(mBuilder, lExponentTest, lMantissaTest, "isNan"); \ LLVMValueRef lMinBoundsTest = LLVMBuildFCmp(mBuilder, LLVMRealOLE, lValue, get_const(OMIN), "minBounds"); \ LLVMValueRef lMaxBoundsTest = LLVMBuildFCmp(mBuilder, LLVMRealOGE, lValue, get_const(OMAX), "maxBounds"); \ LLVMValueRef lConverted = OPCONV(mBuilder, lValue, OTYPE, #OPCODE); \ LLVMValueRef lValueOrMin = LLVMBuildSelect(mBuilder, lMinBoundsTest, get_const(std::numeric_limits<OCTYPE>::min()), lConverted, "valueOrMin"); \ LLVMValueRef lValueOrMax = LLVMBuildSelect(mBuilder, lMaxBoundsTest, get_const(std::numeric_limits<OCTYPE>::max()), lValueOrMin, "valueOrMax"); \ LLVMValueRef lValueOrZero = LLVMBuildSelect(mBuilder, lNan, get_zero(OTYPE), lValueOrMax, "valueOrZero"); \ push(lValueOrZero); \ } break; WEMBED_SAT_TRUNC(o_trunc_sat_f32_si32, LLVMBuildFPToSI, LLVMFloatType(), LLVMInt32Type(), float, int32_t, LLVMInt32Type(), -2147483904.0f, 2147483648.0f); WEMBED_SAT_TRUNC(o_trunc_sat_f64_si32, LLVMBuildFPToSI, LLVMDoubleType(), LLVMInt32Type(), double, int32_t, LLVMInt64Type(), -2147483649.0, 2147483648.0); WEMBED_SAT_TRUNC(o_trunc_sat_f32_ui32, LLVMBuildFPToUI, LLVMFloatType(), LLVMInt32Type(), float, uint32_t, LLVMInt32Type(), -1.0f, 4294967296.0f); WEMBED_SAT_TRUNC(o_trunc_sat_f64_ui32, LLVMBuildFPToUI, LLVMDoubleType(), LLVMInt32Type(), double, uint32_t, LLVMInt64Type(), -1.0, 4294967296.0); WEMBED_SAT_TRUNC(o_trunc_sat_f32_si64, LLVMBuildFPToSI, LLVMFloatType(), LLVMInt64Type(), float, int64_t, LLVMInt32Type(), -9223373136366403584.0f, 9223372036854775808.0f); WEMBED_SAT_TRUNC(o_trunc_sat_f64_si64, LLVMBuildFPToSI, LLVMDoubleType(), LLVMInt64Type(), double, int64_t, LLVMInt64Type(), -9223372036854777856.0, 9223372036854775808.0); WEMBED_SAT_TRUNC(o_trunc_sat_f32_ui64, LLVMBuildFPToUI, LLVMFloatType(), LLVMInt64Type(), float, uint64_t, LLVMInt32Type(), -1.0f, 18446744073709551616.0f); WEMBED_SAT_TRUNC(o_trunc_sat_f64_ui64, LLVMBuildFPToUI, LLVMDoubleType(), LLVMInt64Type(), double, uint64_t, LLVMInt64Type(), -1.0, 18446744073709551616.0); default: throw malformed_exception("unknown numeric instruction"); } } break; default: throw malformed_exception("unknown instruction"); } #if defined(WEMBED_VERBOSE) && 0 std::cout << "Step: " << LLVMPrintValueToString(lFunc) << std::endl; std::cout << "Eval stack:" << mEvalStack.size() << std::endl; for (size_t i = 0; i < mEvalStack.size(); i++) { std::cout << '\t' << i << ": "; if (mEvalStack[i] == nullptr) std::cout << "null"; else { std::cout << LLVMPrintValueToString(mEvalStack[i]) << ", " << LLVMPrintTypeToString(LLVMTypeOf(mEvalStack[i])); } std::cout << std::endl; } std::cout << "Control flow stack:" << mCFEntries.size() << std::endl; for (size_t i = 0; i < mCFEntries.size(); i++) { std::cout << '\t' << i; std::cout << ": " << LLVMGetBasicBlockName(mCFEntries[i].mEnd); std::cout << ", " << mCFEntries[i].mReachable << ", "; std::cout << LLVMPrintTypeToString(mCFEntries[i].mSignature); std::cout << std::endl; } std::cout << "Block stack:" << mBlockEntries.size() << std::endl; for (size_t i = 0; i < mBlockEntries.size(); i++) { std::cout << '\t' << i << ": "; std::cout << LLVMGetBasicBlockName(mBlockEntries[i].mBlock) << ", "; std::cout << LLVMPrintTypeToString(mBlockEntries[i].mSignature); std::cout << std::endl; } #endif } assert(mCurrent == lEndPos); assert(LLVMGetInsertBlock(mBuilder) == lFuncEnd); if (lReturnType != LLVMVoidType()) LLVMBuildRet(mBuilder, pop(lReturnType)); else LLVMBuildRetVoid(mBuilder); #if defined(WEMBED_VERBOSE) && 0 std::cout << "Done: " << LLVMPrintValueToString(lFunc) << std::endl; #endif } profile_step(" module/code"); } void addInitialAliasAnalysisPasses(LLVMPassManagerRef pPass) { LLVMAddTypeBasedAliasAnalysisPass(pPass); LLVMAddScopedNoAliasAAPass(pPass); } void addInstructionCombiningPass(LLVMPassManagerRef pPass) { LLVMAddInstructionCombiningPass(pPass); } void addFunctionSimplificationPasses(uint8_t pOptLevel, LLVMPassManagerRef pPass) { LLVMAddScalarReplAggregatesPassSSA(pPass); //createSpeculativeExecutionIfHasBranchDivergencePass LLVMAddJumpThreadingPass(pPass); LLVMAddCorrelatedValuePropagationPass(pPass); LLVMAddCFGSimplificationPass(pPass); if (pOptLevel > 2) LLVMAddAggressiveInstCombinerPass(pPass); addInstructionCombiningPass(pPass); //createPGOMemOPSizeOptLegacyPass LLVMAddTailCallEliminationPass(pPass); LLVMAddCFGSimplificationPass(pPass); LLVMAddReassociatePass(pPass); LLVMAddLoopRotatePass(pPass); LLVMAddLICMPass(pPass); LLVMAddLoopUnswitchPass(pPass); LLVMAddCFGSimplificationPass(pPass); addInstructionCombiningPass(pPass); LLVMAddIndVarSimplifyPass(pPass); LLVMAddLoopIdiomPass(pPass); LLVMAddLoopDeletionPass(pPass); //createSimpleLoopUnrollPass if (pOptLevel > 1) { LLVMAddMergedLoadStoreMotionPass(pPass); LLVMAddNewGVNPass(pPass); } LLVMAddMemCpyOptPass(pPass); LLVMAddSCCPPass(pPass); LLVMAddBitTrackingDCEPass(pPass); addInstructionCombiningPass(pPass); LLVMAddJumpThreadingPass(pPass); LLVMAddCorrelatedValuePropagationPass(pPass); LLVMAddDeadStoreEliminationPass(pPass); LLVMAddLICMPass(pPass); LLVMAddLoopRerollPass(pPass); LLVMAddAggressiveDCEPass(pPass); LLVMAddCFGSimplificationPass(pPass); addInstructionCombiningPass(pPass); } void addLTOOptimizationPasses(uint8_t pOptLevel, LLVMPassManagerRef pPass) { LLVMAddGlobalDCEPass(pPass); addInitialAliasAnalysisPasses(pPass); //createForceFunctionAttrsLegacyPass //createInferFunctionAttrsLegacyPass if (pOptLevel > 1) { //createCallSiteSplittingPass //createPGOIndirectCallPromotionLegacyPass LLVMAddIPSCCPPass(pPass); LLVMAddCalledValuePropagationPass(pPass); } //LLVMAddFunctionAttrsPass(pPass); Makes call.wast fail //createReversePostOrderFunctionAttrsPass //createGlobalSplitPass //createWholeProgramDevirtPass if (pOptLevel == 1) return; LLVMAddGlobalOptimizerPass(pPass); LLVMAddPromoteMemoryToRegisterPass(pPass); LLVMAddConstantMergePass(pPass); LLVMAddDeadArgEliminationPass(pPass); if (pOptLevel > 2) LLVMAddAggressiveInstCombinerPass(pPass); addInstructionCombiningPass(pPass); LLVMAddFunctionInliningPass(pPass); LLVMAddPruneEHPass(pPass); LLVMAddGlobalOptimizerPass(pPass); LLVMAddGlobalDCEPass(pPass); LLVMAddArgumentPromotionPass(pPass); addInstructionCombiningPass(pPass); LLVMAddJumpThreadingPass(pPass); LLVMAddScalarReplAggregatesPass(pPass); //LLVMAddFunctionAttrsPass(pPass); Makes call.wast fail //createGlobalsAAWrapperPass LLVMAddLICMPass(pPass); LLVMAddMergedLoadStoreMotionPass(pPass); LLVMAddNewGVNPass(pPass); LLVMAddMemCpyOptPass(pPass); LLVMAddDeadStoreEliminationPass(pPass); LLVMAddIndVarSimplifyPass(pPass); LLVMAddLoopDeletionPass(pPass); //createLoopInterchangePass //createSimpleLoopUnrollPass LLVMAddLoopVectorizePass(pPass); LLVMAddLoopUnrollPass(pPass); addInstructionCombiningPass(pPass); LLVMAddCFGSimplificationPass(pPass); LLVMAddSCCPPass(pPass); addInstructionCombiningPass(pPass); LLVMAddBitTrackingDCEPass(pPass); LLVMAddAlignmentFromAssumptionsPass(pPass); addInstructionCombiningPass(pPass); LLVMAddJumpThreadingPass(pPass); } void addLateLTOOptimizationPasses(uint8_t pOptLevel, LLVMPassManagerRef pPass) { LLVMAddCFGSimplificationPass(pPass); //createEliminateAvailableExternallyPass LLVMAddGlobalDCEPass(pPass); } void module::optimize(uint8_t pOptLevel) { if (pOptLevel == 0) return; mOptLevel = pOptLevel; LLVMPassManagerRef lPass = LLVMCreatePassManager(); addLTOOptimizationPasses(pOptLevel, lPass); addLateLTOOptimizationPasses(pOptLevel, lPass); LLVMRunPassManager(lPass, mModule); LLVMDisposePassManager(lPass); #if defined(WEMBED_VERBOSE) && 0 dump_ll(std::cout); #endif } } // namespace wembed
47.514421
186
0.651817
[ "vector" ]
db4dafccc0876421b7f44def950287c53831c58b
44,961
cpp
C++
third_party/skia_m84/third_party/externals/angle2/src/tests/gl_tests/ProgramInterfaceTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
third_party/skia_m84/third_party/externals/angle2/src/tests/gl_tests/ProgramInterfaceTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
third_party/skia_m84/third_party/externals/angle2/src/tests/gl_tests/ProgramInterfaceTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
null
null
null
// // Copyright 2017 The ANGLE 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. // // ProgramInterfaceTest: Tests of program interfaces. #include "common/string_utils.h" #include "test_utils/ANGLETest.h" #include "test_utils/gl_raii.h" using namespace angle; namespace { class ProgramInterfaceTestES31 : public ANGLETest { protected: ProgramInterfaceTestES31() { setWindowWidth(64); setWindowHeight(64); setConfigRedBits(8); setConfigGreenBits(8); setConfigBlueBits(8); setConfigAlphaBits(8); } }; // Tests glGetProgramResourceIndex. TEST_P(ProgramInterfaceTestES31, GetResourceIndex) { constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "uniform vec4 color;\n" "out vec4 oColor;\n" "void main()\n" "{\n" " oColor = color;\n" "}"; ANGLE_GL_PROGRAM(program, essl31_shaders::vs::Simple(), kFS); GLuint index = glGetProgramResourceIndex(program, GL_PROGRAM_INPUT, essl31_shaders::PositionAttrib()); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); index = glGetProgramResourceIndex(program, GL_PROGRAM_INPUT, "missing"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(GL_INVALID_INDEX, index); index = glGetProgramResourceIndex(program, GL_PROGRAM_OUTPUT, "oColor"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); index = glGetProgramResourceIndex(program, GL_PROGRAM_OUTPUT, "missing"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(GL_INVALID_INDEX, index); index = glGetProgramResourceIndex(program, GL_ATOMIC_COUNTER_BUFFER, "missing"); EXPECT_GL_ERROR(GL_INVALID_ENUM); } // Tests glGetProgramResourceName. TEST_P(ProgramInterfaceTestES31, GetResourceName) { constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "uniform vec4 color;\n" "out vec4 oColor[4];\n" "void main()\n" "{\n" " oColor[0] = color;\n" "}"; ANGLE_GL_PROGRAM(program, essl31_shaders::vs::Simple(), kFS); GLuint index = glGetProgramResourceIndex(program, GL_PROGRAM_INPUT, essl31_shaders::PositionAttrib()); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLchar name[64]; GLsizei length; glGetProgramResourceName(program, GL_PROGRAM_INPUT, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(static_cast<int>(strlen(essl31_shaders::PositionAttrib())), length); EXPECT_EQ(essl31_shaders::PositionAttrib(), std::string(name)); glGetProgramResourceName(program, GL_PROGRAM_INPUT, index, 4, &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(3, length); EXPECT_TRUE(angle::BeginsWith(essl31_shaders::PositionAttrib(), name)); glGetProgramResourceName(program, GL_PROGRAM_INPUT, index, -1, &length, name); EXPECT_GL_ERROR(GL_INVALID_VALUE); glGetProgramResourceName(program, GL_PROGRAM_INPUT, GL_INVALID_INDEX, sizeof(name), &length, name); EXPECT_GL_ERROR(GL_INVALID_VALUE); index = glGetProgramResourceIndex(program, GL_PROGRAM_OUTPUT, "oColor"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); glGetProgramResourceName(program, GL_PROGRAM_OUTPUT, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(9, length); EXPECT_EQ("oColor[0]", std::string(name)); glGetProgramResourceName(program, GL_PROGRAM_OUTPUT, index, 8, &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(7, length); EXPECT_EQ("oColor[", std::string(name)); } // Tests glGetProgramResourceLocation. TEST_P(ProgramInterfaceTestES31, GetResourceLocation) { // http://anglebug.com/4092 ANGLE_SKIP_TEST_IF(isSwiftshader()); constexpr char kVS[] = "#version 310 es\n" "precision highp float;\n" "layout(location = 3) in highp vec4 position;\n" "in highp vec4 noLocationSpecified;\n" "void main()\n" "{\n" " gl_Position = position;\n" "}"; constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "uniform vec4 color;\n" "layout(location = 2) out vec4 oColor[4];\n" "void main()\n" "{\n" " oColor[0] = color;\n" "}"; ANGLE_GL_PROGRAM(program, kVS, kFS); GLenum invalidInterfaces[] = {GL_UNIFORM_BLOCK, GL_TRANSFORM_FEEDBACK_VARYING, GL_BUFFER_VARIABLE, GL_SHADER_STORAGE_BLOCK, GL_ATOMIC_COUNTER_BUFFER}; GLint location; for (auto &invalidInterface : invalidInterfaces) { location = glGetProgramResourceLocation(program, invalidInterface, "any"); EXPECT_GL_ERROR(GL_INVALID_ENUM); EXPECT_EQ(-1, location); } location = glGetProgramResourceLocation(program, GL_PROGRAM_INPUT, "position"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(3, location); location = glGetProgramResourceLocation(program, GL_PROGRAM_INPUT, "noLocationSpecified"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(-1, location); location = glGetProgramResourceLocation(program, GL_PROGRAM_INPUT, "missing"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(-1, location); location = glGetProgramResourceLocation(program, GL_PROGRAM_OUTPUT, "oColor"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(2, location); location = glGetProgramResourceLocation(program, GL_PROGRAM_OUTPUT, "oColor[0]"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(2, location); location = glGetProgramResourceLocation(program, GL_PROGRAM_OUTPUT, "oColor[3]"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(5, location); } // Tests glGetProgramResource. TEST_P(ProgramInterfaceTestES31, GetResource) { // http://anglebug.com/4092 ANGLE_SKIP_TEST_IF(isSwiftshader()); constexpr char kVS[] = "#version 310 es\n" "precision highp float;\n" "layout(location = 3) in highp vec4 position;\n" "void main()\n" "{\n" " gl_Position = position;\n" "}"; constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "uniform vec4 color;\n" "layout(location = 2) out vec4 oColor[4];\n" "void main()\n" "{\n" " oColor[0] = color;\n" "}"; ANGLE_GL_PROGRAM(program, kVS, kFS); GLuint index = glGetProgramResourceIndex(program, GL_PROGRAM_INPUT, "position"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLenum props[] = {GL_TYPE, GL_ARRAY_SIZE, GL_LOCATION, GL_NAME_LENGTH, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); GLint params[ArraySize(props)]; GLsizei length; glGetProgramResourceiv(program, GL_PROGRAM_INPUT, index, propCount, props, propCount, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(GL_FLOAT_VEC4, params[0]); // type EXPECT_EQ(1, params[1]); // array_size EXPECT_EQ(3, params[2]); // location EXPECT_EQ(9, params[3]); // name_length EXPECT_EQ(1, params[4]); // referenced_by_vertex_shader EXPECT_EQ(0, params[5]); // referenced_by_fragment_shader EXPECT_EQ(0, params[6]); // referenced_by_compute_shader index = glGetProgramResourceIndex(program, GL_PROGRAM_OUTPUT, "oColor[0]"); EXPECT_GL_NO_ERROR(); EXPECT_NE(index, GL_INVALID_INDEX); // bufSize is smaller than propCount. glGetProgramResourceiv(program, GL_PROGRAM_OUTPUT, index, propCount, props, propCount - 1, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount - 1, length); EXPECT_EQ(GL_FLOAT_VEC4, params[0]); // type EXPECT_EQ(4, params[1]); // array_size EXPECT_EQ(2, params[2]); // location EXPECT_EQ(10, params[3]); // name_length EXPECT_EQ(0, params[4]); // referenced_by_vertex_shader EXPECT_EQ(1, params[5]); // referenced_by_fragment_shader GLenum invalidOutputProp = GL_OFFSET; glGetProgramResourceiv(program, GL_PROGRAM_OUTPUT, index, 1, &invalidOutputProp, 1, &length, params); EXPECT_GL_ERROR(GL_INVALID_OPERATION); } // Tests glGetProgramInterfaceiv. TEST_P(ProgramInterfaceTestES31, GetProgramInterface) { // TODO(jiajia.qin@intel.com): Don't skip this test once SSBO are supported on render pipeline. // http://anglebug.com/1951 ANGLE_SKIP_TEST_IF(IsD3D11()); constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "uniform vec4 color;\n" "out vec4 oColor;\n" "uniform ub {\n" " vec4 mem0;\n" " vec4 mem1;\n" "} instance;\n" "layout(std430) buffer shaderStorageBlock1 {\n" " vec3 target;\n" "};\n" "layout(std430) buffer shaderStorageBlock2 {\n" " vec3 target;\n" "} blockInstance2[1];\n" "void main()\n" "{\n" " oColor = color;\n" " target = vec3(0, 0, 0);\n" " blockInstance2[0].target = vec3(1, 1, 1);\n" "}"; ANGLE_GL_PROGRAM(program, essl31_shaders::vs::Simple(), kFS); GLint num; glGetProgramInterfaceiv(program, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(1, num); glGetProgramInterfaceiv(program, GL_PROGRAM_INPUT, GL_MAX_NAME_LENGTH, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(static_cast<GLint>(strlen(essl3_shaders::PositionAttrib())) + 1, num); glGetProgramInterfaceiv(program, GL_PROGRAM_INPUT, GL_MAX_NUM_ACTIVE_VARIABLES, &num); EXPECT_GL_ERROR(GL_INVALID_OPERATION); glGetProgramInterfaceiv(program, GL_PROGRAM_OUTPUT, GL_ACTIVE_RESOURCES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(1, num); glGetProgramInterfaceiv(program, GL_PROGRAM_OUTPUT, GL_MAX_NAME_LENGTH, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(7, num); glGetProgramInterfaceiv(program, GL_PROGRAM_OUTPUT, GL_MAX_NUM_ACTIVE_VARIABLES, &num); EXPECT_GL_ERROR(GL_INVALID_OPERATION); glGetProgramInterfaceiv(program, GL_UNIFORM_BLOCK, GL_ACTIVE_RESOURCES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(1, num); glGetProgramInterfaceiv(program, GL_UNIFORM_BLOCK, GL_MAX_NAME_LENGTH, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(3, num); glGetProgramInterfaceiv(program, GL_UNIFORM_BLOCK, GL_MAX_NUM_ACTIVE_VARIABLES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(2, num); // mem0, mem1 glGetProgramInterfaceiv(program, GL_UNIFORM, GL_ACTIVE_RESOURCES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(3, num); glGetProgramInterfaceiv(program, GL_UNIFORM, GL_MAX_NAME_LENGTH, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(8, num); // "ub.mem0" glGetProgramInterfaceiv(program, GL_UNIFORM, GL_MAX_NUM_ACTIVE_VARIABLES, &num); EXPECT_GL_ERROR(GL_INVALID_OPERATION); glGetProgramInterfaceiv(program, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(2, num); glGetProgramInterfaceiv(program, GL_SHADER_STORAGE_BLOCK, GL_MAX_NAME_LENGTH, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(23, num); // "shaderStorageBlock2[0]" glGetProgramInterfaceiv(program, GL_SHADER_STORAGE_BLOCK, GL_MAX_NUM_ACTIVE_VARIABLES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(1, num); } // Tests the resource property query for uniform can be done correctly. TEST_P(ProgramInterfaceTestES31, GetUniformProperties) { // TODO(jiajia.qin@intel.com): Don't skip this test once atomic counter is supported on d3d // backend. http://anglebug.com/1729 ANGLE_SKIP_TEST_IF(IsD3D11()); constexpr char kVS[] = "#version 310 es\n" "precision highp float;\n" "uniform layout(location=12) vec4 color;\n" "layout(binding = 2, offset = 4) uniform atomic_uint foo;\n" "void main()\n" "{\n" " atomicCounterIncrement(foo);\n" "}"; constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "uniform vec4 color;\n" "out vec4 oColor;\n" "void main()\n" "{\n" " oColor = color;\n" "}"; ANGLE_GL_PROGRAM(program, kVS, kFS); GLuint index = glGetProgramResourceIndex(program, GL_UNIFORM, "color"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLchar name[64]; GLsizei length; glGetProgramResourceName(program, GL_UNIFORM, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(5, length); EXPECT_EQ("color", std::string(name)); GLint location = glGetProgramResourceLocation(program, GL_UNIFORM, "color"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(12, location); GLenum props[] = {GL_TYPE, GL_ARRAY_SIZE, GL_LOCATION, GL_NAME_LENGTH, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER, GL_ARRAY_STRIDE, GL_BLOCK_INDEX, GL_IS_ROW_MAJOR, GL_MATRIX_STRIDE, GL_OFFSET, GL_ATOMIC_COUNTER_BUFFER_INDEX}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); GLint params[ArraySize(props)]; glGetProgramResourceiv(program, GL_UNIFORM, index, propCount, props, propCount, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(GL_FLOAT_VEC4, params[0]); // type EXPECT_EQ(1, params[1]); // array_size EXPECT_EQ(12, params[2]); // location EXPECT_EQ(6, params[3]); // name_length EXPECT_EQ(0, params[4]); // referenced_by_vertex_shader EXPECT_EQ(1, params[5]); // referenced_by_fragment_shader EXPECT_EQ(0, params[6]); // referenced_by_compute_shader EXPECT_EQ(-1, params[7]); // array_stride EXPECT_EQ(-1, params[8]); // block_index EXPECT_EQ(0, params[9]); // is_row_major EXPECT_EQ(-1, params[10]); // matrix_stride EXPECT_EQ(-1, params[11]); // offset EXPECT_EQ(-1, params[12]); // atomic_counter_buffer_index index = glGetProgramResourceIndex(program, GL_UNIFORM, "foo"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); glGetProgramResourceName(program, GL_UNIFORM, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(3, length); EXPECT_EQ("foo", std::string(name)); location = glGetProgramResourceLocation(program, GL_UNIFORM, "foo"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(-1, location); glGetProgramResourceiv(program, GL_UNIFORM, index, propCount, props, propCount, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(GL_UNSIGNED_INT_ATOMIC_COUNTER, params[0]); // type EXPECT_EQ(1, params[1]); // array_size EXPECT_EQ(-1, params[2]); // location EXPECT_EQ(4, params[3]); // name_length EXPECT_EQ(1, params[4]); // referenced_by_vertex_shader EXPECT_EQ(0, params[5]); // referenced_by_fragment_shader EXPECT_EQ(0, params[6]); // referenced_by_compute_shader EXPECT_EQ(0, params[7]); // array_stride EXPECT_EQ(-1, params[8]); // block_index EXPECT_EQ(0, params[9]); // is_row_major EXPECT_EQ(0, params[10]); // matrix_stride EXPECT_EQ(4, params[11]); // offset EXPECT_NE(-1, params[12]); // atomic_counter_buffer_index } // Tests the resource property query for uniform block can be done correctly. TEST_P(ProgramInterfaceTestES31, GetUniformBlockProperties) { constexpr char kVS[] = "#version 310 es\n" "in vec2 position;\n" "out vec2 v;\n" "layout(binding = 2) uniform blockName {\n" " float f1;\n" " float f2;\n" "} instanceName;\n" "void main() {\n" " v = vec2(instanceName.f1, instanceName.f2);\n" " gl_Position = vec4(position, 0, 1);\n" "}"; constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "in vec2 v;\n" "out vec4 color;\n" "void main() {\n" " color = vec4(v, 0, 1);\n" "}"; ANGLE_GL_PROGRAM(program, kVS, kFS); GLuint index = glGetProgramResourceIndex(program, GL_UNIFORM_BLOCK, "blockName"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLchar name[64]; GLsizei length; glGetProgramResourceName(program, GL_UNIFORM_BLOCK, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(9, length); EXPECT_EQ("blockName", std::string(name)); GLenum props[] = {GL_BUFFER_BINDING, GL_BUFFER_DATA_SIZE, GL_NAME_LENGTH, GL_NUM_ACTIVE_VARIABLES, GL_ACTIVE_VARIABLES, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); constexpr int kBufSize = 256; GLint params[kBufSize]; GLint magic = 0xBEEF; // Tests bufSize is respected even some prop returns more than one value. params[propCount] = magic; glGetProgramResourceiv(program, GL_UNIFORM_BLOCK, index, propCount, props, propCount, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(2, params[0]); // buffer_binding EXPECT_NE(0, params[1]); // buffer_data_size EXPECT_EQ(10, params[2]); // name_length EXPECT_EQ(2, params[3]); // num_active_variables EXPECT_LE(0, params[4]); // index of 'f1' or 'f2' EXPECT_LE(0, params[5]); // index of 'f1' or 'f2' EXPECT_EQ(1, params[6]); // referenced_by_vertex_shader EXPECT_EQ(0, params[7]); // referenced_by_fragment_shader EXPECT_EQ(magic, params[8]); glGetProgramResourceiv(program, GL_UNIFORM_BLOCK, index, propCount, props, kBufSize, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount + 1, length); EXPECT_EQ(0, params[8]); // referenced_by_compute_shader // bufSize is reached in middle of outputting values for GL_ACTIVE_VARIABLES. GLenum actvieVariablesProperty = GL_ACTIVE_VARIABLES; params[1] = magic; glGetProgramResourceiv(program, GL_UNIFORM_BLOCK, index, 1, &actvieVariablesProperty, 1, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(1, length); EXPECT_LE(0, params[0]); // index of 'f1' or 'f2' EXPECT_EQ(magic, params[1]); } // Tests atomic counter buffer qeury works correctly. TEST_P(ProgramInterfaceTestES31, QueryAtomicCounteBuffer) { // TODO(jiajia.qin@intel.com): Don't skip this test once atomic counter is supported on d3d // backend. http://anglebug.com/1729 ANGLE_SKIP_TEST_IF(IsD3D11()); constexpr char kVS[] = "#version 310 es\n" "precision highp float;\n" "layout(binding = 2, offset = 0) uniform atomic_uint vcounter;\n" "in highp vec4 a_position;\n" "void main()\n" "{\n" " atomicCounterIncrement(vcounter);\n" " gl_Position = a_position;\n" "}\n"; constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "layout(binding = 2, offset = 4) uniform atomic_uint fcounter;\n" "out highp vec4 my_color;\n" "void main()\n" "{\n" " atomicCounterDecrement(fcounter);\n" " my_color = vec4(0.0);\n" "}\n"; ANGLE_GL_PROGRAM(program, kVS, kFS); GLint num; glGetProgramInterfaceiv(program, GL_ATOMIC_COUNTER_BUFFER, GL_ACTIVE_RESOURCES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(1, num); glGetProgramInterfaceiv(program, GL_ATOMIC_COUNTER_BUFFER, GL_MAX_NUM_ACTIVE_VARIABLES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(2, num); GLenum props[] = {GL_BUFFER_BINDING, GL_NUM_ACTIVE_VARIABLES, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); GLint params[ArraySize(props)]; GLsizei length = 0; glGetProgramResourceiv(program, GL_ATOMIC_COUNTER_BUFFER, 0, propCount, props, propCount, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(2, params[0]); // buffer_binding EXPECT_EQ(2, params[1]); // num_active_variables EXPECT_EQ(1, params[2]); // referenced_by_vertex_shader EXPECT_EQ(1, params[3]); // referenced_by_fragment_shader EXPECT_EQ(0, params[4]); // referenced_by_compute_shader } // Tests the resource property query for buffer variable can be done correctly. TEST_P(ProgramInterfaceTestES31, GetBufferVariableProperties) { // TODO(jiajia.qin@intel.com): Don't skip this test once non-simple SSBO sentences are supported // on d3d backend. http://anglebug.com/1951 ANGLE_SKIP_TEST_IF(IsD3D11()); // Check SSBO support GLint numSupported; glGetIntegerv(GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS, &numSupported); EXPECT_GL_NO_ERROR(); ANGLE_SKIP_TEST_IF(numSupported < 2); constexpr char kVS[] = "#version 310 es\n" "precision highp float;\n" "struct S {\n" " vec3 a;\n" " ivec2 b[4];\n" "};\n" "layout(std140) buffer blockName0 {\n" " S s0;\n" " vec2 v0;\n" " S s1[2];\n" " uint u0;\n" "};\n" "layout(binding = 1) buffer blockName1 {\n" " uint u1[2];\n" " float f1;\n" "} instanceName1[2];\n" "void main()\n" "{\n" " gl_Position = vec4(instanceName1[0].f1, s1[0].a);\n" "}\n"; constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "layout(binding = 1) buffer blockName1 {\n" " uint u1[2];\n" " float f1;\n" "} instanceName1[2];\n" "out vec4 oColor;\n" "void main()\n" "{\n" " oColor = vec4(instanceName1[0].f1, 0, 0, 1);\n" "}"; ANGLE_GL_PROGRAM(program, kVS, kFS); GLuint index = glGetProgramResourceIndex(program, GL_BUFFER_VARIABLE, "blockName1.f1"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLchar name[64]; GLsizei length; glGetProgramResourceName(program, GL_BUFFER_VARIABLE, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(13, length); EXPECT_EQ("blockName1.f1", std::string(name)); GLenum props[] = {GL_ARRAY_SIZE, GL_ARRAY_STRIDE, GL_BLOCK_INDEX, GL_IS_ROW_MAJOR, GL_MATRIX_STRIDE, GL_NAME_LENGTH, GL_OFFSET, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER, GL_TOP_LEVEL_ARRAY_SIZE, GL_TOP_LEVEL_ARRAY_STRIDE, GL_TYPE}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); constexpr int kBufSize = 256; GLint params[kBufSize]; glGetProgramResourceiv(program, GL_BUFFER_VARIABLE, index, propCount, props, kBufSize, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(1, params[0]); // array_size EXPECT_LE(0, params[1]); // array_stride EXPECT_LE(0, params[2]); // block_index EXPECT_EQ(0, params[3]); // is_row_major EXPECT_EQ(0, params[4]); // matrix_stride EXPECT_EQ(14, params[5]); // name_length EXPECT_LE(0, params[6]); // offset EXPECT_EQ(1, params[7]); // referenced_by_vertex_shader EXPECT_EQ(1, params[8]); // referenced_by_fragment_shader EXPECT_EQ(0, params[9]); // referenced_by_compute_shader EXPECT_EQ(1, params[10]); // top_level_array_size EXPECT_LE(0, params[11]); // top_level_array_stride EXPECT_EQ(GL_FLOAT, params[12]); // type index = glGetProgramResourceIndex(program, GL_BUFFER_VARIABLE, "s1[0].a"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); glGetProgramResourceName(program, GL_BUFFER_VARIABLE, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(7, length); EXPECT_EQ("s1[0].a", std::string(name)); glGetProgramResourceiv(program, GL_BUFFER_VARIABLE, index, propCount, props, kBufSize, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(1, params[0]); // array_size EXPECT_LE(0, params[1]); // array_stride EXPECT_LE(0, params[2]); // block_index EXPECT_EQ(0, params[3]); // is_row_major EXPECT_EQ(0, params[4]); // matrix_stride EXPECT_EQ(8, params[5]); // name_length EXPECT_LE(0, params[6]); // offset EXPECT_EQ(1, params[7]); // referenced_by_vertex_shader EXPECT_EQ(0, params[8]); // referenced_by_fragment_shader EXPECT_EQ(0, params[9]); // referenced_by_compute_shader EXPECT_EQ(2, params[10]); // top_level_array_size EXPECT_EQ(80, params[11]); // top_level_array_stride EXPECT_EQ(GL_FLOAT_VEC3, params[12]); // type } // Tests the resource property querying for buffer variable in std430 SSBO works correctly. TEST_P(ProgramInterfaceTestES31, GetStd430BufferVariableProperties) { ANGLE_SKIP_TEST_IF(IsAMD() && IsWindows() && IsOpenGL()); constexpr char kComputeShaderSource[] = R"(#version 310 es layout(local_size_x=1, local_size_y=1, local_size_z=1) in; struct S { uvec2 v; mat2 m; }; layout(std430, binding = 0) buffer blockIn { uint u; uint a[2]; S s; } instanceIn; layout(std430, binding = 1) buffer blockOut { uint u; uint a[2]; S s; } instanceOut; void main() { instanceOut.u = instanceIn.u; instanceOut.a[0] = instanceIn.a[0]; instanceOut.a[1] = instanceIn.a[1]; instanceOut.s.v = instanceIn.s.v; instanceOut.s.m = instanceIn.s.m; } )"; ANGLE_GL_COMPUTE_PROGRAM(program, kComputeShaderSource); GLuint index = glGetProgramResourceIndex(program, GL_BUFFER_VARIABLE, "blockIn.a"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLchar name[64]; GLsizei length; glGetProgramResourceName(program, GL_BUFFER_VARIABLE, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(12, length); EXPECT_EQ("blockIn.a[0]", std::string(name)); GLenum props[] = {GL_ARRAY_SIZE, GL_ARRAY_STRIDE, GL_BLOCK_INDEX, GL_IS_ROW_MAJOR, GL_MATRIX_STRIDE, GL_NAME_LENGTH, GL_OFFSET, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER, GL_TOP_LEVEL_ARRAY_SIZE, GL_TOP_LEVEL_ARRAY_STRIDE, GL_TYPE}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); constexpr int kBufSize = 256; GLint params[kBufSize]; glGetProgramResourceiv(program, GL_BUFFER_VARIABLE, index, propCount, props, kBufSize, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(2, params[0]); // array_size EXPECT_LE(4, params[1]); // array_stride EXPECT_LE(0, params[2]); // block_index EXPECT_EQ(0, params[3]); // is_row_major EXPECT_EQ(0, params[4]); // matrix_stride EXPECT_EQ(13, params[5]); // name_length EXPECT_EQ(4, params[6]); // offset EXPECT_EQ(0, params[7]); // referenced_by_vertex_shader EXPECT_EQ(0, params[8]); // referenced_by_fragment_shader EXPECT_EQ(1, params[9]); // referenced_by_compute_shader EXPECT_EQ(1, params[10]); // top_level_array_size EXPECT_EQ(0, params[11]); // top_level_array_stride EXPECT_EQ(GL_UNSIGNED_INT, params[12]); // type index = glGetProgramResourceIndex(program, GL_BUFFER_VARIABLE, "blockIn.s.m"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); glGetProgramResourceName(program, GL_BUFFER_VARIABLE, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(11, length); EXPECT_EQ("blockIn.s.m", std::string(name)); glGetProgramResourceiv(program, GL_BUFFER_VARIABLE, index, propCount, props, kBufSize, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(1, params[0]); // array_size EXPECT_LE(0, params[1]); // array_stride EXPECT_LE(0, params[2]); // block_index EXPECT_EQ(0, params[3]); // is_row_major EXPECT_EQ(8, params[4]); // matrix_stride EXPECT_EQ(12, params[5]); // name_length EXPECT_EQ(24, params[6]); // offset EXPECT_EQ(0, params[7]); // referenced_by_vertex_shader EXPECT_EQ(0, params[8]); // referenced_by_fragment_shader // TODO(jiajia.qin@intel.com): referenced_by_compute_shader is not // correctly handled. http://anglebug.com/1920. // EXPECT_EQ(1, params[9]); // referenced_by_compute_shader EXPECT_EQ(1, params[10]); // top_level_array_size EXPECT_EQ(0, params[11]); // top_level_array_stride EXPECT_EQ(GL_FLOAT_MAT2, params[12]); // type } // Test that TOP_LEVEL_ARRAY_STRIDE for buffer variable with aggregate type works correctly. TEST_P(ProgramInterfaceTestES31, TopLevelArrayStrideWithAggregateType) { constexpr char kComputeShaderSource[] = R"(#version 310 es layout(local_size_x=1, local_size_y=1, local_size_z=1) in; struct S { uvec2 v; mat2 m; }; layout(std430, binding = 0) buffer blockIn { uint u; uint a[2]; S s; } instanceIn; layout(std430, binding = 1) buffer blockOut { uint u; uint a[4][3]; S s[3][2]; } instanceOut; void main() { instanceOut.u = instanceIn.u; instanceOut.a[0][0] = instanceIn.a[0]; instanceOut.a[0][1] = instanceIn.a[1]; instanceOut.s[0][0].v = instanceIn.s.v; instanceOut.s[0][0].m = instanceIn.s.m; } )"; ANGLE_GL_COMPUTE_PROGRAM(program, kComputeShaderSource); GLuint index = glGetProgramResourceIndex(program, GL_BUFFER_VARIABLE, "blockOut.s[0][0].m"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLchar name[64]; GLsizei length; glGetProgramResourceName(program, GL_BUFFER_VARIABLE, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(18, length); EXPECT_EQ("blockOut.s[0][0].m", std::string(name)); GLenum props[] = {GL_ARRAY_SIZE, GL_ARRAY_STRIDE, GL_BLOCK_INDEX, GL_IS_ROW_MAJOR, GL_MATRIX_STRIDE, GL_NAME_LENGTH, GL_OFFSET, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER, GL_TOP_LEVEL_ARRAY_SIZE, GL_TOP_LEVEL_ARRAY_STRIDE, GL_TYPE}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); constexpr int kBufSize = 256; GLint params[kBufSize]; glGetProgramResourceiv(program, GL_BUFFER_VARIABLE, index, propCount, props, kBufSize, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(1, params[0]); // array_size EXPECT_LE(0, params[1]); // array_stride EXPECT_LE(0, params[2]); // block_index EXPECT_EQ(0, params[3]); // is_row_major EXPECT_EQ(8, params[4]); // matrix_stride EXPECT_EQ(19, params[5]); // name_length EXPECT_EQ(64, params[6]); // offset EXPECT_EQ(0, params[7]); // referenced_by_vertex_shader EXPECT_EQ(0, params[8]); // referenced_by_fragment_shader // TODO(jiajia.qin@intel.com): referenced_by_compute_shader is not // correctly handled. http://anglebug.com/1920. // EXPECT_EQ(1, params[9]); // referenced_by_compute_shader EXPECT_EQ(3, params[10]); // top_level_array_size EXPECT_EQ(48, params[11]); // top_level_array_stride EXPECT_EQ(GL_FLOAT_MAT2, params[12]); // type index = glGetProgramResourceIndex(program, GL_BUFFER_VARIABLE, "blockOut.a[0][0]"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); glGetProgramResourceName(program, GL_BUFFER_VARIABLE, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(16, length); EXPECT_EQ("blockOut.a[0][0]", std::string(name)); glGetProgramResourceiv(program, GL_BUFFER_VARIABLE, index, propCount, props, kBufSize, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(3, params[0]); // array_size EXPECT_LE(0, params[1]); // array_stride EXPECT_LE(0, params[2]); // block_index EXPECT_EQ(0, params[3]); // is_row_major EXPECT_EQ(0, params[4]); // matrix_stride EXPECT_EQ(17, params[5]); // name_length EXPECT_EQ(4, params[6]); // offset EXPECT_EQ(0, params[7]); // referenced_by_vertex_shader EXPECT_EQ(0, params[8]); // referenced_by_fragment_shader EXPECT_EQ(1, params[9]); // referenced_by_compute_shader EXPECT_EQ(4, params[10]); // top_level_array_size EXPECT_EQ(12, params[11]); // top_level_array_stride EXPECT_EQ(GL_UNSIGNED_INT, params[12]); // type } // Tests the resource property query for shader storage block can be done correctly. TEST_P(ProgramInterfaceTestES31, GetShaderStorageBlockProperties) { // TODO(jiajia.qin@intel.com): Don't skip this test once non-simple SSBO sentences are supported // on d3d backend. http://anglebug.com/1951 ANGLE_SKIP_TEST_IF(IsD3D11()); // Check SSBO support GLint numSupported; glGetIntegerv(GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS, &numSupported); EXPECT_GL_NO_ERROR(); ANGLE_SKIP_TEST_IF(numSupported < 3); constexpr char kVS[] = "#version 310 es\n" "precision highp float;\n" "struct S {\n" " vec3 a;\n" " ivec2 b[4];\n" "};\n" "layout(std140) buffer blockName0 {\n" " S s0;\n" " vec2 v0;\n" " S s1[2];\n" " uint u0;\n" "};\n" "layout(binding = 1) buffer blockName1 {\n" " uint u1[2];\n" " float f1;\n" "} instanceName1[2];\n" "layout(binding = 2) buffer blockName2 {\n" " uint u2;\n" " float f2;\n" "};\n" "void main()\n" "{\n" " gl_Position = vec4(instanceName1[0].f1, s1[0].a);\n" "}\n"; constexpr char kFS[] = "#version 310 es\n" "precision highp float;\n" "uniform vec4 color;\n" "out vec4 oColor;\n" "void main()\n" "{\n" " oColor = color;\n" "}"; ANGLE_GL_PROGRAM(program, kVS, kFS); GLuint index = glGetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, "blockName0"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLchar name[64]; GLsizei length; glGetProgramResourceName(program, GL_SHADER_STORAGE_BLOCK, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(10, length); EXPECT_EQ("blockName0", std::string(name)); GLenum props[] = {GL_ACTIVE_VARIABLES, GL_BUFFER_BINDING, GL_NUM_ACTIVE_VARIABLES, GL_BUFFER_DATA_SIZE, GL_NAME_LENGTH, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); constexpr int kBufSize = 256; GLint params[kBufSize]; glGetProgramResourceiv(program, GL_SHADER_STORAGE_BLOCK, index, propCount, props, kBufSize, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(13, length); EXPECT_LE(0, params[0]); // active_variables s0.a EXPECT_LE(0, params[1]); // active_variables s0.b EXPECT_LE(0, params[2]); // active_variables v0 EXPECT_LE(0, params[3]); // active_variables s1[0].a EXPECT_LE(0, params[4]); // active_variables s1[0].b EXPECT_LE(0, params[5]); // active_variables u0 EXPECT_EQ(0, params[6]); // buffer_binding EXPECT_EQ(6, params[7]); // num_active_variables EXPECT_LE(0, params[8]); // buffer_data_size EXPECT_EQ(11, params[9]); // name_length EXPECT_EQ(1, params[10]); // referenced_by_vertex_shader EXPECT_EQ(0, params[11]); // referenced_by_fragment_shader EXPECT_EQ(0, params[12]); // referenced_by_compute_shader index = glGetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, "blockName1"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); glGetProgramResourceName(program, GL_SHADER_STORAGE_BLOCK, index, sizeof(name), &length, name); EXPECT_GL_NO_ERROR(); EXPECT_EQ(13, length); EXPECT_EQ("blockName1[0]", std::string(name)); } // Tests querying the program resources of atomic counter buffers. TEST_P(ProgramInterfaceTestES31, GetAtomicCounterProperties) { constexpr char kCSSource[] = R"(#version 310 es layout(local_size_x=1, local_size_y=1, local_size_z=1) in; layout(binding = 0) uniform atomic_uint acbase; layout(binding = 0, offset = 8) uniform atomic_uint ac[1]; layout(binding = 0) uniform atomic_uint ac2; void main() { atomicCounter(acbase); atomicCounter(ac[0]); atomicCounter(ac2); })"; ANGLE_GL_COMPUTE_PROGRAM(program, kCSSource); GLuint index = glGetProgramResourceIndex(program, GL_UNIFORM, "ac"); EXPECT_GL_NO_ERROR(); EXPECT_NE(GL_INVALID_INDEX, index); GLenum props[] = {GL_ATOMIC_COUNTER_BUFFER_INDEX}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); GLint atomicIndex; GLsizei length; glGetProgramResourceiv(program, GL_UNIFORM, index, propCount, props, 1, &length, &atomicIndex); EXPECT_GL_NO_ERROR(); EXPECT_EQ(1, length); EXPECT_LE(0, atomicIndex); GLenum atomicProps[] = {GL_ACTIVE_VARIABLES, GL_BUFFER_BINDING, GL_NUM_ACTIVE_VARIABLES, GL_BUFFER_DATA_SIZE, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER}; GLsizei atomicPropsCount = static_cast<GLsizei>(ArraySize(atomicProps)); constexpr int kBufSize = 256; GLint params[kBufSize]; GLsizei length2; glGetProgramResourceiv(program, GL_ATOMIC_COUNTER_BUFFER, atomicIndex, atomicPropsCount, atomicProps, kBufSize, &length2, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(9, length2); EXPECT_LE(0, params[0]); // active_variables acbase EXPECT_LE(0, params[1]); // active_variables ac[1] EXPECT_LE(0, params[2]); // active_variables ac2 EXPECT_EQ(0, params[3]); // buffer_binding EXPECT_EQ(3, params[4]); // num_active_variables EXPECT_EQ(16, params[5]); // buffer_data_size EXPECT_EQ(0, params[6]); // referenced_by_vertex_shader EXPECT_EQ(0, params[7]); // referenced_by_fragment_shader EXPECT_EQ(1, params[8]); // referenced_by_compute_shader } // Tests transform feedback varying qeury works correctly. TEST_P(ProgramInterfaceTestES31, QueryTransformFeedbackVarying) { constexpr char kVS[] = R"(#version 310 es in vec3 position; out float outSingleType; out vec2 outWholeArray[2]; out vec3 outArrayElements[16]; void main() { outSingleType = 0.0; outWholeArray[0] = vec2(position); outArrayElements[7] = vec3(0, 0, 0); outArrayElements[15] = position; gl_Position = vec4(position, 1); })"; constexpr char kFS[] = R"(#version 310 es precision mediump float; out vec4 color; in float outSingleType; in vec2 outWholeArray[2]; in vec3 outArrayElements[16]; void main() { color = vec4(0); })"; std::vector<std::string> tfVaryings; tfVaryings.push_back("outArrayElements[7]"); tfVaryings.push_back("outArrayElements[15]"); tfVaryings.push_back("outSingleType"); tfVaryings.push_back("outWholeArray"); GLuint program = CompileProgramWithTransformFeedback(kVS, kFS, tfVaryings, GL_INTERLEAVED_ATTRIBS); ASSERT_NE(0u, program); GLint num; glGetProgramInterfaceiv(program, GL_TRANSFORM_FEEDBACK_VARYING, GL_ACTIVE_RESOURCES, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(4, num); glGetProgramInterfaceiv(program, GL_TRANSFORM_FEEDBACK_VARYING, GL_MAX_NAME_LENGTH, &num); EXPECT_GL_NO_ERROR(); EXPECT_EQ(21, num); // outArrayElements[15] // GLES 3.10, Page 77: // For TRANSFORM_FEEDBACK_VARYING, the active resource list will use the variable order // specified in the most recent call to TransformFeedbackVaryings before the last call to // LinkProgram. GLuint index = glGetProgramResourceIndex(program, GL_TRANSFORM_FEEDBACK_VARYING, "outArrayElements[7]"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(0u, index); index = glGetProgramResourceIndex(program, GL_TRANSFORM_FEEDBACK_VARYING, "outArrayElements[15]"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(1u, index); index = glGetProgramResourceIndex(program, GL_TRANSFORM_FEEDBACK_VARYING, "outSingleType"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(2u, index); index = glGetProgramResourceIndex(program, GL_TRANSFORM_FEEDBACK_VARYING, "outWholeArray"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(3u, index); // GLES 3.10, Page 80: // For TRANSFORM_FEEDBACK_VARYING resources, name must match one of the variables to be captured // as specified by a previous call to TransformFeedbackVaryings. Otherwise, INVALID_INDEX is // returned. // If name does not match a resource as described above, the value INVALID_INDEX is returned, // but no GL error is generated. index = glGetProgramResourceIndex(program, GL_TRANSFORM_FEEDBACK_VARYING, "outWholeArray[0]"); EXPECT_GL_NO_ERROR(); EXPECT_EQ(GL_INVALID_INDEX, index); GLenum props[] = {GL_TYPE, GL_ARRAY_SIZE, GL_NAME_LENGTH}; GLsizei propCount = static_cast<GLsizei>(ArraySize(props)); GLint params[ArraySize(props)]; GLsizei length = 0; // Query properties of 'outArrayElements[15]'. glGetProgramResourceiv(program, GL_TRANSFORM_FEEDBACK_VARYING, 1, propCount, props, propCount, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(GL_FLOAT_VEC3, params[0]); // type EXPECT_EQ(1, params[1]); // array_size EXPECT_EQ(21, params[2]); // name_length // Query properties of 'outWholeArray'. glGetProgramResourceiv(program, GL_TRANSFORM_FEEDBACK_VARYING, 3, propCount, props, propCount, &length, params); EXPECT_GL_NO_ERROR(); EXPECT_EQ(propCount, length); EXPECT_EQ(GL_FLOAT_VEC2, params[0]); // type EXPECT_EQ(2, params[1]); // array_size EXPECT_EQ(14, params[2]); // name_length glDeleteProgram(program); } ANGLE_INSTANTIATE_TEST_ES31(ProgramInterfaceTestES31); } // anonymous namespace
36.944125
100
0.63713
[ "render", "vector", "transform" ]
db52d6ab106a63b8fe2c88b1c1df7f0063719a87
16,617
cpp
C++
src/auto_settings_ui.cpp
Lauriethefish/FishUtils
110815bb316bfb4376cc8306e4eeaf1cfd28727f
[ "Zlib" ]
1
2021-10-17T12:03:40.000Z
2021-10-17T12:03:40.000Z
src/auto_settings_ui.cpp
Lauriethefish/FishUtils
110815bb316bfb4376cc8306e4eeaf1cfd28727f
[ "Zlib" ]
null
null
null
src/auto_settings_ui.cpp
Lauriethefish/FishUtils
110815bb316bfb4376cc8306e4eeaf1cfd28727f
[ "Zlib" ]
null
null
null
#include "auto_settings_ui.hpp" #include "main.hpp" #include "ui_utils.hpp" #include "System/Collections/Generic/List_1.hpp" using namespace System::Collections::Generic; #include "GlobalNamespace/BeatmapLevelsModel.hpp" #include "GlobalNamespace/BeatmapLevelPackCollection.hpp" #include "GlobalNamespace/IBeatmapLevelPack.hpp" #include "questui/shared/CustomTypes/Components/ExternalComponents.hpp" namespace FishUtils { DEFINE_TYPE(FishUtils, AutoSettingsFlowCoordinator); DEFINE_TYPE(FishUtils, AutoSettingSelectionViewController); DEFINE_TYPE(FishUtils, PlaylistOverridesViewController); DEFINE_TYPE(FishUtils, ThresholdsViewController); void AutoSettingsFlowCoordinator::DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) { if(!firstActivation) {return;} getLogger().info("AutoSettingsFlowCoordinator activating"); this->set_showBackButton(true); AutoSettingSelectionViewController* selectionViewController = BeatSaberUI::CreateViewController<AutoSettingSelectionViewController*>(); selectionViewController->flowCoordinator = this; this->playlistOverridesView = BeatSaberUI::CreateViewController<PlaylistOverridesViewController*>(); this->thresholdsView = BeatSaberUI::CreateViewController<ThresholdsViewController*>(); this->ProvideInitialViewControllers(selectionViewController, nullptr, nullptr, nullptr, nullptr); } void AutoSettingsFlowCoordinator::BackButtonWasPressed(HMUI::ViewController* topViewController) { this->parentFlowCoordinator->DismissFlowCoordinator(this, HMUI::ViewController::AnimationDirection::Horizontal, nullptr, false); } void AutoSettingSelectionViewController::DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) { if(!firstActivation) { // Reopen the setting configuration ViewControllers if they were closed due to the back button being pressed if(wasSettingConfigurationViewOpen) { this->OpenSettingConfigurationView(); } return; } getLogger().info("AutoSettingSelectionViewController activating"); VerticalLayoutGroup* mainLayout = UIUtils::CreateListLikeVerticalLayout(this->get_rectTransform()); mainLayout->set_spacing(1.0); mainLayout->set_childAlignment(TextAnchor::UpperCenter); Transform* mainLayoutTransform = mainLayout->get_rectTransform(); UIUtils::CreateTitle(mainLayoutTransform, "Settings To Configure", "Automatically change various settings based on NPS, NJS, or playlist"); HorizontalLayoutGroup* addSettingLayout = UIUtils::CreateListLikeHorizontalLayout(mainLayoutTransform); addSettingLayout->set_childAlignment(TextAnchor::UpperCenter); Transform* addSettingLayoutTransform = addSettingLayout->get_rectTransform(); // Allow the user to switch between multiple settings, and enable/disable them std::vector<std::string> availableSettings; for(AutoSettings::SettingType* settingType : AutoSettings::GetSettingTypes()) { availableSettings.push_back(settingType->name); } std::function<void(std::string_view)> onSelectedSettingChange = [this] (std::string_view newSetting) { this->selectedSetting = AutoSettings::GetSettingType(std::string(newSetting), false); this->selectedSettingConfig = AutoSettings::GetSettingConfiguration(selectedSetting); // We need to force this to be called initially, even if it was previously enabled on the last setting // Otherwise, the layout will not update when moving between settings if the previous and current setting were both enabled UIUtils::SetToggleForceNotify(this->settingEnabledToggle, selectedSettingConfig); }; HMUI::SimpleTextDropdown* selectSettingDropdown = BeatSaberUI::CreateDropdown(mainLayoutTransform, "Available Settings", availableSettings[0], availableSettings, onSelectedSettingChange); this->settingEnabledToggle = BeatSaberUI::CreateToggle(mainLayoutTransform, "Automatically Set Setting", [this](bool newValue){ getLogger().info("Processing setting enabled change. New value: %s", newValue ? "true" : "false"); // Even if the new setting is enabled as well, we need to close the setting view so that DidActivate is called again, thus refreshing it for the new setting this->CloseSettingConfigurationView(); if(newValue) { selectedSettingConfig = AutoSettings::GetSettingConfiguration(this->selectedSetting); if(!selectedSettingConfig) { selectedSettingConfig = AutoSettings::CreateSettingConfiguration(this->selectedSetting); } this->OpenSettingConfigurationView(); } else { AutoSettings::RemoveSettingConfiguration(this->selectedSetting); } }); onSelectedSettingChange(availableSettings[0]); } void AutoSettingSelectionViewController::OpenSettingConfigurationView() { getLogger().info("Option enabled/selected - opening configuration UI"); PlaylistOverridesViewController* playlistOverrides = reinterpret_cast<PlaylistOverridesViewController*>(this->flowCoordinator->playlistOverridesView); ThresholdsViewController* thresholds = reinterpret_cast<ThresholdsViewController*>(this->flowCoordinator->thresholdsView); playlistOverrides->setting = this->selectedSettingConfig; thresholds->setting = this->selectedSettingConfig; flowCoordinator->SetLeftScreenViewController(playlistOverrides, AnimationType::In); flowCoordinator->SetRightScreenViewController(thresholds, AnimationType::In); this->wasSettingConfigurationViewOpen = true; } void AutoSettingSelectionViewController::CloseSettingConfigurationView() { getLogger().info("Option deselected - closing configuration UI"); flowCoordinator->SetLeftScreenViewController(nullptr, AnimationType::Out); flowCoordinator->SetRightScreenViewController(nullptr, AnimationType::Out); this->wasSettingConfigurationViewOpen = false; } void PlaylistOverridesViewController::DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) { static BeatmapLevelsModel* beatmapLevelsModel = Resources::FindObjectsOfTypeAll<BeatmapLevelsModel*>()->values[0]; // Avoid multiple FindObjectsOfTypeAll calls if(firstActivation) { // On first activation, we create all of the widgets. Then we can update them when moving to a different setting getLogger().info("Performing initial setup for PlaylistOverridesViewController"); VerticalLayoutGroup* mainLayout = UIUtils::CreateListLikeVerticalLayout(this->get_rectTransform()); Transform* mainLayoutTransform = mainLayout->get_rectTransform(); UIUtils::CreateTitle(mainLayoutTransform, "Playlist Overrides", "Force the setting to be a particular value when in a certain set of playlists. Always takes priority over map thresholds if in a playlist where this is enabled"); this->enableToggle = BeatSaberUI::CreateToggle(mainLayoutTransform, "Enable", [this](bool newValue) { enabledLayoutGameObject->SetActive(newValue); // When playlist overrides are enabled, we need to use the default setting type (the first) for this SettingTYpe if(newValue) { getLogger().info("Setting to default setting type . . ."); std::string defaultSetting = this->setting->settingType->options[0]; getLogger().info("%s", defaultSetting.c_str()); this->setting->playlistOverrideSetting = defaultSetting; } else { this->setting->playlistOverrideSetting = ""; } // Workaround for setting the text without re-writing to the config getLogger().info("Setting current dropdown text"); this->setSettingToDropdown->text->set_text(il2cpp_utils::createcsstr(this->setting->playlistOverrideSetting)); }); VerticalLayoutGroup* enabledLayout = UIUtils::CreateListLikeVerticalLayout(mainLayoutTransform); this->enabledLayoutGameObject = enabledLayout->get_gameObject(); Transform* enabledLayoutTransform = enabledLayout->get_rectTransform(); this->setSettingToDropdown = BeatSaberUI::CreateDropdown(enabledLayoutTransform, "Set the setting to", "None", {"None"}, [this](std::string_view newValue) { this->setting->playlistOverrideSetting = std::string(newValue); }); BeatSaberUI::CreateText(enabledLayoutTransform, "When in these playlists"); GridLayoutGroup* playlistsLayout = BeatSaberUI::CreateGridLayoutGroup(enabledLayoutTransform); playlistsLayout->set_padding(RectOffset::New_ctor(2, 2, 2, 2)); playlistsLayout->set_constraint(GridLayoutGroup::Constraint::FixedColumnCount); playlistsLayout->set_constraintCount(3); playlistsLayout->set_cellSize(UnityEngine::Vector2(32.0f, 6.0f)); playlistsLayout->set_spacing(UnityEngine::Vector2(1.0f, 0.8f)); UIUtils::ApplyRectPanelBackground(playlistsLayout->get_gameObject()); Transform* playlistsLayoutTransform = playlistsLayout->get_rectTransform(); getLogger().info("Adding all playlists to the UI . . ."); Array<IBeatmapLevelPack*>* playlists = beatmapLevelsModel->get_allLoadedBeatmapLevelPackCollection()->get_beatmapLevelPacks(); for(int i = 0; i < playlists->get_Length(); i++) { IBeatmapLevelPack* playlist = playlists->values[i]; std::string playlistName = to_utf8(csstrtostr(playlist->get_packName())); Toggle* toggle = BeatSaberUI::CreateToggle(playlistsLayoutTransform, playlistName, [this, playlistName](bool newValue) { AutoSettings::SettingConfiguration* setting = this->setting; if(newValue) { setting->overriddenInPlaylists.push_back(playlistName); } else { auto location = std::find(setting->overriddenInPlaylists.begin(), setting->overriddenInPlaylists.end(), playlistName); if(location != setting->overriddenInPlaylists.end()) { setting->overriddenInPlaylists.erase(location); } } }); UnityEngine::Transform* toggleParentTransform = toggle->get_transform()->GetParent(); TextMeshProUGUI* toggleText = toggleParentTransform->get_gameObject()->GetComponentInChildren<TextMeshProUGUI*>(); // Help all of the playlists to actually fit in the layout toggleText->set_overflowMode(TextOverflowModes::Ellipsis); toggleText->set_fontSize(2.5); getLogger().info("Inserting with name %s", playlistName.c_str()); this->playlistToggles.push_back({playlistName, toggle}); // Store the playlist toggles for later so that we can change them when moving between multiple settings } } bool isEnabled = !this->setting->playlistOverrideSetting.empty(); // playlistOverrideSetting is empty if this is disabled getLogger().info("Is setting enabled: %s", isEnabled ? "true" : "false"); UIUtils::SetToggleForceNotify(enableToggle, isEnabled); getLogger().info("Setting options for setting type %s to playlists UI", setting->settingType->saveName.c_str()); List_1<Il2CppString*>* optionsList = List_1<Il2CppString*>::New_ctor(); for(std::string optionName : setting->settingType->options) { optionsList->Add(il2cpp_utils::createcsstr(optionName)); } this->setSettingToDropdown->SetTexts(reinterpret_cast<IReadOnlyList_1<Il2CppString*>*>(optionsList)); // Since we may have just swapped from a different setting, we need to update all of the toggles to be in the correct configuration getLogger().info("Updating playlist toggles . . . Length: %lu", this->playlistToggles.size()); for(auto pair : playlistToggles) { std::string playlistName = pair.first; Toggle* toggle = pair.second; bool isEnabled = this->setting->IsOverriddenInPlaylist(playlistName); toggle->Set(isEnabled, true); } } void ThresholdsViewController::DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) { if(firstActivation) { getLogger().info("Performing initial setup for ThresholdsViewController"); VerticalLayoutGroup* mainLayout = UIUtils::CreateListLikeVerticalLayout(this->get_rectTransform()); this->mainLayoutTransform = mainLayout->get_rectTransform(); UIUtils::CreateTitle(mainLayoutTransform, "Configure Thresholds", "Automatically set the setting depending on various map parameters. NOTE: If a playlist override is found, it will always take priority over this"); std::vector<std::string> mapElements; for(AutoSettings::MapElementType* elementType : AutoSettings::GetMapElementTypes()) { mapElements.push_back(elementType->name); } this->parameterDropdown = BeatSaberUI::CreateDropdown(mainLayoutTransform, "Map Parameter", mapElements[0], mapElements, [this](std::string_view newValue){ getLogger().info("Changing map element type to %s", std::string(newValue).c_str()); this->setting->SetConfigureBasedOn(AutoSettings::GetMapElementType(std::string(newValue), false)); this->RefreshThresholdSettings(); }); this->flipOptionsToggle = BeatSaberUI::CreateToggle(mainLayoutTransform, "Flip Options", [this](bool newValue){ getLogger().info("Changing flip options to %s", newValue ? "true" : "false"); this->setting->SetFlipOptions(newValue); this->RefreshThresholdSettings(); }); BeatSaberUI::AddHoverHint(flipOptionsToggle->get_gameObject(), "Change the order of the options, to allow high NPS enabling debris for example. Not sure why you'd want this, but it's here in case you do."); } UIUtils::SetDropdownValue(this->parameterDropdown, this->setting->configureBasedOn->name); UIUtils::SetToggleForceNotify(this->flipOptionsToggle, this->setting->GetFlipOptions()); } void ThresholdsViewController::RefreshThresholdSettings() { if(thresholdsObject) { getLogger().info("Removing previous thresholds from layout"); UIUtils::RemoveAndChildren(thresholdsObject); // Remove the old thresholds } VerticalLayoutGroup* thresholdsLayout = UIUtils::CreateListLikeVerticalLayout(mainLayoutTransform); thresholdsLayout->set_childForceExpandWidth(false); thresholdsLayout->set_childControlWidth(true); thresholdsLayout->set_padding(RectOffset::New_ctor(2, 2, 2, 2)); UIUtils::ApplyRectPanelBackground(thresholdsLayout->get_gameObject()); this->thresholdsObject = thresholdsLayout->get_gameObject(); Transform* thresholdsLayoutTransform = thresholdsLayout->get_rectTransform(); int i = 0; getLogger().info("Setting has option count %lu", this->setting->settingType->options.size()); getLogger().info("Setting has theshold count %lu", this->setting->thresholds.size()); for(std::string settingOption : this->setting->options) { BeatSaberUI::CreateText(thresholdsLayoutTransform, settingOption); if(i < setting->thresholds.size()) { UIUtils::CreateSeparatorLine(thresholdsLayoutTransform); BeatSaberUI::CreateIncrementSetting(thresholdsLayoutTransform, "Greater than", 2, 0.25f, setting->thresholds[i], [this, i](float newValue) { this->setting->thresholds[i] = newValue; } ); UIUtils::CreateSeparatorLine(thresholdsLayoutTransform); } i++; } } }
58.717314
239
0.686706
[ "vector", "transform" ]
db6af1f87f7acfa986068f6f04935403b8756356
11,577
cpp
C++
source/mclib/appear.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
38
2015-04-10T13:31:03.000Z
2021-09-03T22:34:05.000Z
source/mclib/appear.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
1
2020-07-09T09:48:44.000Z
2020-07-12T12:41:43.000Z
source/mclib/appear.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
12
2015-06-29T08:06:57.000Z
2021-10-13T13:11:41.000Z
//--------------------------------------------------------------------------- // // Appear.cpp -- File contains the Basic Game Appearance operator overrides // //---------------------------------------------------------------------------// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// //--------------------------------------------------------------------------- // Include Files #include "stdinc.h" #include "appear.h" //#include "camera.h" //#include "apprtype.h" //#include "dbasegui.h" //#include "celine.h" //#include "cevfx.h" //#ifndef FONT_H //#include "Font.h" //#endif // extern bool useFog; #if CONSIDERED_OBSOLETE //--------------------------------------------------------------------------- // class Appearance PVOID Appearance::operator new(size_t mySize) { PVOID result = nullptr; if (AppearanceTypeList::appearanceHeap && AppearanceTypeList::appearanceHeap->heapReady()) { result = AppearanceTypeList::appearanceHeap->Malloc(mySize); } return (result); } //--------------------------------------------------------------------------- void Appearance::operator delete(PVOID us) { int32_t result; if (AppearanceTypeList::appearanceHeap && AppearanceTypeList::appearanceHeap->heapReady()) { result = AppearanceTypeList::appearanceHeap->Free(us); } } #endif //--------------------------------------------------------------------------- void Appearance::drawTextHelp(const std::wstring_view& text, uint32_t color) { uint32_t width, height; Stuff::Vector4D moveHere; moveHere = screenPos; gos_TextSetAttributes(gosFontHandle, 0, gosFontScale, false, true, false, false); gos_TextStringLength(&width, &height, text); moveHere.y = lowerRight.y + 10.0f; moveHere.x -= width / 2; moveHere.z = width; moveHere.w = height; globalFloatHelp->setFloatHelp(text, moveHere, color, SD_BLACK, 1.0f, true, false, false, false); } void Appearance::drawTextHelp(const std::wstring_view& text) { drawTextHelp(text, SD_GREEN); } void Appearance::drawPilotName(const std::wstring_view& text, uint32_t color) { uint32_t width, height; Stuff::Vector4D moveHere; moveHere = screenPos; gos_TextSetAttributes(gosFontHandle, 0, gosFontScale, false, true, false, false); gos_TextStringLength(&width, &height, text); moveHere.y = lowerRight.y + 10.0f + height; moveHere.x -= width / 2; moveHere.z = width; moveHere.w = height; globalFloatHelp->setFloatHelp(text, moveHere, color, SD_BLACK, 1.0f, true, false, false, false); } //--------------------------------------------------------------------------- void Appearance::drawSelectBox(uint32_t color) { Stuff::Vector4D ul, br, pos1, pos2; float offsets; AppearanceType* appearType = getAppearanceType(); if (appearType && appearType->typeBoundExists()) { eye->projectZ(appearType->typeUpperLeft, ul); ul.z = HUD_DEPTH; eye->projectZ(appearType->typeLowerRight, br); br.z = HUD_DEPTH; } else { ul.x = upperLeft.x; ul.y = upperLeft.y; ul.z = HUD_DEPTH; br.x = lowerRight.x; br.y = lowerRight.y; br.z = HUD_DEPTH; } //----------------------------------------------------- // Must scale the magic numbers for select bracket offsets = 5.0f * eye->getScaleFactor(); pos1.x = float(ul.x - offsets); pos1.y = float(ul.y - offsets); pos1.z = ul.z; pos2.x = float(ul.x - offsets); pos2.y = float(ul.y); pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = float(ul.x - offsets); pos1.y = float(ul.y - offsets); pos1.z = ul.z; pos2.x = float(ul.x); pos2.y = float(ul.y - offsets); pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = float(br.x + offsets); pos1.y = float(ul.y - offsets); pos1.z = ul.z; pos2.x = float(br.x + offsets); pos2.y = float(ul.y); pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = float(br.x + offsets); pos1.y = float(ul.y - offsets); pos1.z = ul.z; pos2.x = float(br.x); pos2.y = float(ul.y - offsets); pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = float(br.x + offsets); pos1.y = float(br.y + offsets); pos1.z = ul.z; pos2.x = float(br.x + offsets); pos2.y = float(br.y); pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = float(br.x + offsets); pos1.y = float(br.y + offsets); pos1.z = ul.z; pos2.x = float(br.x); pos2.y = float(br.y + offsets); pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = float(ul.x - offsets); pos1.y = float(br.y + offsets); pos1.z = ul.z; pos2.x = float(ul.x - offsets); pos2.y = float(br.y); pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = float(ul.x - offsets); pos1.y = float(br.y + offsets); pos1.z = ul.z; pos2.x = float(ul.x); pos2.y = float(br.y + offsets); pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } } //--------------------------------------------------------------------------- void Appearance::drawSelectBrackets(uint32_t color) { float offsets = 5.0 * eye->getScaleFactor(); Stuff::Vector4D pos1; Stuff::Vector4D pos2; Stuff::Vector4D ul, br; ul.x = upperLeft.x; ul.y = upperLeft.y; ul.z = HUD_DEPTH; br.x = lowerRight.x; br.y = lowerRight.y; br.z = HUD_DEPTH; pos1.x = ul.x; pos1.y = ul.y; pos1.z = ul.z; pos2.x = ul.x + offsets; pos2.y = ul.y; pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = ul.x; pos1.y = ul.y; pos1.z = ul.z; pos2.x = ul.x; pos2.y = ul.y + offsets; pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = br.x; pos1.y = ul.y; pos1.z = ul.z; pos2.x = br.x; pos2.y = ul.y + offsets; pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = br.x; pos1.y = ul.y; pos1.z = ul.z; pos2.x = br.x - offsets; pos2.y = ul.y; pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = ul.x; pos1.y = br.y; pos1.z = br.z; pos2.x = ul.x; pos2.y = br.y - offsets; pos2.z = br.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = ul.x; pos1.y = br.y; pos1.z = br.z; pos2.x = ul.x + offsets; pos2.y = br.y; pos2.z = br.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = br.x; pos1.y = br.y; pos1.z = br.z; pos2.x = br.x; pos2.y = br.y - offsets; pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } pos1.x = br.x; pos1.y = br.y; pos1.z = br.z; pos2.x = br.x - offsets; pos2.y = br.y; pos2.z = ul.z; pos2.w = pos1.w = 1.0f; { LineElement newElement(pos1, pos2, color, nullptr, -1); newElement.draw(); } } //----------------------------------------------------------------------------- void DrawBox(float l, float t, float r, float b) { Stuff::Vector4D p1, p2; p1.x = l; p1.y = t; p1.z = HUD_DEPTH; p1.w = 1.0; p2.x = r; p2.y = t; p2.z = HUD_DEPTH; p2.w = 1.0; { LineElement newElement(p1, p2, SD_BLACK, nullptr, -1); newElement.draw(); } p1.x = r; p1.y = t; p2.x = r; p2.y = b; { LineElement newElement(p1, p2, SD_BLACK, nullptr, -1); newElement.draw(); } p1.x = r; p1.y = b; p2.x = l; p2.y = b; { LineElement newElement(p1, p2, SD_BLACK, nullptr, -1); newElement.draw(); } p1.x = l; p1.y = t; p2.x = l; p2.y = b; { LineElement newElement(p1, p2, SD_BLACK, nullptr, -1); newElement.draw(); } } void Appearance::drawIcon( uint32_t bmpHandle, uint32_t bmpwidth, uint32_t bmpheight, uint32_t color, uint32_t where) { // ignoring where for now float offset = 8.0 * eye->getScaleFactor(); float trueheight = HEIGHT * eye->getScaleFactor(); float Y = upperLeft.y - offset - trueheight - 2 * bmpheight; float X = (upperLeft.x + lowerRight.x) / 2.f - bmpwidth / 2.f; gos_VERTEX v[4]; for (size_t i = 0; i < 4; i++) { v[i].argb = color; v[i].frgb = 0; v[i].z = 0.f; v[i].rhw = .5f; v[i].x = X; v[i].y = Y; v[i].u = .25; // might want to pass these in too.... v[i].v = 0.f; } v[2].x = v[3].x = X + bmpwidth; v[1].y = v[2].y = Y + bmpheight; v[2].u = v[3].u = 9.f / 16.f; v[1].v = v[2].v = 5.f / 16.f; gos_VERTEX v1[3]; v1[0] = v[0]; v1[1] = v[2]; v1[2] = v[3]; mcTextureManager->addVertices(bmpHandle, v, MC2_ISHUDLMNT); mcTextureManager->addVertices(bmpHandle, v1, MC2_ISHUDLMNT); } //--------------------------------------------------------------------------- void Appearance::drawBars(void) { //----------------------------------------- // Change to GOS DrawQuad code for HWare!! float offset = 8.0 * eye->getScaleFactor(); // Remember, EVEN numbers!!! float truewidth = WIDTH * eye->getScaleFactor() * 2; float trueheight = HEIGHT * eye->getScaleFactor(); float topY = upperLeft.y - offset - trueheight; float leftX = floor((upperLeft.x + lowerRight.x) / 2.f - truewidth / 2); uint32_t color; if (barStatus > 1.0f) barStatus = 1.0f; if (!barcolour) { if (barStatus >= 0.5) color = SB_GREEN; else if (barStatus > 0.2) color = SB_YELLOW; else if (barStatus) color = SB_RED; else color = 0; } else color = barcolour; float barLength = truewidth * barStatus; gos_VERTEX vertices[4]; vertices[0].x = leftX - 1.0; vertices[0].y = topY - 1.0; vertices[0].z = HUD_DEPTH; vertices[0].rhw = 0.5; vertices[0].u = 0.0; vertices[0].v = 0.0; vertices[0].argb = color | 0xff000000; // Factor out the alpha color!! vertices[0].frgb = 0x00000000; vertices[1].x = leftX + barLength + 1.0; vertices[1].y = topY - 1.0; vertices[1].z = HUD_DEPTH; vertices[1].rhw = 0.5; vertices[1].u = 0.0; vertices[1].v = 0.0; vertices[1].argb = color | 0xff000000; // Factor out the alpha color!! vertices[1].frgb = 0x00000000; vertices[2].x = leftX + barLength + 1.0; vertices[2].y = topY + trueheight + 1.0; vertices[2].z = HUD_DEPTH; vertices[2].rhw = 0.5; vertices[2].u = 0.0; vertices[2].v = 0.0; vertices[2].argb = color | 0xff000000; // Factor out the alpha color!! vertices[2].frgb = 0x00000000; vertices[3].x = leftX - 1.0; vertices[3].y = topY + trueheight + 1.0; vertices[3].z = HUD_DEPTH; vertices[3].rhw = 0.5; vertices[3].u = 0.0; vertices[3].v = 0.0; vertices[3].argb = color | 0xff000000; // Factor out the alpha color!! vertices[3].frgb = 0x00000000; PolygonQuadElement newElement; newElement.init(vertices); gos_SetRenderState(gos_State_Fog, 0); newElement.draw(); DrawBox(vertices[0].x, vertices[0].y, (leftX + truewidth + 1.0), vertices[2].y); uint32_t fogcolour = eye->fogcolour; //----------------------------------------------------- // FOG time. Set Render state to FOG on! if (useFog) { gos_SetRenderState(gos_State_Fog, (int32_t)&fogcolour); } } //---------------------------------------------------------------------------
25.00432
97
0.57692
[ "render" ]
db6f0295625ec6f8751ba4805c625f655c4244a4
9,132
cpp
C++
src/FaceTracker.cpp
m9dfukc/ofxDLib
a92befdfea8b45aaf273f79fa123d507567f1635
[ "MIT" ]
4
2016-04-22T13:00:09.000Z
2021-06-21T07:05:59.000Z
src/FaceTracker.cpp
m9dfukc/ofxDLib
a92befdfea8b45aaf273f79fa123d507567f1635
[ "MIT" ]
null
null
null
src/FaceTracker.cpp
m9dfukc/ofxDLib
a92befdfea8b45aaf273f79fa123d507567f1635
[ "MIT" ]
null
null
null
// // FaceTracker.cpp // example_FaceTracker // // Created by Roy Macdonald on 15-01-16. // // #include "FaceTracker.h" using namespace ofxDLib; FaceTracker::FaceTracker() { smoothingRate = 0.5; drawStyle = lines; tracker.setSmoothingRate(smoothingRate); } //-------------------------------------------------------------- void FaceTracker::setup(string predictorDatFilePath) { detector = dlib::get_frontal_face_detector(); if(predictorDatFilePath.empty()){ predictorDatFilePath = ofToDataPath("shape_predictor_68_face_landmarks.dat"); } ofFile f(predictorDatFilePath); if (f.exists()) { dlib::deserialize(f.getAbsolutePath()) >> predictor; } else { ofLogError("ofxDLib::FaceTracker","SHAPE PREDICTOR DAT FILE MISSING!!!"); } } //-------------------------------------------------------------- void FaceTracker::findFaces(const ofPixels& pixels, bool bUpscale) { faces.clear(); dlib::array2d<dlib::rgb_pixel> img; toDLib(pixels, img); if (bUpscale) pyramid_up(img); std::vector<dlib::rectangle> dets = detector(img); tracker.track(toOf(dets)); for (int i=0; i<dets.size(); i++) { vector<ofVec3f> currentLandmarks; dlib::full_object_detection shapes = predictor(img, dets[i]); unsigned int label = tracker.getLabelFromIndex(i); bool existsShapeHistory = shapeHistory.count(label) > 0; bool existsSmoothingPerFace = smoothingRatePerFace.count(label) > 0; if (!existsSmoothingPerFace) smoothingRatePerFace[label] = smoothingRate; float currentSmoothingRate = smoothingRatePerFace[label]; Face face; face.label = label; face.rect = tracker.getSmoothed(label); face.age = tracker.getAge(label); face.velocity = tracker.getVelocity(i); for (int j=0; j<shapes.num_parts(); j++) { ofVec3f point; ofVec3f current = toOf(shapes.part(j)); ofVec3f previous = existsShapeHistory ? shapeHistory[label][j] : current; point.x = ofLerp(previous.x, current.x, currentSmoothingRate); point.y = ofLerp(previous.y, current.y, currentSmoothingRate); currentLandmarks.push_back(point); face.landmarks.push_back(point); } if (face.landmarks.size() == 68) { for (int j=0; j<=16; j++) { // jaw face.jaw.addVertex(face.landmarks[j]); } for (int j=17; j<=21; j++) { // leftEyebrow face.leftEyebrow.addVertex(face.landmarks[j]); } for (int j=22; j<=26; j++) { // rightEyebrow face.rightEyebrow.addVertex(face.landmarks[j]); } for (int j=27; j<=30; j++) { // noseBridge face.noseBridge.addVertex(face.landmarks[j]); } for (int j=30; j<=35; j++) { // noseTip face.noseTip.addVertex(face.landmarks[j]); } face.noseTip.addVertex(face.landmarks[30]); face.noseTip.close(); for (int j=36; j<=41; j++) { // leftEye face.leftEye.addVertex(face.landmarks[j]); } face.leftEye.addVertex(face.landmarks[36]); face.leftEye.close(); face.leftEyeCenter = face.leftEye.getCentroid2D(); for (int j=42; j<=47; j++) { // rightEye face.rightEye.addVertex(face.landmarks[j]); } face.rightEye.addVertex(face.landmarks[42]); face.rightEye.close(); face.rightEyeCenter = face.rightEye.getCentroid2D(); for (int j=48; j<=59; j++) { // outerMouth face.outerMouth.addVertex(face.landmarks[j]); } face.outerMouth.addVertex(face.landmarks[48]); face.outerMouth.close(); for (int j=60; j<=67; j++) { // innerMouth face.innerMouth.addVertex(face.landmarks[j]); } face.innerMouth.addVertex(face.landmarks[60]); face.innerMouth.close(); } shapeHistory[label] = currentLandmarks; faces.push_back(face); std::map<unsigned int, vector<ofVec3f>>::iterator shapeHistoryItr = shapeHistory.begin(); while(shapeHistoryItr != shapeHistory.end()) { unsigned int label = shapeHistoryItr->first; if(!tracker.existsCurrent(label)) { shapeHistory.erase(shapeHistoryItr++); smoothingRatePerFace.erase(label); // dirty but should do it for now } else { ++shapeHistoryItr; } } } } //-------------------------------------------------------------- unsigned int FaceTracker::size() { return faces.size(); } //-------------------------------------------------------------- RectTracker & FaceTracker::getTracker() { return tracker; } //-------------------------------------------------------------- Face FaceTracker::getFace(unsigned int i) { return faces[i]; } //-------------------------------------------------------------- vector<Face> & FaceTracker::getFaces() { return faces; } //-------------------------------------------------------------- ofRectangle FaceTracker::getRectangle(unsigned int i) { return faces[i].rect; } //-------------------------------------------------------------- vector<ofVec3f> FaceTracker::getLandmarks(unsigned int i) { return faces[i].landmarks; } ofPolyline FaceTracker::getShape(unsigned int i, ShapeType t) { Face face = faces[i]; ofPolyline out; switch (t) { case leftEye: out = face.leftEye; break; case rightEye: out = face.rightEye; break; case innerMouth: out = face.innerMouth; break; case outerMouth: out = face.outerMouth; break; case leftEyebrow: out = face.leftEyebrow; break; case rightEyebrow: out = face.rightEyebrow; break; case jaw: out = face.jaw; break; case noseBridge: out = face.noseBridge; break; case noseTip: out = face.noseTip; break; default: break; } return out; } //-------------------------------------------------------------- unsigned int FaceTracker::getLabel(unsigned int i) { return faces[i].label; } //-------------------------------------------------------------- int FaceTracker::getIndexFromLabel(unsigned int label) { int index = -1; for (int i=0; i<faces.size(); i++) { if (faces[i].label == label) { index = i; break; } } return index; } //-------------------------------------------------------------- ofVec2f FaceTracker::getVelocity(unsigned int i) { return faces[i].velocity; } //-------------------------------------------------------------- void FaceTracker::setSmoothingRate(float smoothingRate) { this->smoothingRate = smoothingRate; tracker.setSmoothingRate(smoothingRate); } //-------------------------------------------------------------- void FaceTracker::setSmoothingRate(unsigned int label, float smoothingRate) { if (smoothingRatePerFace.count(label) > 0) { smoothingRatePerFace[label] = smoothingRate; } } //-------------------------------------------------------------- float FaceTracker::getSmoothingRate() { return smoothingRate; } //-------------------------------------------------------------- float FaceTracker::getSmoothingRate(unsigned int label) { if (smoothingRatePerFace.count(label) > 0) { return smoothingRatePerFace[label]; } else { return 1.0; } } //-------------------------------------------------------------- void FaceTracker::setDrawStyle(DrawStyle style) { this->drawStyle = style; } //-------------------------------------------------------------- void FaceTracker::draw() { ofPushStyle(); ofSetColor(ofColor::red); ofNoFill(); for (auto & face : faces) { ofDrawBitmapString(ofToString(face.label), face.rect.getTopLeft()); ofDrawRectangle(face.rect); switch (drawStyle) { case lines: face.leftEye.draw(); face.rightEye.draw(); face.innerMouth.draw(); face.outerMouth.draw(); face.leftEyebrow.draw(); face.rightEyebrow.draw(); face.jaw.draw(); face.noseBridge.draw(); face.noseTip.draw(); break; case circles: for (auto & landmark : face.landmarks) { ofDrawCircle(landmark, 3); } break; case none: break; } } ofPopStyle(); }
31.381443
97
0.491568
[ "shape", "vector" ]
db7344d6d79de6b002adf67f2d9813c1bf9cbe50
4,754
cc
C++
lite/core/optimizer/mir/fusion/keepdims_convert_fuser.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
808
2018-04-17T17:43:12.000Z
2019-08-18T07:39:13.000Z
lite/core/optimizer/mir/fusion/keepdims_convert_fuser.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
728
2018-04-18T08:15:25.000Z
2019-08-16T07:14:43.000Z
lite/core/optimizer/mir/fusion/keepdims_convert_fuser.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
364
2018-04-18T17:05:02.000Z
2019-08-18T03:25:38.000Z
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/core/optimizer/mir/fusion/keepdims_convert_fuser.h" #include <memory> #include <vector> namespace paddle { namespace lite { namespace mir { namespace fusion { void KeepdimsConvertFuser::BuildPattern() { // create input nodes auto* input = VarNode("input")->assert_is_op_input(op_type_, "X")->AsInput(); // create intermediate nodes // create op nodes auto attr_names = attr_names_; auto op_teller = [&](const Node* node) -> bool { const std::vector<std::string> attr_names{"keep_dim", "keepdims"}; // Convert false to true when the above attribute exists and it's false. // Note the attribute is false by default when the attribute doesn't exist. auto* op_desc = const_cast<Node*>(node)->AsStmt().op_info(); for (auto attr_name : attr_names) { if (op_desc->HasAttr(attr_name)) { if (op_desc->GetAttr<bool>(attr_name)) { return false; } } } return true; }; auto* op = OpNode("op", op_type_) ->assert_is_op(op_type_) ->assert_node_satisfied(op_teller); // create output node auto* output = VarNode("output")->assert_is_op_output(op_type_, "Out")->AsOutput(); // create topology *input >> *op >> *output; } void KeepdimsConvertFuser::InsertNewNode(SSAGraph* graph, const key2nodes_t& matched) { auto* inst = matched.at("op")->stmt(); auto new_op_desc = GenOpDesc(matched); auto new_op = LiteOpRegistry::Global().Create("reshape"); auto op = inst->op(); auto* scope = op->scope(); auto& valid_places = op->valid_places(); new_op->Attach(new_op_desc, scope); auto* new_op_node = graph->GraphCreateInstructNode(new_op, valid_places); auto outlinks_num = matched.at("op")->outlinks.size(); CHECK_EQ(outlinks_num, 1L) << "outlinks num should be 1, but got " << outlinks_num; auto* in = matched.at("op")->outlinks.front(); auto* new_input_arg = graph->NewArgumentNode(new_input_name_); const Type& from = *in->AsArg().type; new_input_arg->AsArg().type = LiteType::GetTensorTy(from.target(), from.precision(), from.layout()); // Set keepdims/keep_dim attribute to true // Update Out arg name auto op_desc = inst->mutable_op_info(); for (auto attr_name : attr_names_) { op_desc->SetAttr(attr_name, true); op_desc->SetOutput("Out", {new_input_name_}); } IR_NODE_LINK_TO(matched.at("op"), new_input_arg); IR_NODE_LINK_TO(new_input_arg, new_op_node); IR_NODE_LINK_TO(new_op_node, matched.at("output")); // Remove the old link RemoveDirectedLink(matched.at("op"), matched.at("output")); } cpp::OpDesc KeepdimsConvertFuser::GenOpDesc(const key2nodes_t& matched) { auto* inst = matched.at("op")->stmt(); // Create the new var manually auto* in = matched.at("op")->outlinks.front(); new_input_name_ = string_format("%s/trans", in->AsArg().name.c_str()); inst->op()->scope()->Var(new_input_name_); cpp::OpDesc op_desc; op_desc.SetType("reshape"); op_desc.SetInput("X", {new_input_name_}); op_desc.SetOutput("Out", {matched.at("output")->arg()->name}); op_desc.SetAttr("shape", GetTensorDims(inst)); return op_desc; } std::vector<int> KeepdimsConvertFuser::GetTensorDims(const Node::Stmt* inst) { const auto op = inst->op(); const auto* op_info = inst->op_info(); auto var_names = op_info->output_names(); CHECK_EQ(var_names.size(), 1); std::string var_name = var_names[0]; auto* scope = op->scope(); auto* var = scope->FindVar(var_name); if (var == nullptr) { LOG(FATAL) << "var is nullptr! var_name: " << var_name; } const auto& tensor = var->Get<Tensor>(); VLOG(4) << "tensor dims: " << tensor.dims(); std::vector<int> dims; // Out dims may be empty. For example, argmax's in dims{3}, keepdims=false, // axis=0. // Set out dims manually. if (tensor.dims().empty()) { dims.push_back(1); } else { for (auto iter : tensor.dims().Vectorize()) { dims.push_back(iter); } } return dims; } } // namespace fusion } // namespace mir } // namespace lite } // namespace paddle
33.013889
79
0.667017
[ "shape", "vector" ]
db778c16812e7d12003f2b07900f253dd31faa7b
4,997
hpp
C++
src/sage/modular/arithgroup/farey.hpp
bopopescu/classic_diff_geom
2b1d88becbc8cb30962e0995cc78e429e0f5589f
[ "BSL-1.0" ]
5
2015-01-04T07:15:06.000Z
2022-03-04T15:15:18.000Z
src/sage/modular/arithgroup/farey.hpp
bopopescu/classic_diff_geom
2b1d88becbc8cb30962e0995cc78e429e0f5589f
[ "BSL-1.0" ]
null
null
null
src/sage/modular/arithgroup/farey.hpp
bopopescu/classic_diff_geom
2b1d88becbc8cb30962e0995cc78e429e0f5589f
[ "BSL-1.0" ]
10
2016-09-28T13:12:40.000Z
2022-02-12T09:28:34.000Z
// // farey.hpp // FareySymbol // //************************************************************************* // Copyright (C) 2011 Hartmut Monien <monien@th.physik.uni-bonn.de> // // Distributed under the terms of the GNU General Public License (GPL) // // This code 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. // // The full text of the GPL is available at: // // http://www.gnu.org/licenses/ //************************************************************************* #ifndef FAREY_SYMBOL_HPP_ #define FAREY_SYMBOL_HPP_ #include <iostream> #include <vector> #include <string> #include <Python.h> #include <gmpxx.h> #include "sl2z.hpp" //--- pure virtual base class for helper class for membership test -------- class is_element_group { public: virtual bool is_member(const SL2Z&) const = 0; }; class is_element_Gamma0 : public is_element_group { const int p; public: is_element_Gamma0(int p_) : p(p_) { } bool is_member(const SL2Z& V) const { return (V.c() % p == 0); } }; class is_element_Gamma1 : public is_element_group { const int p; public: is_element_Gamma1(int p_) : p(p_) { } bool is_member(const SL2Z& V) const { return ((V.a()-1) % p == 0 && V.c() % p == 0 && (V.d()-1) % p == 0); } }; class is_element_Gamma : public is_element_group { const int p; public: is_element_Gamma(int p_) : p(p_) { } bool is_member(const SL2Z& V) const { return ((V.a()-1) % p == 0 && V.b() % p == 0 && V.c() % p == 0 && (V.d()-1) % p == 0); } }; class is_element_GammaH : public is_element_group { const int p; std::vector<long> H; public: is_element_GammaH(int p_, PyObject*); ~is_element_GammaH(); bool is_member(const SL2Z&) const; }; class is_element_general : public is_element_group { protected: PyObject* group; PyObject* method; public: is_element_general(PyObject*); virtual ~is_element_general(); bool is_member(const SL2Z&) const; }; class FareySymbol { protected: enum PAIRING { EVEN=-2, ODD=-3, NO=0, FREE=1 }; size_t pairing_max; std::vector<int> pairing; std::vector<int> cusp_classes; std::vector<mpz_class> a, b; std::vector<mpq_class> x; std::vector<SL2Z> coset; std::vector<SL2Z> generators; std::vector<mpq_class> cusps; std::vector<mpq_class> cusp_widths; std::vector<SL2Z> reductions; bool even; std::vector<bool> pairing_in_group; // For membership test: //Is the i-th pairing matrix in the group? size_t rank_pi() const; long side_index(const mpz_class& a0, const mpz_class& b0, const mpz_class& a1, const mpz_class& b1) const; void LLT_algorithm(const SL2Z& M, std::vector<int>& p, SL2Z& beta) const; void dump(std::ostream& os) const; std::vector<SL2Z> init_reductions() const; private: void add_term(const int, const mpq_class&); void check_pair(const is_element_group*, const int); size_t paired_side(const std::vector<int>& p, const size_t i) const; SL2Z pairing_matrix(const std::vector<int>&, const size_t i) const; void init_pairing(const is_element_group*); std::vector<SL2Z> init_generators(const is_element_group*) const; std::vector<SL2Z> init_coset_reps() const; std::vector<int> init_cusp_classes() const; std::vector<mpq_class> init_cusps() const; std::vector<mpq_class> init_cusp_widths() const; SL2Z pairing_matrix(const size_t) const; SL2Z pairing_matrix_in_group(const size_t) const; std::vector<bool> init_sl2z_lift(const is_element_group*) const; public: FareySymbol(); FareySymbol(std::istream& is); FareySymbol(PyObject*); FareySymbol(PyObject*, const is_element_group*); ~FareySymbol(); const size_t size() const; size_t nu2() const; size_t nu3() const; size_t index() const; size_t number_of_cusps() const; size_t level() const; size_t genus() const; SL2Z reduce_to_fraction(const mpq_class& q) const; SL2Z reduce_to_elementary_cusp(const mpq_class& q) const; size_t cusp_class(const mpq_class& q) const; bool is_element(const SL2Z& M) const; friend std::ostream& operator<<(std::ostream&, const FareySymbol&); friend std::istream& operator>>(std::istream&, FareySymbol&); //--- communication with sage ------------------------------------------- PyObject* is_element(const mpz_t, const mpz_t, const mpz_t, const mpz_t) const; PyObject* get_transformation_to_cusp(const mpz_t, const mpz_t) const; PyObject* get_cusps() const; PyObject* get_cusp_widths() const; size_t get_cusp_class(const mpz_t, const mpz_t) const; PyObject* get_fractions() const; PyObject* get_coset() const; PyObject* get_generators() const; PyObject* get_pairings() const; PyObject* get_paired_sides() const; PyObject* get_pairing_matrices() const; PyObject* dumps() const; }; #endif // FAREY_SYMBOL_HPP_
30.469512
81
0.668801
[ "vector" ]
db780abd9d864db8fe85de3ba3c1ff3f59646c3e
37,715
cpp
C++
darkness-engine/private-src/engine/graphics/vulkan/VulkanPipeline.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
6
2019-10-17T11:31:55.000Z
2022-02-11T08:51:20.000Z
darkness-engine/private-src/engine/graphics/vulkan/VulkanPipeline.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
1
2020-08-11T09:01:29.000Z
2020-08-11T09:01:29.000Z
darkness-engine/private-src/engine/graphics/vulkan/VulkanPipeline.cpp
Karmiska/Darkness
c87eaf067a2707a0141909125ff461f69a3812e0
[ "MIT" ]
1
2020-06-02T15:48:20.000Z
2020-06-02T15:48:20.000Z
#include "engine/graphics/vulkan/VulkanPipeline.h" #include "engine/graphics/vulkan/VulkanHeaders.h" #include "engine/graphics/vulkan/VulkanShaderBinary.h" #include "engine/graphics/vulkan/VulkanConversions.h" #include "engine/graphics/vulkan/VulkanRootSignature.h" #include "engine/graphics/vulkan/VulkanRootParameter.h" #include "engine/graphics/vulkan/VulkanDevice.h" #include "engine/graphics/vulkan/VulkanSwapChain.h" #include "engine/graphics/vulkan/VulkanResources.h" #include "engine/graphics/vulkan/VulkanCommandList.h" #include "engine/graphics/vulkan/VulkanDescriptorHandle.h" #include "engine/graphics/vulkan/VulkanDescriptorHeap.h" #include "engine/graphics/ShaderBinary.h" #include "engine/graphics/Pipeline.h" #include "engine/graphics/RootSignature.h" #include "engine/graphics/Device.h" #include "engine/graphics/SwapChain.h" #include "engine/graphics/Resources.h" #include "engine/graphics/Sampler.h" #include "engine/graphics/CommandList.h" #include "shaders/ShaderTypes.h" #include "spirv_cross.hpp" #include "tools/Debug.h" #include "shaders/ShaderTypes.h" #include <array> namespace engine { namespace implementation { PipelineImpl::PipelineImpl( Device& device, shaders::PipelineConfiguration* configuration, ShaderStorage& storage) : m_device{ device } , m_pipelineState{ nullptr } , m_pipelineStateDesc{ nullptr } , m_configuration{ configuration } , m_vertexShader{ configuration->hasVertexShader() ? configuration->vertexShader()->load(device, storage) : nullptr } , m_pixelShader{ configuration->hasPixelShader() ? configuration->pixelShader()->load(device, storage) : nullptr } , m_geometryShader{ configuration->hasGeometryShader() ? configuration->geometryShader()->load(device, storage) : nullptr } , m_hullShader{ configuration->hasHullShader() ? configuration->hullShader()->load(device, storage) : nullptr } , m_domainShader{ configuration->hasDomainShader() ? configuration->domainShader()->load(device, storage) : nullptr } , m_computeShader{ configuration->hasComputeShader() ? configuration->computeShader()->load(device, storage) : nullptr } , m_vertShaderStageInfo{ nullptr } , m_fragShaderStageInfo{ nullptr } , m_geometryShaderStageInfo{ nullptr } , m_computeShaderStageInfo{ nullptr } , m_domainShaderStageInfo{ nullptr } , m_hullShaderStageInfo{ nullptr } , m_inputAssembly{} , m_viewport{} , m_scissor{} , m_rasterizer{} , m_multisampling{} , m_colorBlendAttachement{} , m_colorBlending{} , m_pipelineLayoutInfo{} , m_colorAttachement{} , m_colorAttachmentRef{} , m_depthAttachment{} , m_depthAttachmentRef{} , m_subPass{} , m_dependency{} , m_renderPassInfo{} , m_pipelineLayout{ vulkanPtr<VkPipelineLayout>(DeviceImplGet::impl(device).device(), vkDestroyPipelineLayout) } , m_renderPass{ vulkanPtr<VkRenderPass>(DeviceImplGet::impl(device).device(), vkDestroyRenderPass) } , m_pipeline{ vulkanPtr<VkPipeline>(DeviceImplGet::impl(device).device(), vkDestroyPipeline) } , m_depthBufferView{} { /*auto swapChain = m_device.currentSwapChain().lock(); ASSERT(swapChain); m_viewport = { 0.0f, 0.0f, static_cast<float>(SwapChainImplGet::impl(*swapChain).extent().width), static_cast<float>(SwapChainImplGet::impl(*swapChain).extent().height), 0.0f, 1.0f }; m_scissor = { { 0, 0 }, SwapChainImplGet::impl(*swapChain).extent() };*/ LOG("Check viewport and scissor settings"); m_rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; m_rasterizer.depthClampEnable = VK_FALSE; m_rasterizer.rasterizerDiscardEnable = VK_FALSE; m_rasterizer.polygonMode = VK_POLYGON_MODE_FILL; m_rasterizer.lineWidth = 1.0f; m_rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; m_rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; //m_rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; m_rasterizer.depthBiasEnable = VK_FALSE; m_rasterizer.depthBiasConstantFactor = 0.0f; m_rasterizer.depthBiasClamp = 0.0f; m_rasterizer.depthBiasSlopeFactor = 0.0f; m_multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; m_multisampling.sampleShadingEnable = VK_FALSE; m_multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; m_multisampling.minSampleShading = 1.0f; m_multisampling.pSampleMask = nullptr; m_multisampling.alphaToCoverageEnable = VK_FALSE; m_multisampling.alphaToOneEnable = VK_FALSE; m_colorBlendAttachement.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; m_colorBlendAttachement.blendEnable = VK_FALSE; m_colorBlendAttachement.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; m_colorBlendAttachement.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; m_colorBlendAttachement.colorBlendOp = VK_BLEND_OP_ADD; m_colorBlendAttachement.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; m_colorBlendAttachement.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; m_colorBlendAttachement.alphaBlendOp = VK_BLEND_OP_ADD; m_colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; m_colorBlending.logicOpEnable = VK_FALSE; m_colorBlending.logicOp = VK_LOGIC_OP_COPY; m_colorBlending.attachmentCount = 1; m_colorBlending.pAttachments = &m_colorBlendAttachement; m_colorBlending.blendConstants[0] = 0.0f; m_colorBlending.blendConstants[1] = 0.0f; m_colorBlending.blendConstants[2] = 0.0f; m_colorBlending.blendConstants[3] = 0.0f; // dynamic stuff. that can change midflight with pipeline /*VkDynamicState dynamicStates[] = { VK_DYNAMIC_STATE_VIEWPORT }; VkPipelineDynamicStateCreateInfo dynamicState = {}; dynamicState.dynamicStateCount = 1; dynamicState.pDynamicStates = dynamicStates;*/ m_pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; m_pipelineLayoutInfo.setLayoutCount = 0; m_pipelineLayoutInfo.pSetLayouts = nullptr; m_pipelineLayoutInfo.pushConstantRangeCount = 0; m_pipelineLayoutInfo.pPushConstantRanges = nullptr; //m_colorAttachement.format = SwapChainImplGet::impl(*swapChain).surfaceFormat().format; m_colorAttachement.format = VK_FORMAT_B8G8R8A8_UNORM; m_colorAttachement.samples = VK_SAMPLE_COUNT_1_BIT; m_colorAttachement.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; m_colorAttachement.storeOp = VK_ATTACHMENT_STORE_OP_STORE; m_colorAttachement.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; m_colorAttachement.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; m_colorAttachement.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; m_colorAttachement.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; m_colorAttachmentRef.attachment = 0; m_colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; m_depthAttachment.format = vulkanFormat(Format::D32_FLOAT); m_depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT; m_depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; m_depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; m_depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; m_depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; m_depthAttachment.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; m_depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; m_depthAttachmentRef.attachment = 1; m_depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; m_dependency.srcSubpass = VK_SUBPASS_EXTERNAL; m_dependency.dstSubpass = 0; m_dependency.srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; m_dependency.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; m_dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; m_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } void PipelineImpl::createRootSignature() { #if 0 InputElementDescription vertDesc; vertDesc.alignedByteOffset(sizeof(Vertex)) .format(Format::R32G32B32_FLOAT) .inputSlot(0) .inputSlotClass(InputClassification::PerVertexData) .offset(offsetof(Vertex, pos)); InputElementDescription colorDesc; colorDesc.alignedByteOffset(sizeof(Vertex)) .format(Format::R32G32B32_FLOAT) .inputSlot(0) .inputSlotClass(InputClassification::PerVertexData) .offset(offsetof(Vertex, color)); InputElementDescription uvDesc; uvDesc.alignedByteOffset(sizeof(Vertex)) .format(Format::R32G32_FLOAT) .inputSlot(0) .inputSlotClass(InputClassification::PerVertexData) .offset(offsetof(Vertex, texCoord)); m_pipelineDescriptions.emplace_back(vertDesc); m_pipelineDescriptions.emplace_back(colorDesc); m_pipelineDescriptions.emplace_back(uvDesc); setInputLayout(static_cast<unsigned int>( m_pipelineDescriptions.size()), m_pipelineDescriptions.data()); /*if (m_vertexShader) setVertexShader(*m_vertexShader); if (m_pixelShader) setPixelShader(*m_pixelShader); if (m_geometryShader) setGeometryShader(*m_geometryShader); if (m_hullShader) setHullShader(*m_hullShader); if (m_domainShader) setDomainShader(*m_domainShader); if (m_computeShader) setComputeShader(*m_computeShader);*/ m_rootSignature = std::make_shared<RootSignature>(m_device.createRootSignature()); RootSignature& rootSignature = *m_rootSignature; rootSignature.reset(2, 0); rootSignature[0].binding(0); rootSignature[0].descriptorType(DescriptorType::UniformBuffer); rootSignature[0].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Vertex)); rootSignature[1].binding(1); rootSignature[1].descriptorType(DescriptorType::CombinedImageSampler); rootSignature[1].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Pixel)); rootSignature.finalize(); setRootSignature(rootSignature); #endif } const VkDescriptorSet& PipelineImpl::descriptorSet() const { return m_uniform->native(); // m_descriptorSet } PipelineImpl::~PipelineImpl() { for (auto&& item : m_framebuffers) { vkDestroyFramebuffer(DeviceImplGet::impl(m_device).device(), item, nullptr); } if (m_pipelineStateDesc) { //delete m_pipelineStateDesc; m_pipelineStateDesc = nullptr; } if (m_pipelineState) { //m_pipelineState->Release(); m_pipelineState = nullptr; } } void PipelineImpl::setDepthBufferView(std::shared_ptr<TextureDSV> view) { m_depthBufferView = view; } void* PipelineImpl::native() const { return m_pipelineState; } void PipelineImpl::setRootSignature(const RootSignature& signature) { m_currentLayouts.clear(); m_currentLayouts.emplace_back(RootSignatureImplGet::impl(signature).layout()); m_pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; m_pipelineLayoutInfo.setLayoutCount = 1; m_pipelineLayoutInfo.pSetLayouts = m_currentLayouts.data(); } void PipelineImpl::setBlendState(const BlendDescription& /*desc*/) { // TODO } void PipelineImpl::setRasterizerState(const RasterizerDescription& desc) { m_rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; m_rasterizer.depthClampEnable = desc.desc.depthClipEnable ? static_cast<uint32_t>(VK_TRUE) : static_cast<uint32_t>(VK_FALSE); m_rasterizer.rasterizerDiscardEnable = VK_FALSE; m_rasterizer.polygonMode = vulkanFillMode(desc.desc.fillMode); m_rasterizer.lineWidth = 1.0f; m_rasterizer.cullMode = vulkanCullMode(desc.desc.cullMode); m_rasterizer.frontFace = desc.desc.frontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; m_rasterizer.depthBiasEnable = desc.desc.depthBias > 0 ? static_cast<uint32_t>(VK_TRUE) : static_cast<uint32_t>(VK_FALSE); m_rasterizer.depthBiasConstantFactor = 0.0f; m_rasterizer.depthBiasClamp = desc.desc.depthBiasClamp; m_rasterizer.depthBiasSlopeFactor = desc.desc.slopeScaledDepthBias; m_multisampling.sampleShadingEnable = desc.desc.multisampleEnable ? static_cast<uint32_t>(VK_TRUE) : static_cast<uint32_t>(VK_FALSE); } void PipelineImpl::setDepthStencilState(const DepthStencilDescription& /*desc*/) { // TODO } void PipelineImpl::setSampleMask(unsigned int /*mask*/) { // TODO } void PipelineImpl::setPrimitiveTopologyType(PrimitiveTopologyType type, bool adjacency) { m_inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; m_inputAssembly.topology = vulkanPrimitiveTopologyType(type); m_inputAssembly.primitiveRestartEnable = VK_FALSE; } void PipelineImpl::setRenderTargetFormat(Format RTVFormat, Format DSVFormat, unsigned int msaaCount, unsigned int msaaQuality) { setRenderTargetFormats({ RTVFormat }, DSVFormat, msaaCount, msaaQuality); } void PipelineImpl::setRenderTargetFormats(std::vector<Format> RTVFormats, Format /*DSVFormat*/, unsigned int /*msaaCount*/, unsigned int /*msaaQuality*/) { // Null format array conflicts with non-zero length /*for (UINT i = 0; i < numRTVs; ++i) m_pipelineStateDesc->RTVFormats[i] = dxFormat(RTVFormats[i]); for (UINT i = numRTVs; i < m_pipelineStateDesc->NumRenderTargets; ++i) m_pipelineStateDesc->RTVFormats[i] = DXGI_FORMAT_UNKNOWN; m_pipelineStateDesc->NumRenderTargets = numRTVs; m_pipelineStateDesc->DSVFormat = dxFormat(DSVFormat); m_pipelineStateDesc->SampleDesc.Count = msaaCount; m_pipelineStateDesc->SampleDesc.Quality = msaaQuality;*/ } void PipelineImpl::setInputLayout(unsigned int numElements, const InputElementDescription* inputElementDescs) { m_bindings.resize(1); m_bindingAttributes.resize(numElements); for (uint32_t i = 0; i < numElements; ++i) { if (i == 0) { m_bindings[i].binding = i; m_bindings[i].stride = inputElementDescs[i].desc.alignedByteOffset; m_bindings[i].inputRate = vulkanInputClassification(inputElementDescs[i].desc.inputSlotClass); // VK_VERTEX_INPUT_RATE_INSTANCE } m_bindingAttributes[i].binding = inputElementDescs[i].desc.inputSlot; m_bindingAttributes[i].format = vulkanFormat(inputElementDescs[i].desc.format); m_bindingAttributes[i].location = i; m_bindingAttributes[i].offset = inputElementDescs[i].desc.offset; } } void PipelineImpl::setPrimitiveRestart(IndexBufferStripCutValue /*value*/) { // TODO } void PipelineImpl::setVertexShader(const ShaderBinary& shaderBinary) { /*auto trColor = TriangleColor(); auto inst = trColor->construct(); auto res = inst->resources; spirv_cross::Compiler compiler(ShaderBinaryImplGet::impl(shaderBinary).data()); spirv_cross::ShaderResources resources = compiler.get_shader_resources(); for (auto &resource : resources.sampled_images) { unsigned set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); unsigned binding = compiler.get_decoration(resource.id, spv::DecorationBinding); //add_sampled_image_to_layout(set, binding); }*/ m_vertShaderStageInfo = std::make_unique<VkPipelineShaderStageCreateInfo>(); m_vertShaderStageInfo->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; m_vertShaderStageInfo->stage = VK_SHADER_STAGE_VERTEX_BIT; m_vertShaderStageInfo->module = ShaderBinaryImplGet::impl(shaderBinary).native(); m_vertShaderStageInfo->pName = "main"; m_vertShaderStageInfo->pSpecializationInfo = nullptr; // this can be used to add defines and such } void PipelineImpl::setPixelShader(const ShaderBinary& shaderBinary) { /*spirv_cross::Compiler compiler(ShaderBinaryImplGet::impl(shaderBinary).data()); spirv_cross::ShaderResources resources = compiler.get_shader_resources(); for (auto &resource : resources.sampled_images) { unsigned set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); unsigned binding = compiler.get_decoration(resource.id, spv::DecorationBinding); //add_sampled_image_to_layout(set, binding); }*/ m_fragShaderStageInfo = std::make_unique<VkPipelineShaderStageCreateInfo>(); m_fragShaderStageInfo->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; m_fragShaderStageInfo->stage = VK_SHADER_STAGE_FRAGMENT_BIT; m_fragShaderStageInfo->module = ShaderBinaryImplGet::impl(shaderBinary).native(); m_fragShaderStageInfo->pName = "main"; m_fragShaderStageInfo->pSpecializationInfo = nullptr; // this can be used to add defines and such } void PipelineImpl::setGeometryShader(const ShaderBinary& shaderBinary) { m_geometryShaderStageInfo = std::make_unique<VkPipelineShaderStageCreateInfo>(); m_geometryShaderStageInfo->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; m_geometryShaderStageInfo->stage = VK_SHADER_STAGE_GEOMETRY_BIT; m_geometryShaderStageInfo->module = ShaderBinaryImplGet::impl(shaderBinary).native(); m_geometryShaderStageInfo->pName = "main"; m_geometryShaderStageInfo->pSpecializationInfo = nullptr; } void PipelineImpl::setHullShader(const ShaderBinary& shaderBinary) { m_hullShaderStageInfo = std::make_unique<VkPipelineShaderStageCreateInfo>(); m_hullShaderStageInfo->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; m_hullShaderStageInfo->stage = VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT; m_hullShaderStageInfo->module = ShaderBinaryImplGet::impl(shaderBinary).native(); m_hullShaderStageInfo->pName = "main"; m_hullShaderStageInfo->pSpecializationInfo = nullptr; } void PipelineImpl::setDomainShader(const ShaderBinary& shaderBinary) { m_domainShaderStageInfo = std::make_unique<VkPipelineShaderStageCreateInfo>(); m_domainShaderStageInfo->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; m_domainShaderStageInfo->stage = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT; m_domainShaderStageInfo->module = ShaderBinaryImplGet::impl(shaderBinary).native(); m_domainShaderStageInfo->pName = "main"; m_domainShaderStageInfo->pSpecializationInfo = nullptr; } void PipelineImpl::setComputeShader(const ShaderBinary& shaderBinary) { m_computeShaderStageInfo = std::make_unique<VkPipelineShaderStageCreateInfo>(); m_computeShaderStageInfo->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; m_computeShaderStageInfo->stage = VK_SHADER_STAGE_COMPUTE_BIT; m_computeShaderStageInfo->module = ShaderBinaryImplGet::impl(shaderBinary).native(); m_computeShaderStageInfo->pName = "main"; m_computeShaderStageInfo->pSpecializationInfo = nullptr; } void PipelineImpl::configure(CommandListImpl& commandList, shaders::PipelineConfiguration* configuration) { //m_colorAttachement.format = SwapChainImplGet::impl(*swapChain).surfaceFormat().format; } void PipelineImpl::finalize() { /*InputElementDescription vertDesc; vertDesc.alignedByteOffset(sizeof(Vertex)) .format(Format::R32G32B32_FLOAT) .inputSlot(0) .inputSlotClass(InputClassification::PerVertexData) .offset(offsetof(Vertex, pos)); InputElementDescription colorDesc; colorDesc.alignedByteOffset(sizeof(Vertex)) .format(Format::R32G32B32_FLOAT) .inputSlot(0) .inputSlotClass(InputClassification::PerVertexData) .offset(offsetof(Vertex, color)); InputElementDescription uvDesc; uvDesc.alignedByteOffset(sizeof(Vertex)) .format(Format::R32G32_FLOAT) .inputSlot(0) .inputSlotClass(InputClassification::PerVertexData) .offset(offsetof(Vertex, texCoord)); m_pipelineDescriptions.emplace_back(vertDesc); m_pipelineDescriptions.emplace_back(colorDesc); m_pipelineDescriptions.emplace_back(uvDesc); setInputLayout(static_cast<unsigned int>( m_pipelineDescriptions.size()), m_pipelineDescriptions.data());*/ size_t vsTexSrvCount = 0; size_t vsTexUavCount = 0; size_t vsBufSrvCount = 0; size_t vsBufUavCount = 0; size_t vsSamplerCount = 0; size_t psTexSrvCount = 0; size_t psTexUavCount = 0; size_t psBufSrvCount = 0; size_t psBufUavCount = 0; size_t psSamplerCount = 0; if (m_configuration->hasVertexShader()) { setVertexShader(*m_vertexShader); vsTexSrvCount = m_configuration->vertexShader()->texture_srvs().size(); vsTexUavCount = m_configuration->vertexShader()->texture_uavs().size(); vsBufSrvCount = m_configuration->vertexShader()->buffer_srvs().size(); vsBufUavCount = m_configuration->vertexShader()->buffer_uavs().size(); vsSamplerCount = m_configuration->vertexShader()->samplers().size(); } if (m_configuration->hasPixelShader()) { setPixelShader(*m_pixelShader); psTexSrvCount = m_configuration->pixelShader()->texture_srvs().size(); psTexUavCount = m_configuration->pixelShader()->texture_uavs().size(); psBufSrvCount = m_configuration->pixelShader()->buffer_srvs().size(); psBufUavCount = m_configuration->pixelShader()->buffer_uavs().size(); psSamplerCount = m_configuration->vertexShader()->samplers().size(); } if (m_configuration->hasGeometryShader()) setGeometryShader(*m_geometryShader); if (m_configuration->hasHullShader()) setHullShader(*m_hullShader); if (m_configuration->hasDomainShader()) setDomainShader(*m_domainShader); if (m_configuration->hasComputeShader()) setComputeShader(*m_computeShader); size_t resourceCount = vsTexSrvCount + vsTexUavCount + vsBufSrvCount + vsBufUavCount + vsSamplerCount + psTexSrvCount + psTexUavCount + psBufSrvCount + psBufUavCount + psSamplerCount; m_rootSignature = std::make_shared<RootSignature>(m_device.createRootSignature()); RootSignature& rootSignature = *m_rootSignature; rootSignature.reset(static_cast<int>(resourceCount), 0); uint32_t currentIndex = 0; for (auto&& res : m_configuration->vertexShader()->texture_srvs()) { rootSignature[currentIndex].binding(currentIndex); RootParameterImplGet::impl(rootSignature[currentIndex]).descriptorType(DescriptorType::StorageImage); rootSignature[currentIndex].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Vertex)); ++currentIndex; } for (auto&& res : m_configuration->vertexShader()->texture_uavs()) { rootSignature[currentIndex].binding(currentIndex); RootParameterImplGet::impl(rootSignature[currentIndex]).descriptorType(DescriptorType::StorageImage); rootSignature[currentIndex].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Vertex)); ++currentIndex; } for (auto&& res : m_configuration->vertexShader()->buffer_srvs()) { rootSignature[currentIndex].binding(currentIndex); RootParameterImplGet::impl(rootSignature[currentIndex]).descriptorType(DescriptorType::UniformTexelBuffer); rootSignature[currentIndex].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Vertex)); ++currentIndex; } for (auto&& res : m_configuration->vertexShader()->buffer_uavs()) { rootSignature[currentIndex].binding(currentIndex); RootParameterImplGet::impl(rootSignature[currentIndex]).descriptorType(DescriptorType::UniformTexelBuffer); rootSignature[currentIndex].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Vertex)); ++currentIndex; } for (auto&& res : m_configuration->pixelShader()->texture_srvs()) { rootSignature[currentIndex].binding(currentIndex); RootParameterImplGet::impl(rootSignature[currentIndex]).descriptorType(DescriptorType::StorageImage); rootSignature[currentIndex].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Pixel)); ++currentIndex; } for (auto&& res : m_configuration->pixelShader()->texture_uavs()) { rootSignature[currentIndex].binding(currentIndex); RootParameterImplGet::impl(rootSignature[currentIndex]).descriptorType(DescriptorType::StorageImage); rootSignature[currentIndex].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Pixel)); ++currentIndex; } for (auto&& res : m_configuration->pixelShader()->buffer_srvs()) { rootSignature[currentIndex].binding(currentIndex); RootParameterImplGet::impl(rootSignature[currentIndex]).descriptorType(DescriptorType::UniformTexelBuffer); rootSignature[currentIndex].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Pixel)); ++currentIndex; } for (auto&& res : m_configuration->pixelShader()->buffer_uavs()) { rootSignature[currentIndex].binding(currentIndex); RootParameterImplGet::impl(rootSignature[currentIndex]).descriptorType(DescriptorType::UniformTexelBuffer); rootSignature[currentIndex].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Pixel)); ++currentIndex; } /*rootSignature[0].binding(0); rootSignature[0].descriptorType(DescriptorType::UniformBuffer); rootSignature[0].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Vertex)); rootSignature[1].binding(1); rootSignature[1].descriptorType(DescriptorType::CombinedImageSampler); rootSignature[1].visibility(static_cast<ShaderVisibility>(ShaderVisibilityBits::Pixel));*/ rootSignature.finalize(); setRootSignature(rootSignature); m_subPass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; m_subPass.colorAttachmentCount = 1; m_subPass.pColorAttachments = &m_colorAttachmentRef; if (m_depthBufferView) m_subPass.pDepthStencilAttachment = &m_depthAttachmentRef; else m_subPass.pDepthStencilAttachment = nullptr; m_attachments.emplace_back(m_colorAttachement); if (m_depthBufferView) m_attachments.emplace_back(m_depthAttachment); m_renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; m_renderPassInfo.attachmentCount = static_cast<uint32_t>(m_attachments.size()); m_renderPassInfo.pAttachments = m_attachments.data(); m_renderPassInfo.subpassCount = 1; m_renderPassInfo.pSubpasses = &m_subPass; //m_renderPassInfo.dependencyCount = 1; //m_renderPassInfo.pDependencies = &m_dependency; //VkPipelineShaderStageCreateInfo shaderStages[] = { *m_vertShaderStageInfo.get(), *m_fragShaderStageInfo.get() }; std::vector<VkPipelineShaderStageCreateInfo> shaderStages; if (m_configuration->hasVertexShader()) shaderStages.emplace_back(*m_vertShaderStageInfo.get()); if (m_configuration->hasPixelShader()) shaderStages.emplace_back(*m_fragShaderStageInfo.get()); if (m_configuration->hasGeometryShader()) shaderStages.emplace_back(*m_geometryShaderStageInfo.get()); if (m_configuration->hasComputeShader()) shaderStages.emplace_back(*m_computeShaderStageInfo.get()); if (m_configuration->hasDomainShader()) shaderStages.emplace_back(*m_domainShaderStageInfo.get()); if (m_configuration->hasHullShader()) shaderStages.emplace_back(*m_hullShaderStageInfo.get()); VkPipelineVertexInputStateCreateInfo vertexInputInfo = {}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(m_bindings.size()); vertexInputInfo.pVertexBindingDescriptions = m_bindings.size() > 0 ? m_bindings.data() : nullptr; vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(m_bindingAttributes.size()); vertexInputInfo.pVertexAttributeDescriptions = m_bindingAttributes.size() > 0 ? m_bindingAttributes.data() : nullptr; VkPipelineViewportStateCreateInfo viewportState = {}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &m_viewport; viewportState.scissorCount = 1; viewportState.pScissors = &m_scissor; auto result = vkCreatePipelineLayout( DeviceImplGet::impl(m_device).device(), &m_pipelineLayoutInfo, nullptr, m_pipelineLayout.get()); ASSERT(result == VK_SUCCESS); result = vkCreateRenderPass(DeviceImplGet::impl(m_device).device(), &m_renderPassInfo, nullptr, m_renderPass.get()); ASSERT(result == VK_SUCCESS); VkPipelineDepthStencilStateCreateInfo depthStencil = {}; depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depthStencil.depthTestEnable = VK_TRUE; depthStencil.depthWriteEnable = VK_TRUE; depthStencil.depthCompareOp = VK_COMPARE_OP_LESS; depthStencil.depthBoundsTestEnable = VK_FALSE; depthStencil.minDepthBounds = 0.0f; // Optional depthStencil.maxDepthBounds = 1.0f; // Optional depthStencil.stencilTestEnable = VK_FALSE; depthStencil.front = {}; // Optional depthStencil.back = {}; // Optional VkGraphicsPipelineCreateInfo pipelineInfo = {}; pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; pipelineInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineInfo.pStages = shaderStages.data(); pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &m_inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &m_rasterizer; pipelineInfo.pMultisampleState = &m_multisampling; pipelineInfo.pDepthStencilState = &depthStencil; pipelineInfo.pColorBlendState = &m_colorBlending; pipelineInfo.pDynamicState = nullptr; pipelineInfo.layout = *m_pipelineLayout; pipelineInfo.renderPass = *m_renderPass; pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; pipelineInfo.basePipelineIndex = -1; result = vkCreateGraphicsPipelines( DeviceImplGet::impl(m_device).device(), VK_NULL_HANDLE, // VkPipelineCache object 1, &pipelineInfo, nullptr, m_pipeline.get()); ASSERT(result == VK_SUCCESS); auto swapChain = m_device.currentSwapChain().lock(); ASSERT(swapChain); m_framebuffers.resize( SwapChainImplGet::impl(*swapChain).chainLength() // for some reason this causes framebuffer corruption. // so we're manually destroying the framebuffers in the destructor /*,vulkanPtr<VkFramebuffer>(DeviceImplGet::impl(m_device).device(), vkDestroyFramebuffer)*/ ); for (int i = 0; i < static_cast<int>(m_framebuffers.size()); ++i) { auto rtv = SwapChainImplGet::impl(*swapChain).renderTarget(i); std::vector<VkImageView> attachments; attachments.emplace_back(TextureRTVImplGet::impl(rtv)->native()); if (m_depthBufferView) attachments.emplace_back(TextureDSVImplGet::impl(*m_depthBufferView)->native()); VkFramebufferCreateInfo framebufferInfo = {}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = *m_renderPass; framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); framebufferInfo.pAttachments = attachments.data(); framebufferInfo.width = SwapChainImplGet::impl(*swapChain).extent().width; framebufferInfo.height = SwapChainImplGet::impl(*swapChain).extent().height; framebufferInfo.layers = 1; auto result = vkCreateFramebuffer(DeviceImplGet::impl(m_device).device(), &framebufferInfo, nullptr, &m_framebuffers[static_cast<size_t>(i)]); ASSERT(result == VK_SUCCESS); } //m_descriptorHeap = m_device.createDescriptorHeap({ DescriptorType::UniformTexelBuffer }); /*m_uniform = std::make_shared<DescriptorHandle>(m_descriptorHeap->allocate( *m_rootSignature, *m_configuration ));*/ } void PipelineImpl::setUniformBuffer(const Buffer& buffer) { m_uniformBuffers.emplace_back(std::move(buffer)); } void PipelineImpl::setTextureSRV(const TextureSRV& srv) { m_srvs.emplace_back(srv); } void PipelineImpl::setSampler(const Sampler& sampler) { m_samplers.emplace_back(sampler); } } }
49.821664
161
0.649821
[ "object", "vector" ]
db7830a92cca225b4a7f58b6e85e67c4144c5068
9,970
hpp
C++
dmc.contracts/eosio.system/include/eosio.system/eosio.system.hpp
JTNowitzki/dmchain_contract
2c0e17aa89426bf5b37b256126d7be60423113a4
[ "MIT" ]
2
2022-02-01T08:04:24.000Z
2022-02-09T11:22:02.000Z
dmc.contracts/eosio.system/include/eosio.system/eosio.system.hpp
JTNowitzki/dmchain_contract
2c0e17aa89426bf5b37b256126d7be60423113a4
[ "MIT" ]
1
2022-02-07T07:02:35.000Z
2022-02-07T07:02:35.000Z
dmc.contracts/eosio.system/include/eosio.system/eosio.system.hpp
JTNowitzki/dmchain_contract
2c0e17aa89426bf5b37b256126d7be60423113a4
[ "MIT" ]
1
2022-03-15T12:10:31.000Z
2022-03-15T12:10:31.000Z
/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eosio.system/native.hpp> #include <eosiolib/asset.hpp> #include <eosiolib/time.hpp> #include <eosiolib/privileged.hpp> #include <eosiolib/singleton.hpp> #include <eosio.system/exchange_state.hpp> #include <string> namespace eosiosystem { using eosio::asset; using eosio::block_timestamp; using eosio::const_mem_fun; using eosio::indexed_by; struct name_bid { account_name newname; account_name high_bidder; int64_t high_bid = 0; ///< negative high_bid == closed auction waiting to be claimed uint64_t last_bid_time = 0; auto primary_key() const { return newname; } uint64_t by_high_bid() const { return static_cast<uint64_t>(-high_bid); } }; struct bid_refund { account_name bidder; asset amount; auto primary_key() const { return bidder; } }; typedef eosio::multi_index<N(namebids), name_bid, indexed_by<N(highbid), const_mem_fun<name_bid, uint64_t, &name_bid::by_high_bid>>> name_bid_table; typedef eosio::multi_index<N(bidrefunds), bid_refund> bid_refund_table; struct eosio_global_state : eosio::blockchain_parameters { uint64_t free_ram() const { return max_ram_size - total_ram_bytes_reserved; } uint64_t max_ram_size = 64ll * 1024 * 1024 * 1024; uint64_t total_ram_bytes_reserved = 0; int64_t total_ram_stake = 0; block_timestamp last_producer_schedule_update; uint64_t last_pervote_bucket_fill = 0; int64_t pervote_bucket = 0; int64_t perblock_bucket = 0; uint32_t total_unpaid_blocks = 0; /// all blocks which have been produced but not paid int64_t total_activated_stake = 0; uint64_t thresh_activated_stake_time = 0; uint16_t last_producer_schedule_size = 0; double total_producer_vote_weight = 0; /// the sum of all producer votes block_timestamp last_name_close; // explicit serialization macro is not necessary, used here only to improve compilation time EOSLIB_SERIALIZE_DERIVED(eosio_global_state, eosio::blockchain_parameters, (max_ram_size)(total_ram_bytes_reserved)(total_ram_stake)(last_producer_schedule_update)(last_pervote_bucket_fill)(pervote_bucket)(perblock_bucket)(total_unpaid_blocks)(total_activated_stake)(thresh_activated_stake_time)(last_producer_schedule_size)(total_producer_vote_weight)(last_name_close)) }; /** * Defines new global state parameters added after version 1.0 */ struct eosio_global_state2 { eosio_global_state2() { } uint16_t new_ram_per_block = 0; block_timestamp last_ram_increase; block_timestamp last_block_num; /* deprecated */ double reserved = 0; uint8_t revision = 0; ///< used to track version updates in the future. EOSLIB_SERIALIZE(eosio_global_state2, (new_ram_per_block)(last_ram_increase)(last_block_num)(reserved)(revision)) }; struct producer_info { account_name owner; double total_votes = 0; eosio::public_key producer_key; /// a packed public key object bool is_active = true; std::string url; uint32_t unpaid_blocks = 0; uint64_t last_claim_time = 0; uint16_t location = 0; uint64_t primary_key() const { return owner; } double by_votes() const { return is_active ? -total_votes : total_votes; } bool active() const { return is_active; } void deactivate() { producer_key = public_key(); is_active = false; } // explicit serialization macro is not necessary, used here only to improve compilation time EOSLIB_SERIALIZE(producer_info, (owner)(total_votes)(producer_key)(is_active)(url)(unpaid_blocks)(last_claim_time)(location)) }; struct voter_info { account_name owner = 0; /// the voter account_name proxy = 0; /// the proxy set by the voter, if any std::vector<account_name> producers; /// the producers approved by this voter if no proxy set int64_t staked = 0; /** * Every time a vote is cast we must first "undo" the last vote weight, before casting the * new vote weight. Vote weight is calculated as: * * stated.amount * 2 ^ ( weeks_since_launch/weeks_per_year) */ double last_vote_weight = 0; /// the vote weight cast the last time the vote was updated /** * Total vote weight delegated to this voter. */ double proxied_vote_weight = 0; /// the total vote weight delegated to this voter as a proxy bool is_proxy = 0; /// whether the voter is a proxy for others uint32_t reserved1 = 0; time reserved2 = 0; eosio::asset reserved3; uint64_t primary_key() const { return owner; } // explicit serialization macro is not necessary, used here only to improve compilation time EOSLIB_SERIALIZE(voter_info, (owner)(proxy)(producers)(staked)(last_vote_weight)(proxied_vote_weight)(is_proxy)(reserved1)(reserved2)(reserved3)) }; typedef eosio::multi_index<N(voters), voter_info> voters_table; typedef eosio::multi_index<N(producers), producer_info, indexed_by<N(prototalvote), const_mem_fun<producer_info, double, &producer_info::by_votes>>> producers_table; typedef eosio::singleton<N(global), eosio_global_state> global_state_singleton; typedef eosio::singleton<N(global2), eosio_global_state2> global_state2_singleton; // static constexpr uint32_t max_inflation_rate = 5; // 5% annual inflation static constexpr uint32_t seconds_per_day = 24 * 3600; static constexpr uint64_t system_token_symbol = CORE_SYMBOL; struct pst_stats { account_name owner; eosio::extended_asset amount; uint64_t primary_key() const { return owner; } EOSLIB_SERIALIZE(pst_stats, (owner)(amount)) }; typedef eosio::multi_index<N(pststats), pst_stats> pststats; class system_contract : public native { private: voters_table _voters; producers_table _producers; global_state_singleton _global; global_state2_singleton _global2; eosio_global_state _gstate; eosio_global_state2 _gstate2; rammarket _rammarket; public: system_contract(account_name s); ~system_contract(); // Actions: void onblock(block_timestamp timestamp, account_name producer); // const block_header& header ); /// only parse first 3 fields of block header void setalimits(account_name act, int64_t ram, int64_t net, int64_t cpu); // functions defined in delegate_bandwidth.cpp /** * Stakes SYS from the balance of 'from' for the benfit of 'receiver'. * If transfer == true, then 'receiver' can unstake to their account * Else 'from' can unstake at any time. */ void delegatebw(account_name from, account_name receiver, asset stake_net_quantity, asset stake_cpu_quantity, bool transfer); /** * Decreases the total tokens delegated by from to receiver and/or * frees the memory associated with the delegation if there is nothing * left to delegate. * * This will cause an immediate reduction in net/cpu bandwidth of the * receiver. * * A transaction is scheduled to send the tokens back to 'from' after * the staking period has passed. If existing transaction is scheduled, it * will be canceled and a new transaction issued that has the combined * undelegated amount. * * The 'from' account loses voting power as a result of this call and * all producer tallies are updated. */ void undelegatebw(account_name from, account_name receiver, asset unstake_net_quantity, asset unstake_cpu_quantity); /** * Increases receiver's ram quota based upon current price and quantity of * tokens provided. An inline transfer from receiver to system contract of * tokens will be executed. */ void buyram(account_name buyer, account_name receiver, asset tokens); void buyrambytes(account_name buyer, account_name receiver, uint32_t bytes); /** * Reduces quota my bytes and then performs an inline transfer of tokens * to receiver based upon the average purchase price of the original quota. */ void sellram(account_name receiver, int64_t bytes); /** * This action is called after the delegation-period to claim all pending * unstaked tokens belonging to owner */ void refund(account_name owner); // functions defined in voting.cpp void regproducer(const account_name producer, const public_key& producer_key, const std::string& url, uint16_t location); void unregprod(const account_name producer); void setram(uint64_t max_ram_size); void setramrate(uint16_t bytes_per_block); void voteproducer(const account_name voter, const account_name proxy, const std::vector<account_name>& producers); void regproxy(const account_name proxy, bool isproxy); void setparams(const eosio::blockchain_parameters& params); // functions defined in producer_pay.cpp void claimrewards(const account_name& owner); void setpriv(account_name account, uint8_t ispriv); void rmvproducer(account_name producer); void bidname(account_name bidder, account_name newname, asset bid); void bidrefund(account_name bidder, account_name newname); public: // function defined in voting.cpp void settotalvote(account_name owner, int64_t pst_amount); private: // Implementation details: // defined in eosio.system.cpp static eosio_global_state get_default_parameters(); static block_timestamp current_block_time(); void update_ram_supply(); // defined in delegate_bandwidth.cpp void changebw(account_name from, account_name receiver, asset stake_net_quantity, asset stake_cpu_quantity, bool transfer); // defined in voting.hpp void update_elected_producers(block_timestamp timestamp); void update_votes(const account_name voter, const account_name proxy, const std::vector<account_name>& producers, bool voting); // defined in voting.cpp void propagate_weight_change(const voter_info& voter); }; } /// eosiosystem
35.863309
303
0.733099
[ "object", "vector" ]
db7c4ab6bd3a1678fb04331d2673821b293100c0
5,878
hpp
C++
src/header/UDP_Rcv.hpp
chenxull/UDP_Project
2490ee11dea3f0a11ff509f59338e510db25d0d9
[ "MIT" ]
null
null
null
src/header/UDP_Rcv.hpp
chenxull/UDP_Project
2490ee11dea3f0a11ff509f59338e510db25d0d9
[ "MIT" ]
null
null
null
src/header/UDP_Rcv.hpp
chenxull/UDP_Project
2490ee11dea3f0a11ff509f59338e510db25d0d9
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------- // Filename: UDP_Rcv.hpp // Revision: None // Date: 2018/09/30 - 02:00 // Author: Haixiang HOU // Email: hexid26@outlook.com // Website: [NULL] // Notes: [NULL] // ----------------------------------------------------------------------------- // Copyright: 2018 (c) Haixiang // License: GPL // ----------------------------------------------------------------------------- // Version [1.0] // ! UDP 收包类,监听 172.16.0.1 ~ 172.16.31.1,同时每秒显示收包计数。 // TODO 加入解码和保存功能 #include <boost/thread/thread_pool.hpp> #include <vector> #include "Config.hpp" #include "Error_Code.hpp" #include "UDP_Socket.hpp" class UDP_Rcv { private: Error_Code error_code; // 错误码 int listen_port; // 监听端口号 Config *config; // 配置信息 char **data_buffer; // 保存的采集信息缓存空间 char **check_buffer; // 保存的验证信息缓存空间 std::vector<std::string> ip_address_list; // 监听的 IP 地址 int *packets_cnt; // 收包数量计数器,每个线程一个 unsigned long long *bytes_cnt; // TODO 收包字节计数器,可能删除掉 void init_buffer(int ip_count); // 初始化缓存空间 void listening(int ip_address_index); // 开始监听 /* data */ public: UDP_Rcv(Config *config); ~UDP_Rcv(); }; void UDP_Rcv::init_buffer(int ip_count) { for (uint8_t index = 0; index < ip_count; index++) { // ! 监听地址 172.16.0.1 ~ 172.16.31.1 (可选,从 config 中读取 Raw_Data_Ids) ip_address_list.push_back("172.16." + std::to_string(config->raw_data_ids[index]) + ".1"); } // ! 监听端口号 listen_port = 58000; data_buffer = (char **)malloc(sizeof(char *) * ip_count + (long long)ip_count * 1400 * PACKET_SUM_PER_INTERFACE * sizeof(char)); int tmp_index = ip_count; // 为 data_buffer 生成连续的二维数组空间,head 是一维数组的头 if (data_buffer != NULL) { char *head = (char *)(data_buffer + ip_count * sizeof(char *)); while (tmp_index--) { data_buffer[tmp_index] = (char *)(head + (int)tmp_index * 1400 * PACKET_SUM_PER_INTERFACE * sizeof(char)); } } else { std::cout << error_code.Description(error_code.mem_malloc_error); } check_buffer = (char **)malloc(sizeof(char *) * ip_count + (long long)ip_count * 5 * PACKET_SUM_PER_INTERFACE * sizeof(char)); tmp_index = ip_count; if (check_buffer != NULL) { char *head = (char *)(check_buffer + ip_count * sizeof(char *)); while (tmp_index--) { check_buffer[tmp_index] = (char *)(head + (int)tmp_index * 5 * PACKET_SUM_PER_INTERFACE * sizeof(char)); } } else { std::cout << error_code.Description(error_code.mem_malloc_error); } } void UDP_Rcv::listening(int ip_address_index) { UDP_Socket *socket; boost::asio::io_context io_context; printf("%s\n", ip_address_list[ip_address_index].c_str()); // ! 生成一个 UDP_Socket 类来监听一个 ip 地址 socket = new UDP_Socket(io_context, packets_cnt[ip_address_index], bytes_cnt[ip_address_index], ip_address_list[ip_address_index], listen_port, &data_buffer[ip_address_index][0], &check_buffer[ip_address_index][0]); io_context.run(); } UDP_Rcv::UDP_Rcv(Config *cfg) { config = cfg; uint8_t ip_count = config->raw_data_ids.size(); init_buffer(ip_count); // ! 初始化计数器 packets_cnt = (int *)calloc(sizeof(int), ip_count); memset(&packets_cnt[0], 0, sizeof(int) * ip_count); bytes_cnt = (unsigned long long *)calloc(sizeof(unsigned long long), ip_count); memset(&bytes_cnt[0], 0, sizeof(unsigned long long) * ip_count); int *tmp_packets_cnt = new int[ip_count](); int *repeat_cnt = new int[ip_count](); boost::asio::thread_pool udp_rcv_thread_pool(ip_count); // ! index < 1 这里要改成 ip_count 才能监听所有端口,1 为测试用,监听一个端口 for (int index = 0; index < ip_count; index++) { boost::asio::post(udp_rcv_thread_pool, boost::bind(&UDP_Rcv::listening, this, index)); } // ! 等待40ms usleep(40000); std::cout << "INFO :: Ready done." << std::endl; // TODO 开始监听,告诉 Daemon 程序,可以开始发包 while (true) { sleep(1); for (uint8_t index = 0; index < ip_count; index++) { if (tmp_packets_cnt[index] != packets_cnt[index]) { printf("Interface %d :: %d\n", index, packets_cnt[index]); tmp_packets_cnt[index] = packets_cnt[index]; repeat_cnt[index] = 0; } else { repeat_cnt[index]++; if (repeat_cnt[index] > 3) { packets_cnt[index] = 0; if (tmp_packets_cnt[index] != 0) { printf("Interface %d :: packets_cnt = %d\n", index, packets_cnt[index]); } tmp_packets_cnt[index] = 0; repeat_cnt[index] = 0; bytes_cnt[index] = 0; } if (packets_cnt[index] == 614400) { printf("Interface %d :: Rcv done. %llu bytes\n", index, bytes_cnt[index]); // printf("Interface 1 CNT :: %d\n", packets_cnt[1]); // printf("Interface 2 CNT :: %d\n", packets_cnt[2]); // printf("Interface 3 CNT :: %d\n", packets_cnt[3]); // printf("Interface 4 CNT :: %d\n", packets_cnt[4]); // printf("Interface 5 CNT :: %d\n", packets_cnt[5]); // printf("Interface 6 CNT :: %d\n", packets_cnt[6]); // printf("Interface 7 CNT :: %d\n", packets_cnt[7]); break; } } } } } UDP_Rcv::~UDP_Rcv() { free(data_buffer); free(check_buffer); }
40.260274
119
0.534876
[ "vector" ]
db85e4f315c96df77d2497ed81a2976b2b29b32b
2,514
cpp
C++
SDK/Ethereum/EthereumToken.cpp
heropan/Elastos.ELA.SPV.Cpp
9b7fe0de47d3213ed175e28e20905120bfb80a23
[ "MIT" ]
11
2018-08-01T02:01:34.000Z
2019-09-15T23:31:40.000Z
SDK/Ethereum/EthereumToken.cpp
heropan/Elastos.ELA.SPV.Cpp
9b7fe0de47d3213ed175e28e20905120bfb80a23
[ "MIT" ]
51
2018-07-16T09:41:14.000Z
2020-01-08T03:40:34.000Z
SDK/Ethereum/EthereumToken.cpp
heropan/Elastos.ELA.SPV.Cpp
9b7fe0de47d3213ed175e28e20905120bfb80a23
[ "MIT" ]
26
2018-07-12T02:34:46.000Z
2022-02-07T07:08:54.000Z
/* * EthereumToken * * Created by Ed Gamble <ed@breadwallet.com> on 3/20/18. * Copyright (c) 2018 Breadwinner AG. All right reserved. * Copyright (c) 2020 Elastos Foundation * * 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 "EthereumToken.h" #include <string> namespace Elastos { namespace ElaWallet { EthereumToken::EthereumToken(BREthereumToken token) : _token(token) { } EthereumToken::~EthereumToken() { } std::string EthereumToken::getAddressLowerCase() const { std::string address = tokenGetAddress(_token); std::transform(address.begin(), address.end(), address.begin(), [](unsigned char c) { return std::tolower(c); }); return address; } std::string EthereumToken::getAddress() const { return tokenGetAddress(_token); } std::string EthereumToken::getSymbol() const { return tokenGetSymbol(_token); } std::string EthereumToken::getName() const { return tokenGetName(_token); } std::string EthereumToken::getDescription() const { return tokenGetDescription(_token); } int EthereumToken::getDecimals() { return tokenGetDecimals(_token); } int EthereumToken::hashCode() { std::hash<std::string> hash; std::string addr = tokenGetAddress(_token); return hash(addr); } std::string EthereumToken::toString() const { return std::string("EthereumToken{") + tokenGetSymbol(_token) + +"}"; } BREthereumToken EthereumToken::getRaw() const { return _token; } } }
29.576471
81
0.721161
[ "transform" ]
db880f5b6f8014f946b37c5f4cefbb1b8378e2e6
2,129
cpp
C++
src/tools.cpp
ahmedmbakr/CarND-Extended-Kalman-Filter-Project
5840bf5382e573648e45a75e7ec381b82cee9f01
[ "MIT" ]
null
null
null
src/tools.cpp
ahmedmbakr/CarND-Extended-Kalman-Filter-Project
5840bf5382e573648e45a75e7ec381b82cee9f01
[ "MIT" ]
null
null
null
src/tools.cpp
ahmedmbakr/CarND-Extended-Kalman-Filter-Project
5840bf5382e573648e45a75e7ec381b82cee9f01
[ "MIT" ]
null
null
null
#include <iostream> #include "tools.h" using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; Tools::Tools() {} Tools::~Tools() {} //RMSE = sqrt( (1 / n) * sum-of((estimiations[i] - ground_truth[i])^2) ) VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { VectorXd rmse(4); rmse << 0, 0, 0, 0; // check the validity of the following inputs: // * the estimation vector size should not be zero // * the estimation vector size should equal ground truth vector size if (estimations.size() != ground_truth.size() || estimations.size() == 0) { cout << "Invalid estimation or ground_truth data" << endl; return rmse; } //accumulate squared residuals for (unsigned int i = 0; i < estimations.size(); ++i) { VectorXd residual = estimations[i] - ground_truth[i]; //coefficient-wise multiplication residual = residual.array() * residual.array(); rmse += residual; } //calculate the mean rmse = rmse / estimations.size(); //calculate the squared root rmse = rmse.array().sqrt(); //return the result return rmse; } //The Jacobian matrix is used in the computation of the radar update stage MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { MatrixXd Hj(3, 4); //recover state parameters float px = x_state(0); float py = x_state(1); float vx = x_state(2); float vy = x_state(3); //check division by zero if (px == 0 || py == 0) { cout << "px or py can not be zero\n"; return Hj; } //compute the Jacobian matrix float px2PlusPy2 = px * px + py * py; float px2PlusPy2_pow_1Point5 = pow(px2PlusPy2, 1.5); float px2PlusPy2_sqrt = sqrt(px2PlusPy2); float hj_0_0 = px / px2PlusPy2_sqrt; float hj_0_1 = py / px2PlusPy2_sqrt; float hj_1_0 = -py / px2PlusPy2; float hj_1_1 = px / px2PlusPy2; float hj_2_0 = py * (vx * py - vy * px) / px2PlusPy2_pow_1Point5; float hj_2_1 = px * (vy * px - vx * py) / px2PlusPy2_pow_1Point5; float hj_2_2 = hj_0_0; float hj_2_3 = hj_0_1; Hj << hj_0_0, hj_0_1, 0, 0, hj_1_0, hj_1_1, 0, 0, hj_2_0, hj_2_1, hj_2_2, hj_2_3; return Hj; }
25.963415
74
0.670268
[ "vector" ]
db8c7b4a57a1366715c2b8935c12c32d72b93b4d
20,138
cxx
C++
PWGPP/EVCHAR/AliCentralityGlauberFit.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGPP/EVCHAR/AliCentralityGlauberFit.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGPP/EVCHAR/AliCentralityGlauberFit.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* Origin: Alberica Toia, CERN, Alberica.Toia@cern.ch */ /////////////////////////////////////////////////////////////////////////////// // // // class to determine centrality percentiles from 1D distributions // // // /////////////////////////////////////////////////////////////////////////////// #include <TNamed.h> #include <TH1D.h> #include <TString.h> #include <TFile.h> #include <TMath.h> #include <TROOT.h> #include <TH2F.h> #include <TF1.h> #include <TNtuple.h> #include <TStyle.h> #include <TGraphErrors.h> #include <vector> #include <TMinuit.h> #include <TStopwatch.h> #include <TRandom.h> #include "AliCentralityGlauberFit.h" #include "AliLog.h" ClassImp(AliCentralityGlauberFit) //______________________________________________________________________________ AliCentralityGlauberFit::AliCentralityGlauberFit(const char *filename) : fNmu(0), fMulow(0), fMuhigh(0), fNk(0), fKlow(0), fKhigh(0), fNalpha(0), fAlphalow(0), fAlphahigh(0), fRebinFactor(0), fScalemin(0), fMultmin(0), fMultmax(0), fGlauntuple(0), fNpart(0), fNcoll(0), fB(0), fTaa(0), fEffi(0), fhEffi(0), fTempHist(0), fGlauberHist(0), fFastFit(0), fAncestor(2), fNBD(0), fUseChi2(kTRUE), fUseAverage(kFALSE), fhAncestor(0), fNevents(100000), fNtrials(100), fInrootfilename(0), fInntuplename(0), fOutrootfilename(0), fOutntuplename(0), fAncfilename("ancestor_hists.root"), fHistnames() { // Standard constructor. TFile *f = 0; if (filename) { // glauber file f = TFile::Open(filename); fGlauntuple = (TNtuple*) f->Get("nt_Pb_Pb"); fGlauntuple->SetBranchAddress("Npart",&fNpart); fGlauntuple->SetBranchAddress("Ncoll",&fNcoll); fGlauntuple->SetBranchAddress("B",&fB); fGlauntuple->SetBranchAddress("tAA",&fTaa); } fNBD = new TF1 ("fNBD", AliCentralityGlauberFit::NBDFunc, 0, 100,2); } //-------------------------------------------------------------------------------------------------- void AliCentralityGlauberFit::SetRangeToFit(Double_t fmultmin, Double_t fmultmax) { // Set fit range. fMultmin=fmultmin; fMultmax=fmultmax; } //-------------------------------------------------------------------------------------------------- void AliCentralityGlauberFit::SetRangeToScale(Double_t fscalemin) { // Set range where to scale simulated histo to data fScalemin=fscalemin; } //-------------------------------------------------------------------------------------------------- void AliCentralityGlauberFit::SetGlauberParam( Int_t Nmu, Double_t mulow, Double_t muhigh, Int_t Nk, Double_t klow, Double_t khigh, Int_t Nalpha, Double_t alphalow, Double_t alphahigh) { // Set Glauber parameters. fNmu=Nmu; fMulow=mulow; fMuhigh=muhigh; fNk=Nk; fKlow=klow; fKhigh=khigh; fNalpha=Nalpha; fAlphalow=alphalow; fAlphahigh=alphahigh; } //-------------------------------------------------------------------------------------------------- void AliCentralityGlauberFit::MakeFits() { // Make fits. TH1F *hDATA; TH1F *thistGlau; TFile *inrootfile; TFile *outrootfile; //FILE* fTxt = fopen ("parameters.txt","w"); // open inrootfile, outrootfile std::cout << "input file " << fInrootfilename << std::endl; std::cout << "output file " << fOutrootfilename << std::endl; inrootfile = new TFile(fInrootfilename,"OPEN"); outrootfile = new TFile(fOutrootfilename,"RECREATE"); // loop over all distribution names std::vector<TString>::const_iterator hni; for(hni=fHistnames.begin(); hni!=fHistnames.end(); hni++) { hDATA = (TH1F*) (inrootfile->Get(*hni)); if (!hDATA) { TList *list = (TList*) (inrootfile->Get("CentralityStat")); //TList *list = (TList*) (inrootfile->Get("VZEROEquaFactorStat")); hDATA = (TH1F*) (list->FindObject(*hni)); } hDATA->Rebin(fRebinFactor); //TH1F *hGLAU = new TH1F("hGLAU","hGLAU",hDATA->GetNbinsX(),0,hDATA->GetNbinsX()*hDATA->GetBinWidth(1)); Double_t chi2min = 9999999.0; Double_t alpha_min=-1; Double_t mu_min=-1; Double_t k_min=-1; Double_t alpha, mu, k, chi2; for (Int_t nalpha=0;nalpha<fNalpha;nalpha++) { alpha = fAlphalow + ((Double_t) nalpha ) * (fAlphahigh - fAlphalow ) / fNalpha; mu=0.0; for (Int_t nmu=0; nmu<fNmu; nmu++) { mu = fMulow + ((Double_t) nmu ) * (fMuhigh - fMulow ) / fNmu; for (Int_t nk=0; nk<fNk; nk++) { k = fKlow + ((Double_t) nk ) * (fKhigh - fKlow ) / fNk; thistGlau = GlauberHisto(mu,k,alpha,hDATA,kFALSE); chi2 = CalculateChi2(hDATA,thistGlau); //fprintf(fTxt, "%3.3f %3.3f %3.3f %3.3f\n", (float) mu, (float) k, (float) alpha, chi2); if ( chi2 < chi2min ) { chi2min = chi2; alpha_min=alpha; mu_min=mu; k_min=k; } } } } thistGlau = GlauberHisto(mu_min,k_min,alpha_min,hDATA,kTRUE); TH1F * hGLAU = 0x0; hGLAU = (TH1F *) thistGlau->Clone("hGLAU"); hGLAU->SetName( ((TString)hDATA->GetName()).Append(Form("_GLAU"))); hGLAU->SetTitle( ((TString)hDATA->GetName()).Append(Form("_GLAU_%.3f_%.3f_%.3f", mu_min,k_min,alpha_min))); Double_t mcintegral = hGLAU->Integral(hGLAU->FindBin(fScalemin),hGLAU->GetNbinsX()); Double_t scale = (hDATA->Integral(hDATA->FindBin(fScalemin),hDATA->GetNbinsX())/mcintegral); hGLAU->Scale(scale); fhEffi = GetTriggerEfficiencyFunction(hDATA, hGLAU); SaveHisto(hDATA,hGLAU,fhEffi,outrootfile); //fclose (fTxt); std::cout << "chi2 min is " << chi2min << std::endl; std::cout << "fitted " << hGLAU->Integral(hGLAU->FindBin(fMultmin), hGLAU->FindBin(fMultmax))/hGLAU->Integral() << " of the total cross section" << std::endl; fTempHist=hDATA; fGlauberHist=hGLAU; } // close inrootfile, outrootfile inrootfile->Close(); outrootfile->Close(); } //-------------------------------------------------------------------------------------------------- void AliCentralityGlauberFit::MakeFitsMinuitNBD(Double_t alpha, Double_t mu, Double_t k) { // Make fits using Minuit. if (alpha<0) alpha = fAlphalow; if (mu<0) mu = fMulow; if (k<0) k = fKlow; printf("Calling Minuit with starting values: %f %f %f\n", alpha, mu, k); TH1F *hDATA; TH1F *thistGlau; TFile *inrootfile; TFile *outrootfile; // open inrootfile, outrootfile std::cout << "input file " << fInrootfilename << std::endl; std::cout << "output file " << fOutrootfilename << std::endl; inrootfile = new TFile(fInrootfilename,"OPEN"); outrootfile = new TFile(fOutrootfilename,"RECREATE"); // loop over all distribution names std::vector<TString>::const_iterator hni; for(hni=fHistnames.begin(); hni!=fHistnames.end(); hni++) { hDATA = (TH1F*) (inrootfile->Get(*hni)); if (!hDATA) { TList *list = (TList*) (inrootfile->Get("CentralityStat")); //TList *list = (TList*) (inrootfile->Get("VZEROEquaFactorStat")); hDATA = (TH1F*) (list->FindObject(*hni)); } hDATA->Rebin(fRebinFactor); fTempHist=hDATA; TH1F *hGLAU = new TH1F("hGLAU","hGLAU",hDATA->GetNbinsX(),0,hDATA->GetNbinsX()*hDATA->GetBinWidth(1)); hGLAU->Sumw2(); // Minimize here if(gMinuit) delete gMinuit; new TMinuit(3); gMinuit->mncler(); gMinuit->SetFCN(AliCentralityGlauberFit::MinuitFcnNBD); gMinuit->SetObjectFit(this); Double_t arglist[2]={0}; Int_t ierflg; if (fUseChi2) arglist[0] = 1; // should be 1 if you want to minimize chi2 else arglist[0] = 0.5; // should be 0.5 for ll gMinuit->mnexcm("SET ERR",arglist, 1, ierflg); gMinuit->mnparm(0,"alpha", alpha, (fAlphahigh-fAlphalow)/fNalpha, fAlphalow, fAlphahigh, ierflg); gMinuit->mnparm(1,"mu" , mu, (fMuhigh-fMulow)/fNmu, fMulow, fMuhigh, ierflg); gMinuit->mnparm(2,"k" , k, (fKhigh-fKlow)/fNk, fKlow, fKhigh, ierflg); // Call migrad arglist[0] = 100; // max calls arglist[1] = 0.1; // tolerance gMinuit->mnexcm("SIMPLEX",arglist, 2, ierflg); arglist[0] = 1000; // max calls arglist[1] = 0.1; // tolerance gMinuit->mnexcm("MIGrad",arglist, 2, ierflg); //gMinuit->mnexcm("IMPROVE",arglist, 0, ierflg); if (ierflg != 0) { AliWarning("Abnormal termination of minimization."); } // ______________________ Get chi2 and Fit Status __________ Double_t amin,edm,errdef; Int_t nvpar, nparx, icstat; gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat); Double_t chi2min = amin; std::cout << "Fit status " << icstat << std::endl; Double_t alpha_min, mu_min, k_min; Double_t alpha_mine, mu_mine, k_mine; gMinuit->GetParameter(0, alpha_min , alpha_mine ); gMinuit->GetParameter(1, mu_min , mu_mine ); gMinuit->GetParameter(2, k_min , k_mine ); // print some infos std::cout << "chi2 min is " << chi2min << ", " << alpha_min << ", "<< mu_min<< ", " << k_min << std::endl; thistGlau = GlauberHisto(mu_min,k_min,alpha_min,hDATA,kTRUE); hGLAU = (TH1F *) thistGlau->Clone("hGLAU"); hGLAU->SetName( ((TString)hDATA->GetName()).Append(Form("_GLAU"))); hGLAU->SetTitle( ((TString)hDATA->GetName()).Append(Form("_GLAU_%.3f_%.3f_%.3f", mu_min,k_min,alpha_min))); std::cout << "fitted " << hGLAU->Integral(hGLAU->FindBin(fMultmin), hGLAU->FindBin(fMultmax))/hGLAU->Integral() << " of the total cross section" << std::endl; Double_t mcintegral = hGLAU->Integral(hGLAU->FindBin(fScalemin),hGLAU->GetNbinsX()); Double_t scale = (hDATA->Integral(hDATA->FindBin(fScalemin),hDATA->GetNbinsX())/mcintegral); hGLAU->Scale(scale); std::cout << "Chi2 final " << CalculateChi2(hDATA,hGLAU) << std::endl; fhEffi = GetTriggerEfficiencyFunction(hDATA, hGLAU); SaveHisto(hDATA,hGLAU,fhEffi,outrootfile); fGlauberHist=hGLAU; } // close inrootfile, outrootfile inrootfile->Close(); outrootfile->Close(); } //-------------------------------------------------------------------------------------------------- TH1F *AliCentralityGlauberFit::GlauberHisto(Double_t mu, Double_t k, Double_t alpha, TH1F *hDATA, Bool_t save) { // Get Glauber histogram. static TH1F *h1 = (TH1F*)hDATA->Clone(); h1->Reset(); h1->SetName(Form("fit_%.3f_%.3f_%.3f",mu,k,alpha)); if (fUseAverage) { fhAncestor = MakeAncestor(alpha); for (Int_t np=1; np<=fhAncestor->GetNbinsX(); ++np) { Double_t nanc = fhAncestor->GetBinCenter(np); Double_t weights = fhAncestor->GetBinContent(np); if (weights <= 0) continue; Int_t trials = (Int_t) (20 * nanc * (Int_t) mu); if (trials <=0) continue; for (Int_t j=0; j<trials; j++) { Double_t nbdvalue = NBD(j, mu * nanc, k * nanc); h1->Fill((Double_t) j, nbdvalue * weights); } } return h1; } TH1F *hSample = fFastFit != 2 ? NBDhist(mu,k) : 0; TFile *outFile = NULL; TNtuple *ntuple = NULL; if (save) { outFile = new TFile(fOutntuplename,"RECREATE"); ntuple = new TNtuple("gnt", "Glauber ntuple", "Npart:Ncoll:B:tAA:ntot"); } Int_t nents = 0; if (fGlauntuple) nents = fGlauntuple->GetEntries(); for (Int_t i=0;i<fNevents;++i) { if (fGlauntuple) fGlauntuple->GetEntry(i % nents); else { fNpart = 2; fNcoll = 1; } Int_t n=0; if (fAncestor == 1) n = (Int_t)(TMath::Power(fNpart,alpha)); //if (fAncestor == 1) n = (Int_t)(TMath::Power(fNcoll,alpha)); else if (fAncestor == 2) n = (Int_t)(alpha * fNpart + (1-alpha) * fNcoll); else if (fAncestor == 3) n = (Int_t)((1-alpha) * fNpart/2 + alpha * fNcoll); Int_t ntot=0; if (fFastFit == 1) { ntot = (Int_t)(n*hSample->GetRandom()); // NBD } else if (fFastFit == 2) { Double_t sigma = k*TMath::Sqrt(n*mu); ntot = (Int_t)(gRandom->Gaus(n*mu,sigma)); // Gaussian } else { for(Int_t j = 0; j<(Int_t)n; ++j) ntot += (Int_t)hSample->GetRandom(); } h1->Fill(ntot); if (save) ntuple->Fill(fNpart,fNcoll,fB,fTaa,ntot); } if (save) { ntuple->Write(); outFile->Close(); } if (fFastFit != 2) delete hSample; return h1; } //-------------------------------------------------------------------------------------------------- Double_t AliCentralityGlauberFit::CalculateChi2(TH1F *hDATA, TH1F *thistGlau) { // Note that for different values of neff the mc distribution is identical, just re-scaled below // normalize the two histogram, scale MC up but leave data alone - that preserves error bars !!!! Int_t lowchibin = hDATA->FindBin(fMultmin); Int_t highchibin = hDATA->FindBin(fMultmax); Double_t mcintegral = thistGlau->Integral(1,thistGlau->GetNbinsX()); Double_t scale = (hDATA->Integral(1,hDATA->GetNbinsX())/mcintegral); thistGlau->Scale(scale); // calculate the chi2 between MC and real data over some range ???? if (fUseChi2) { Double_t chi2 = 0.0; for (Int_t i=lowchibin; i<=highchibin; i++) { if (hDATA->GetBinContent(i) < 1.0) continue; Double_t diff = TMath::Power((thistGlau->GetBinContent(i) - hDATA->GetBinContent(i)),2); diff = diff / (TMath::Power(hDATA->GetBinError(i),2) + TMath::Power(thistGlau->GetBinError(i),2)); chi2 += diff; } chi2 = chi2 / (highchibin - lowchibin + 1); return chi2; } // "-2 log likelihood ratio(mu;n) = 2[(mu - n) + n ln(n/mu)]" else { std::cout << "LL" << std::endl; Double_t ll = 0.0; for (Int_t i=lowchibin; i<=highchibin; i++) { Double_t data = hDATA ->GetBinContent(i); Double_t mc = thistGlau->GetBinContent(i); Int_t idata = TMath::Nint(data); if (mc < 1.e-9) mc = 1.e-9; Double_t fsub = - mc + idata * TMath::Log(mc); Double_t fobs = 0; if (idata > 0) { for(Int_t istep = 0; istep < idata; istep++){ if (istep > 1) fobs += TMath::Log(istep); } } fsub -= fobs; ll -= fsub ; } return 2*ll; } } //-------------------------------------------------------------------------------------------------- TH1F *AliCentralityGlauberFit::GetTriggerEfficiencyFunction(TH1F *hist1, TH1F *hist2) { // Get efficiency. fhEffi = (TH1F*)hist1->Clone("heffi"); fhEffi->Divide(hist2); return fhEffi; } //-------------------------------------------------------------------------------------------------- Double_t AliCentralityGlauberFit::GetTriggerEfficiencyIntegral(TH1F *hist1, TH1F *hist2) { // Get eff integral. fEffi = hist1->Integral()/hist2->Integral(); return fEffi; } //-------------------------------------------------------------------------------------------------- void AliCentralityGlauberFit::SaveHisto(TH1F *hist1, TH1F *hist2, TH1F *heffi, TFile *outrootfile) { // Save histograms. outrootfile->cd(); hist1->Write(); hist2->Write(); heffi->Write(); } //-------------------------------------------------------------------------------------------------- Double_t AliCentralityGlauberFit::NBD(Int_t n, Double_t mu, Double_t k) const { // Compute NBD. Double_t F; Double_t f; if (n+k > 100.0) { // log method for handling large numbers F = TMath::LnGamma(n + k)- TMath::LnGamma(n + 1.)- TMath::LnGamma(k); f = n * TMath::Log(mu/k) - (n + k) * TMath::Log(1.0 + mu/k); F = F+f; F = TMath::Exp(F); } else { F = TMath::Gamma(n + k) / ( TMath::Gamma(n + 1.) * TMath::Gamma(k) ); f = n * TMath::Log(mu/k) - (n + k) * TMath::Log(1.0 + mu/k); f = TMath::Exp(f); F *= f; } return F; } //-------------------------------------------------------------------------------------------------- TH1F *AliCentralityGlauberFit::NBDhist(Double_t mu, Double_t k) { // Interface for TH1F. TH1F *h = new TH1F("htemp","",100,-0.5,299.5); h->SetName(Form("nbd_%f_%f",mu,k)); h->SetDirectory(0); for (Int_t i=0;i<300;++i) { Double_t val = NBD(i,mu,k); if (val>1e-20) h->Fill(i,val); } return h; } //-------------------------------------------------------------------------------------------------- void AliCentralityGlauberFit::MinuitFcnNBD(Int_t &/*npar*/, Double_t */*gin*/, Double_t &f, Double_t *par, Int_t /*iflag*/) { // FCN for minuit. Double_t alpha = par[0]; Double_t mu = par[1]; Double_t k = par[2]; AliCentralityGlauberFit * obj = (AliCentralityGlauberFit *) gMinuit->GetObjectFit(); TH1F * thistGlau = obj->GlauberHisto(mu,k,alpha,obj->GetTempHist(),kFALSE); f = obj->CalculateChi2(obj->GetTempHist(),thistGlau); Printf("Minuit step: chi2=%f, alpha=%f, mu=%f, k=%f\n",f,alpha,mu,k); } //-------------------------------------------------------------------------------------------------- Double_t AliCentralityGlauberFit::NBDFunc(const Double_t *x, const Double_t *par) { // TF1 interface. Double_t mu = par[0]; Double_t k = par[1]; Double_t n = x[0]; Double_t ret = exp( TMath::LnGamma(n+k) - TMath::LnGamma(k) - TMath::LnGamma(n+1) ) * TMath::Power(mu/(mu+k),n) * TMath::Power(1-mu/(mu+k),k); return ret; } //-------------------------------------------------------------------------------------------------- TH1F *AliCentralityGlauberFit::MakeAncestor(Double_t alpha) { // Make ancestor histogram. TString hname(Form("fhAncestor_%.3f",alpha)); if (fhAncestor) { if (hname.CompareTo(fhAncestor->GetName())==0) return fhAncestor; } delete fhAncestor; fhAncestor = 0; TFile *ancfile = TFile::Open(fAncfilename,"read"); if (ancfile && ancfile->IsOpen()) { fhAncestor = dynamic_cast<TH1F*>(ancfile->Get(hname)); if (fhAncestor) { fhAncestor->SetDirectory(0); delete ancfile; return fhAncestor; } } delete ancfile; fhAncestor = new TH1F(hname,hname,3000,0,3000); fhAncestor->SetDirectory(0); Int_t nents = fGlauntuple->GetEntries(); for (Int_t i=0;i<nents;++i) { fGlauntuple->GetEntry(i % nents); Int_t n=0; if (fAncestor == 1) n = (Int_t) (TMath::Power(fNpart,alpha)); //if (fAncestor == 1) n = (Int_t) (TMath::Power(fNcoll,alpha)); else if (fAncestor == 2) n = (Int_t) (alpha * fNpart + (1-alpha) * fNcoll); else if (fAncestor == 3) n = (Int_t) ((1-alpha) * fNpart/2 + alpha * fNcoll); fhAncestor->Fill(n); } ancfile = TFile::Open(fAncfilename,"update"); if (ancfile && ancfile->IsOpen()) { fhAncestor->Write(); } delete ancfile; return fhAncestor; }
33.067323
123
0.549061
[ "vector" ]
db9758dc3c7d6dbbc5874af62c29cdc7a8375fa0
592
cpp
C++
src/question_3/main.cpp
acc-cosc-1337-spring-2021/acc-spring-2021-midterm-isaiahgher
76e14dd47cffa40f9c7f595f9f42a8a6dc362089
[ "MIT" ]
null
null
null
src/question_3/main.cpp
acc-cosc-1337-spring-2021/acc-spring-2021-midterm-isaiahgher
76e14dd47cffa40f9c7f595f9f42a8a6dc362089
[ "MIT" ]
null
null
null
src/question_3/main.cpp
acc-cosc-1337-spring-2021/acc-spring-2021-midterm-isaiahgher
76e14dd47cffa40f9c7f595f9f42a8a6dc362089
[ "MIT" ]
null
null
null
#include "question3.cpp" #include<algorithm> #include "question3.h" void transcribe_dna_into_rna(){ static std::string const dna{"GCTA"}; static std::string const rna{"CGAU"}; char strand_switch(char c) { const auto charpos = dna.find(c); if( charpos != std::string::npos ) { c = rna[charpos]; return c; } return 0; } char to_rna(char c) { return strand_switch(c); } std::string to_rna( std::string dna_string) { std::transform( dna_string.begin(), dna_string.end(), dna_string.begin(), strand_switch); return dna_string; } } int main() { return 0; }
16.914286
91
0.663851
[ "transform" ]
db97e0e92f8b43813aeecb9a249b88a5e82ea374
44,661
cpp
C++
express/MathOp.cpp
jinfagang/MNN
f10b2203dbb27432155f863f1dfd65a156d57a09
[ "Apache-2.0" ]
null
null
null
express/MathOp.cpp
jinfagang/MNN
f10b2203dbb27432155f863f1dfd65a156d57a09
[ "Apache-2.0" ]
null
null
null
express/MathOp.cpp
jinfagang/MNN
f10b2203dbb27432155f863f1dfd65a156d57a09
[ "Apache-2.0" ]
null
null
null
// // MathOp.cpp // MNN // // Created by MNN on 2019/06/27. // Copyright © 2018, Alibaba Group Holding Limited // #include <algorithm> #include <map> #include <numeric> #include <MNN/expr/ExprCreator.hpp> #include <MNN/MNNDefine.h> #include "Utils.hpp" #define MNN_DEFAULT_FLATBUFFER_SIZE 32 namespace MNN { namespace Express { static DataType _convertDataType(halide_type_t type) { if (type.code == halide_type_float) { return DataType_DT_FLOAT; } if (type.code == halide_type_uint && type.bits == 8) { return DataType_DT_UINT8; } if (type.code == halide_type_int && type.bits == 8) { return DataType_DT_INT8; } if (type.code == halide_type_int && type.bits == 32) { return DataType_DT_INT32; } return DataType_DT_INVALID; } static VARP _checkNC4HW4(VARP x) { #ifdef MNN_EXPR_SHAPE_EAGER auto info = x->getInfo(); if (nullptr != info && info->order == NC4HW4) { return _Convert(x, NCHW); } #endif return x; } static VARP _Binary(VARP x, VARP y, BinaryOpOperation operation) { x = _checkNC4HW4(x); y = _checkNC4HW4(y); flatbuffers::FlatBufferBuilder builder(MNN_DEFAULT_FLATBUFFER_SIZE); BinaryOpBuilder parameter(builder); parameter.add_opType(operation); auto paOffset = parameter.Finish(); OpBuilder opB(builder); opB.add_main(paOffset.Union()); opB.add_type(OpType_BinaryOp); opB.add_main_type(OpParameter_BinaryOp); builder.Finish(opB.Finish()); std::shared_ptr<BufferStorage> extra(new BufferStorage); extra->storage = builder.ReleaseRaw(extra->allocated_size, extra->offset); return Variable::create(Expr::create(extra, {x, y}, 1)); } static VARP _Unary(VARP x, UnaryOpOperation operation) { flatbuffers::FlatBufferBuilder builder(MNN_DEFAULT_FLATBUFFER_SIZE); UnaryOpBuilder parameter(builder); parameter.add_opType(operation); auto paOffset = parameter.Finish(); OpBuilder opB(builder); opB.add_main(paOffset.Union()); opB.add_type(OpType_UnaryOp); opB.add_main_type(OpParameter_UnaryOp); builder.Finish(opB.Finish()); std::shared_ptr<BufferStorage> extra(new BufferStorage); extra->storage = builder.ReleaseRaw(extra->allocated_size, extra->offset); return Variable::create(Expr::create(extra, {x}, 1)); } static VARP _Reduce(VARP x, INTS dim, ReductionType type, bool keepDim) { x = _checkNC4HW4(x); flatbuffers::FlatBufferBuilder builder(MNN_DEFAULT_FLATBUFFER_SIZE); flatbuffers::Offset<flatbuffers::Vector<int>> dimOffset; if (!dim.empty()) { dimOffset = builder.CreateVector(dim); } ReductionParamBuilder parameter(builder); parameter.add_operation(type); parameter.add_keepDims(keepDim); if (!dim.empty()) { parameter.add_dim(dimOffset); } auto paOffset = parameter.Finish(); OpBuilder opB(builder); opB.add_main(paOffset.Union()); opB.add_type(OpType_Reduction); opB.add_main_type(OpParameter_ReductionParam); builder.Finish(opB.Finish()); std::shared_ptr<BufferStorage> extra(new BufferStorage); extra->storage = builder.ReleaseRaw(extra->allocated_size, extra->offset); return Variable::create(Expr::create(extra, {x}, 1)); } static VARP _ReduceMutable(VARP x, VARP dim, ReductionType type, bool keepDim) { x = _checkNC4HW4(x); flatbuffers::FlatBufferBuilder builder; ReductionParamBuilder parameter(builder); parameter.add_operation(type); parameter.add_keepDims(keepDim); auto paOffset = parameter.Finish(); OpBuilder opB(builder); opB.add_main(paOffset.Union()); opB.add_type(OpType_Reduction); opB.add_main_type(OpParameter_ReductionParam); builder.Finish(opB.Finish()); // TODO: Remove Copy std::shared_ptr<BufferStorage> extra(new BufferStorage); extra->storage = builder.ReleaseRaw(extra->allocated_size, extra->offset); return Variable::create(Expr::create(extra, {x, dim}, 1)); } static VARP _Eltwise(VARP a, VARP b, EltwiseType type, std::vector<float> coeff) { std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_Eltwise; op->type = OpType_Eltwise; op->main.value = new EltwiseT; op->main.AsEltwise()->type = type; op->main.AsEltwise()->coeff = coeff; return (Variable::create(Expr::create(std::move(op), {a, b}))); } static VARP _EltwiseInt8(VARP x, VARP y, EltwiseType type, std::vector<int8_t> x_weight, std::vector<int32_t> x_bias, std::vector<float> x_scale, std::vector<float> x_tensorScale, std::vector<int8_t> y_weight, std::vector<int32_t> y_bias, std::vector<float> y_scale, std::vector<float> y_tensorScale, std::vector<int8_t> output_weight, std::vector<int32_t> output_bias, std::vector<float> output_scale, std::vector<float> output_tensorScale) { std::unique_ptr<OpT> op(new OpT); std::unique_ptr<QuantizedFloatParamT> param_x(new QuantizedFloatParamT); std::unique_ptr<QuantizedFloatParamT> param_y(new QuantizedFloatParamT); std::unique_ptr<QuantizedFloatParamT> param_output(new QuantizedFloatParamT); auto param_op = new EltwiseInt8T; param_x->weight = x_weight; param_x->bias = x_bias; param_x->scale = x_scale; param_x->tensorScale = y_tensorScale; param_y->weight = y_weight; param_y->bias = y_bias; param_y->scale = y_scale; param_y->tensorScale = y_tensorScale; param_output->weight = output_weight; param_output->bias = output_bias; param_output->scale = output_scale; param_output->tensorScale = output_tensorScale; param_op->type = type; param_op->inputQuan0 = std::move(param_x); param_op->inputQuan1 = std::move(param_y); param_op->outputQuan = std::move(param_output); op->main.type = OpParameter_EltwiseInt8; op->type = OpType_EltwiseInt8; op->main.value = param_op; return (Variable::create(Expr::create(std::move(op), {x, y}))); } /*Casts a variable to a new type. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64, Halide_Type_Uint8 dtype: The destination type. The list of supported dtypes is the same as x. Returns: A variable with same shape as x and same type as dtype. */ VARP _Cast(VARP x, halide_type_t dtype) { std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_CastParam; op->type = OpType_Cast; op->main.value = new CastParamT; op->main.AsCastParam()->dstT = _convertDataType(dtype); return (Variable::create(Expr::create(std::move(op), {x}))); } /*Computes the absolute value of a variable. Given a variable of integer or floating-point values, this operation returns a variable of the same type, where each element contains the absolute value of the corresponding element in the input. x = MNN.const((-1.0, -2.0, 3.0), (3, )) x = MNN.abs(x) # (1.0, 2.0, 3.0) Args: x: A variable of type Halide_Type_Int or Halide_Type_Float Returns: A variable the same size, type as x with absolute values. */ VARP _Abs(VARP x) { return _Unary(x, UnaryOpOperation_ABS); } /*Computes numerical negative value element-wise. x = MNN.const((-1.0, -2.0, 3.0), (3, )) x = MNN.negative(x) #(1.0, 2.0, -3.0) Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Negative(VARP x) { return _Unary(x, UnaryOpOperation_NEG); } /*Returns element-wise largest integer not greater than x. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Floor(VARP x) { return _Unary(x, UnaryOpOperation_FLOOR); } /*Returns element-wise smallest integer not less than x. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Ceil(VARP x) { return _Unary(x, UnaryOpOperation_CEIL); } /*Returns element-wise rounded integer not less than x. Args: x: A variable. Must be Halide_Type_Float Returns: A variable. Halide_Type_Float. */ VARP _Round(VARP x) { return _Unary(x, UnaryOpOperation_ROUND); } /*Computes square of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Square(VARP x) { return _Unary(x, UnaryOpOperation_SQUARE); } /*Computes square root of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Sqrt(VARP x) { return _Unary(x, UnaryOpOperation_SQRT); } /*Computes reciprocal of square root of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Rsqrt(VARP x) { return _Unary(x, UnaryOpOperation_RSQRT); } /*Computes exponential of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Exp(VARP x) { return _Unary(x, UnaryOpOperation_EXP); } /*Computes natural logarithm of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Log(VARP x) { return _Unary(x, UnaryOpOperation_LOG); } /*Computes sine of x element-wise. Given an input variable, this function computes sine of every element in the variable. Input range is (-inf, inf) and output range is [-1,1]. Args: x: A variable. Must be one of the following types: Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Sin(VARP x) { return _Unary(x, UnaryOpOperation_SIN); } /*Computes cos of x element-wise. Given an input variable, this function computes cosine of every element in the variable. Input range is (-inf, inf) and output range is [-1,1]. If input lies outside the boundary, nan is returned. Args: x: A variable. Must be one of the following types: Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Cos(VARP x) { return _Unary(x, UnaryOpOperation_COS); } /*Computes tan of x element-wise. Given an input variable, this function computes tangent of every element in the variable. Input range is (-inf, inf) and output range is (-inf, inf). If input lies outside the boundary, nan is returned. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Tan(VARP x) { return _Unary(x, UnaryOpOperation_TAN); } /*Computes the trignometric inverse sine of x element-wise. The asin operation returns the inverse of sin, such that if y = sin(x) then, x = asin(y). Note: The output of asin will lie within the invertible range of sine, i.e [-pi/2, pi/2]. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Asin(VARP x) { return _Unary(x, UnaryOpOperation_ASIN); } /*Computes acos of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Acos(VARP x) { return _Unary(x, UnaryOpOperation_ACOS); } /*Computes acosh of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Acosh(VARP x) { return _Unary(x, UnaryOpOperation_ACOSH); } /*Computes asinh of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Asinh(VARP x) { return _Unary(x, UnaryOpOperation_ASINH); } /*Computes atanh of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Atanh(VARP x) { return _Unary(x, UnaryOpOperation_ATANH); } /*Computes cosh of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Cosh(VARP x) { return _Unary(x, UnaryOpOperation_COSH); } /*Computes sinh of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Sinh(VARP x) { return _Unary(x, UnaryOpOperation_SINH); } /*Computes the Gauss error function of `x` element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Erf(VARP x) { return _Unary(x, UnaryOpOperation_ERF); } /*Computes the complementary error function of `x` element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Erfc(VARP x) { return _Unary(x, UnaryOpOperation_ERFC); } /*Computes the inverse function for erf, for `x` element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Note: The output of atan will lie within the invertible range of tan, i.e (0.0, pi). Returns: A variable. Has the same type as x. */ VARP _Erfinv(VARP x) { return _Unary(x, UnaryOpOperation_ERFINV); } /*Computes sign of x eltment-wise sign(x) = 0 if x=0 sign(x) =-1 if x<0 sign(x) = 1 if x>0 */ VARP _Sign(VARP x) { return _Unary(x, UnaryOpOperation_SIGN); } /*Computes the trignometric inverse tangent of x element-wise. The atan operation returns the inverse of tan, such that if y = tan(x) then, x = atan(y). Note: The output of atan will lie within the invertible range of tan, i.e (-pi/2, pi/2). Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Atan(VARP x) { return _Unary(x, UnaryOpOperation_ATAN); } /*Computes the reciprocal of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Reciprocal(VARP x) { return _Unary(x, UnaryOpOperation_RECIPROCAL); } /*Computes natural logarithm of (1 + x) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Log1p(VARP x) { return _Unary(x, UnaryOpOperation_LOG1P); } /*Computes Gelu of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float Returns: A variable. Has the same type as x . */ VARP _Gelu(VARP x) { return _Unary(x, UnaryOpOperation_GELU); } /*Computes hyperbolic tangent of x element-wise. Given an input variable, this function computes hyperbolic tangent of every element in the variable. Input range is [-inf, inf] and output range is [-1,1]. Args: x: A variable. Must be one of the following types: Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Tanh(VARP x) { return _Unary(x, UnaryOpOperation_TANH); } /*Computes sigmoid of x element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Sigmoid(VARP x) { return _Unary(x, UnaryOpOperation_SIGMOID); } /*Computes ((exponential of x) - 1) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float Returns: A variable. Has the same type as x. */ VARP _Expm1(VARP x) { return _Unary(x, UnaryOpOperation_EXPM1); } /*Returns x + y element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64, Halide_Type_Uint8. y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _Add(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_ADD); } /*Returns x - y element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64, Halide_Type_Uint8. y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _Subtract(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_SUB); } /*Returns x * y element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64, Halide_Type_Uint8. y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _Multiply(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_MUL); } /*Computes Python style division of x by y. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64, Halide_Type_Uint8. y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _Divide(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_REALDIV); } /*Computes the power of one value to another. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64 y: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64 Returns: A variable. Has the same type as x. */ VARP _Pow(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_POW); } /*Returns the min of x and y (i.e. x < y ? x : y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64 y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _Minimum(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_MINIMUM); } /*Returns the max of x and y (i.e. x > y ? x : y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int or Halide_Type_Float, Halide_Type_Int64 y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _Maximum(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_MAXIMUM); } /*Adds bias to value. This is (mostly) a special case of add where bias is restricted to 1-D. Broadcasting is supported, so value may have any number of dimensions. Unlike add, the type of bias is allowed to differ from value in the case where both types are quantized. Args: value: A variable with type Halide_Type_Float, Halide_Type_Int bias: A 1-D variable with size matching the channel dimension of value. Must be the same type as value unless value is a quantized type, in which case a different quantized type may be used. Returns: A variable with the same type as value. */ VARP _BiasAdd(VARP value, VARP bias) { return _Add(value, bias); } /*Returns the truth value of (x > y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable of type bool. */ VARP _Greater(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_GREATER); } /*Returns the truth value of (x >= y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable of type bool. */ VARP _GreaterEqual(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_GREATER_EQUAL); } /*Returns the truth value of (x < y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable of type bool. */ VARP _Less(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_LESS); } /*Returns the value of (x // y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _FloorDiv(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_FLOORDIV); } /*Returns the value of (x - y)(x - y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _SquaredDifference(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_SquaredDifference); } /*Returns the truth value of (x == y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable of type bool. */ VARP _Equal(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_EQUAL); } /*Returns the truth value of (x <= y) element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable of type bool. */ VARP _LessEqual(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_LESS_EQUAL); } /*Returns element-wise remainder of division Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _FloorMod(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_FLOORMOD); } /*Computes arctangent of `y/x` element-wise, respecting signs of the arguments. Args: x: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _Atan2(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_ATAN2); } /*Returns the truth value of x OR y element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _LogicalOr(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_LOGICALOR); } /*Returns the truth value of x != y element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _NotEqual(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_NOTEQUAL); } /*Returns the truth value of x & y element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _BitwiseAnd(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_BITWISE_AND); } /*Returns the truth value of x | y element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _BitwiseOr(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_BITWISE_OR); } /*Returns the truth value of x ^ y element-wise. Args: x: A variable. Must be one of the following types: Halide_Type_Int y: A variable. Must have the same type as x. Returns: A variable. Has the same type as x. */ VARP _BitwiseXor(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_BITWISE_XOR); } /*Computes the sum of elements across dimensions of a variable Reduces input_variable along the dimensions given in axis. Unless keepdims is true, the rank of the variable is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis is empty, all dimensions are reduced, and a variable with a single element is returned. Args: input_variable: The variable to reduce. Should have numeric type. axis: The dimensions to reduce. If empty(the default), reduces all dimensions. Must be in the range [-rank(input_variable), rank(input_variable)). keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced variable, of the same dtype as the input_variable. */ VARP _ReduceSum(VARP input_variable, INTS axis, bool keepdims) { return _Reduce(input_variable, axis, ReductionType_SUM, keepdims); } VARP _ReduceSumMutable(VARP input_variable, VARP axis, bool keepdims) { return _ReduceMutable(input_variable, axis, ReductionType_SUM, keepdims); } //ruhuan:TODO: ReductionType_ASUM and ReductionType_SUMSQ /*Computes the mean of elements across dimensions of a variable. Reduces input_variable along the dimensions given in axis. Unless keepdims is true, the rank of the variable is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis is empty, all dimensions are reduced, and a variable with a single element is returned. Args: input_variable: The variable to reduce. Should have numeric type. axis: The dimensions to reduce. If empty(the default), reduces all dimensions. Must be in the range [-rank(input_variable), rank(input_variable)). keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced variable, of the same dtype as the input_variable. */ VARP _ReduceMean(VARP input_variable, INTS axis, bool keepdims) { return _Reduce(input_variable, axis, ReductionType_MEAN, keepdims); } VARP _ReduceMeanMutable(VARP input_variable, VARP axis, bool keepdims) { return _ReduceMutable(input_variable, axis, ReductionType_MEAN, keepdims); } /*Computes the variance of elements across dimensions of a variable. Reduces input_variable along the dimensions given in axis. Unless keepdims is true, the rank of the variable is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis is empty, all dimensions are reduced, and a variable with a single element is returned. Args: input_variable: The variable to reduce. Should have numeric type. axis: The dimensions to reduce. If empty(the default), reduces all dimensions. Must be in the range [-rank(input_variable), rank(input_variable)). keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced variable, of the same dtype as the input_variable. */ VARP _ReduceVariance(VARP input_variable, INTS axis, bool keepdims) { auto mean = _ReduceMean(input_variable, axis, true); // to use broadcast of subtract auto variance = _ReduceMean(_Square(_Subtract(input_variable, mean)), axis, keepdims); return variance; } /*Computes the maximum of elements across dimensions of a variable. Reduces input_variable along the dimensions given in axis. Unless keepdims is true, the rank of the variable is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis is empty, all dimensions are reduced, and a variable with a single element is returned. Args: input_variable: The variable to reduce. Should have numeric type. axis: The dimensions to reduce. If empty(the default), reduces all dimensions. Must be in the range [-rank(input_variable), rank(input_variable)). keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced variable, of the same dtype as the input_variable. */ VARP _ReduceMax(VARP input_variable, INTS axis, bool keepdims) { return _Reduce(input_variable, axis, ReductionType_MAXIMUM, keepdims); } VARP _ReduceMaxMutable(VARP input_variable, VARP axis, bool keepdims) { return _ReduceMutable(input_variable, axis, ReductionType_MAXIMUM, keepdims); } /*Computes the minimum of elements across dimensions of a variable. Reduces input_variable along the dimensions given in axis. Unless keepdims is true, the rank of the variable is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis is empty, all dimensions are reduced, and a variable with a single element is returned. Args: input_variable: The variable to reduce. Should have numeric type. axis: The dimensions to reduce. If empty(the default), reduces all dimensions. Must be in the range [-rank(input_variable), rank(input_variable)). keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced variable, of the same dtype as the input_variable. */ VARP _ReduceMin(VARP input_variable, INTS axis, bool keepdims) { return _Reduce(input_variable, axis, ReductionType_MINIMUM, keepdims); } VARP _ReduceMinMutable(VARP input_variable, VARP axis, bool keepdims) { return _ReduceMutable(input_variable, axis, ReductionType_MINIMUM, keepdims); } /*Computes the product of elements across dimensions of a variable. Reduces input_variable along the dimensions given in axis. Unless keepdims is true, the rank of the variable is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis is empty, all dimensions are reduced, and a variable with a single element is returned. Args: input_variable: The variable to reduce. Should have numeric type. axis: The dimensions to reduce. If empty(the default), reduces all dimensions. Must be in the range [-rank(input_variable), rank(input_variable)). keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced variable, of the same dtype as the input_variable. */ VARP _ReduceProd(VARP input_variable, INTS axis, bool keepdims) { return _Reduce(input_variable, axis, ReductionType_PROD, keepdims); } VARP _ReduceProdMutable(VARP input_variable, VARP axis, bool keepdims) { return _ReduceMutable(input_variable, axis, ReductionType_PROD, keepdims); } /*Computes the "logical or" of elements across dimensions of a variable. Reduces input_variable along the dimensions given in axis. Unless keepdims is true, the rank of the variable is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis is empty, all dimensions are reduced, and a variable with a single element is returned. Args: input_variable: The variable to reduce. Should have booling type. axis: The dimensions to reduce. If empty(the default), reduces all dimensions. Must be in the range [-rank(input_variable), rank(input_variable)). keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced variable, of the same dtype as the input_variable. */ VARP _ReduceAny(VARP input_variable, INTS axis, bool keepdims) { return _Reduce(input_variable, axis, ReductionType_ANY, keepdims); } VARP _ReduceAnyMutable(VARP input_variable, VARP axis, bool keepdims) { return _ReduceMutable(input_variable, axis, ReductionType_ANY, keepdims); } /*Computes the "logical and" of elements across dimensions of a variable. Reduces input_variable along the dimensions given in axis. Unless keepdims is true, the rank of the variable is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis is empty, all dimensions are reduced, and a variable with a single element is returned. Args: input_variable: The variable to reduce. Should have booling type. axis: The dimensions to reduce. If empty(the default), reduces all dimensions. Must be in the range [-rank(input_variable), rank(input_variable)). keepdims: If true, retains reduced dimensions with length 1. Returns: The reduced variable, of the same dtype as the input_variable. */ VARP _ReduceAll(VARP input_variable, INTS axis, bool keepdims) { return _Reduce(input_variable, axis, ReductionType_ALL, keepdims); } VARP _ReduceAllMutable(VARP input_variable, VARP axis, bool keepdims) { return _ReduceMutable(input_variable, axis, ReductionType_ALL, keepdims); } /*Multiply the matrix "a" by the matrix "b". The inputs must be two-dimensional matrices and the inner dimension of "a" (after being transposed if transpose_a is true) must match the outer dimension of "b" (after being transposed if transposed_b is true). Arguments: a: a variable representing a matrix "a" b: a variable representing a matrix "b" tranposeA: If true, "a" is transposed before multiplication. tranposeB: If true, "b" is transposed before multiplication. Returns: The product variable. */ VARP _MatMul(VARP a, VARP b, bool tranposeA, bool tranposeB) { std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_MatMul; op->type = OpType_MatMul; op->main.value = new MatMulT; op->main.AsMatMul()->transposeA = tranposeA; op->main.AsMatMul()->transposeB = tranposeB; return (Variable::create(Expr::create(op.get(), {a, b}))); } VARP _Normalize(VARP x, int32_t acrossSpatial, int32_t channelShared, float eps, std::vector<float> scale) { std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_Normalize; op->type = OpType_Normalize; op->main.value = new NormalizeT; op->main.AsNormalize()->acrossSpatial = acrossSpatial; op->main.AsNormalize()->channelShared = channelShared; op->main.AsNormalize()->eps = eps; op->main.AsNormalize()->scale = scale; return (Variable::create(Expr::create(std::move(op), {x}))); } /* Compute the element-wise prod Args: a: A variable. Must be one of the following types: Halide_Type_Float b: A variable. Must be one of the following types: Halide_Type_Float coeff: blob-wise coefficients Returns: The prod variable. */ VARP _Prod(VARP a, VARP b, std::vector<float> coeff) { return _Eltwise(a, b, EltwiseType_PROD, coeff); } /* Compute the element-wise sum Args: a: A variable. Must be one of the following types: Halide_Type_Float b: A variable. Must be one of the following types: Halide_Type_Float coeff: blob-wise coefficients Returns: The sum variable. */ VARP _Sum(VARP a, VARP b, std::vector<float> coeff) { return _Eltwise(a, b, EltwiseType_SUM, coeff); } /* Compute the element-wise max Args: a: A variable. Must be one of the following types: Halide_Type_Float b: A variable. Must be one of the following types: Halide_Type_Float coeff: blob-wise coefficients Returns: The max variable. */ VARP _Max(VARP a, VARP b, std::vector<float> coeff) { return _Eltwise(a, b, EltwiseType_MAXIMUM, coeff); } /* Compute the element-wise sub Args: a: A variable. Must be one of the following types: Halide_Type_Float b: A variable. Must be one of the following types: Halide_Type_Float coeff: blob-wise coefficients Returns: The sub variable. */ VARP _Sub(VARP a, VARP b, std::vector<float> coeff) { return _Eltwise(a, b, EltwiseType_SUB, coeff); } /*Returns the index with the largest value across axes of a tensor. Args: input: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int axis: A int. must be in the range -rank(input), rank(input)). Describes which axis of the input variable to reduce across. For vectors, use axis = 0. Returns: A variable of type int. */ VARP _ArgMax(VARP input, int axis) { input = _checkNC4HW4(input); std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_ArgMax; op->type = OpType_ArgMax; op->main.value = new ArgMaxT; op->main.AsArgMax()->axis = axis; op->main.AsArgMax()->outMaxVal = 0; op->main.AsArgMax()->topK = 0; op->main.AsArgMax()->softmaxThreshold = 0; return (Variable::create(Expr::create(std::move(op), {input}))); } /*Returns the index with the smallest value across axes of a tensor. Args: input: A variable. Must be one of the following types: Halide_Type_Float, Halide_Type_Int axis: A int. must be in the range -rank(input), rank(input)). Describes which axis of the input variable to reduce across. For vectors, use axis = 0. Returns: A variable of type int. */ VARP _ArgMin(VARP input, int axis) { input = _checkNC4HW4(input); std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_ArgMax; op->type = OpType_ArgMin; op->main.value = new ArgMaxT; op->main.AsArgMax()->axis = axis; op->main.AsArgMax()->outMaxVal = 0; op->main.AsArgMax()->topK = 0; op->main.AsArgMax()->softmaxThreshold = 0; return (Variable::create(Expr::create(std::move(op), {input}))); } /*Multiplies slices of two variable in batches Multiplies all slices of variable x and y (each slice can be viewed as an element of a batch), and arranges the individual results in a single output variable of the same batch size. Each of the individual slices can optionally be adjointed (to adjoint a matrix means to transpose and conjugate it) before multiplication by setting the adj_x or adj_y flag to True, which are by default False. The input variable x and y are 2-D or higher with shape [..., r_x, c_x] and [..., r_y, c_y]. The output variable is 2-D or higher with shape [..., r_o, c_o], where: r_o = c_x if adj_x else r_x c_o = r_y if adj_y else c_y It is computed as: output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) Arguments: x: 2-D or higher with shape [..., r_x, c_x]. y: 2-D or higher with shape [..., r_y, c_y]. Optional: adj_x: If True, adjoint the slices of x. Defaults to False. adj_y: If True, adjoint the slices of y. Defaults to False. Returns: Output: 3-D or higher with shape [..., r_o, c_o] */ VARP _BatchMatMul(VARP x, VARP y, bool adj_x, bool adj_y) { std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_BatchMatMulParam; op->type = OpType_BatchMatMul; op->main.value = new BatchMatMulParamT; op->main.AsBatchMatMulParam()->adjX = adj_x; op->main.AsBatchMatMulParam()->adjY = adj_y; return (Variable::create(Expr::create(std::move(op), {x, y}))); } VARP _UnravelIndex(VARP indices, VARP dims) { std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_NONE; op->type = OpType_UnravelIndex; op->main.value = nullptr; return (Variable::create(Expr::create(std::move(op), {indices, dims}))); } VARP _ScatterNd(VARP indices, VARP updates, VARP shape) { std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_NONE; op->type = OpType_ScatterNd; op->main.value = nullptr; return (Variable::create(Expr::create(std::move(op), {indices, updates, shape}))); } VARP _ScatterNd(VARP indices, VARP updates, VARP shape, VARP input) { std::unique_ptr<OpT> op(new OpT); op->main.type = OpParameter_NONE; op->type = OpType_ScatterNd; op->main.value = nullptr; return (Variable::create(Expr::create(std::move(op), {indices, updates, shape, input}))); } VARP _OneHot(VARP indices, VARP depth, VARP onValue, VARP offValue, int axis) { std::unique_ptr<OpT> op(new OpT); op->type = OpType_OneHot; op->main.type = OpParameter_OneHotParam; op->main.value = new OneHotParamT; op->main.AsOneHotParam()->axis = axis; return (Variable::create(Expr::create(std::move(op), {indices, depth, onValue, offValue}))); } VARP _BroadcastTo(VARP a, VARP shape) { std::unique_ptr<OpT> op(new OpT); op->type = OpType_BroadcastTo; op->main.type = OpParameter_NONE; op->main.value = nullptr; return (Variable::create(Expr::create(std::move(op), {a, shape}))); } VARP _LinSpace(VARP start, VARP stop, VARP num) { std::unique_ptr<OpT> op(new OpT); op->type = OpType_LinSpace; op->main.type = OpParameter_NONE; op->main.value = nullptr; return (Variable::create(Expr::create(std::move(op), {start, stop, num}))); } VARP _EltwiseProdInt8(VARP x, VARP y, std::vector<int8_t> x_weight, std::vector<int32_t> x_bias, std::vector<float> x_scale, std::vector<float> x_tensorScale, std::vector<int8_t> y_weight, std::vector<int32_t> y_bias, std::vector<float> y_scale, std::vector<float> y_tensorScale, std::vector<int8_t> output_weight, std::vector<int32_t> output_bias, std::vector<float> output_scale, std::vector<float> output_tensorScale) { return _EltwiseInt8(x, y, EltwiseType_PROD, x_weight, x_bias, x_scale, x_tensorScale, y_weight, y_bias, y_scale, y_tensorScale, output_weight, output_bias, output_scale, output_tensorScale); } VARP _EltwiseSumInt8(VARP x, VARP y, std::vector<int8_t> x_weight, std::vector<int32_t> x_bias, std::vector<float> x_scale, std::vector<float> x_tensorScale, std::vector<int8_t> y_weight, std::vector<int32_t> y_bias, std::vector<float> y_scale, std::vector<float> y_tensorScale, std::vector<int8_t> output_weight, std::vector<int32_t> output_bias, std::vector<float> output_scale, std::vector<float> output_tensorScale) { return _EltwiseInt8(x, y, EltwiseType_SUM, x_weight, x_bias, x_scale, x_tensorScale, y_weight, y_bias, y_scale, y_tensorScale, output_weight, output_bias, output_scale, output_tensorScale); } VARP _EltwiseSubInt8(VARP x, VARP y, std::vector<int8_t> x_weight, std::vector<int32_t> x_bias, std::vector<float> x_scale, std::vector<float> x_tensorScale, std::vector<int8_t> y_weight, std::vector<int32_t> y_bias, std::vector<float> y_scale, std::vector<float> y_tensorScale, std::vector<int8_t> output_weight, std::vector<int32_t> output_bias, std::vector<float> output_scale, std::vector<float> output_tensorScale) { return _EltwiseInt8(x, y, EltwiseType_SUB, x_weight, x_bias, x_scale, x_tensorScale, y_weight, y_bias, y_scale, y_tensorScale, output_weight, output_bias, output_scale, output_tensorScale); } VARP _EltwiseMaxInt8(VARP x, VARP y, std::vector<int8_t> x_weight, std::vector<int32_t> x_bias, std::vector<float> x_scale, std::vector<float> x_tensorScale, std::vector<int8_t> y_weight, std::vector<int32_t> y_bias, std::vector<float> y_scale, std::vector<float> y_tensorScale, std::vector<int8_t> output_weight, std::vector<int32_t> output_bias, std::vector<float> output_scale, std::vector<float> output_tensorScale) { return _EltwiseInt8(x, y, EltwiseType_MAXIMUM, x_weight, x_bias, x_scale, x_tensorScale, y_weight, y_bias, y_scale, y_tensorScale, output_weight, output_bias, output_scale, output_tensorScale); } VARP _RandomUnifom(VARP shape, halide_type_t dtype, float low, float high, int seed0, int seed1) { flatbuffers::FlatBufferBuilder builder(MNN_DEFAULT_FLATBUFFER_SIZE); RandomUniformBuilder paramBuilder(builder); paramBuilder.add_type(_convertDataType(dtype)); paramBuilder.add_low(low); paramBuilder.add_high(high); paramBuilder.add_seed(seed0); paramBuilder.add_seed2(seed1); auto parmOffset = paramBuilder.Finish(); OpBuilder opB(builder); opB.add_type(OpType_RandomUniform); opB.add_main(parmOffset.Union()); opB.add_main_type(OpParameter_RandomUniform); builder.Finish(opB.Finish()); std::shared_ptr<BufferStorage> extra(new BufferStorage); extra->storage = builder.ReleaseRaw(extra->allocated_size, extra->offset); return Variable::create(Expr::create(extra, {shape}, 1)); } VARP _Mod(VARP x, VARP y) { return _Binary(x, y, BinaryOpOperation_MOD); } } // namespace Express } // namespace MNN
36.428222
160
0.719084
[ "shape", "vector" ]
db9d4b15a244f596ad73b3e225d3e2717403ba97
14,029
cpp
C++
src/applications_pool.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
null
null
null
src/applications_pool.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
null
null
null
src/applications_pool.cpp
gatehouse/cppcms
61da055ffeb349b4eda14bc9ac393af9ce842364
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2008-2012 Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com> // // See accompanying file COPYING.TXT file for licensing details. // /////////////////////////////////////////////////////////////////////////////// #define CPPCMS_SOURCE #include <cppcms/applications_pool.h> #include <cppcms/application.h> #include <cppcms/service.h> #include <cppcms/mount_point.h> #include <cppcms/cppcms_error.h> #include <cppcms/json.h> #include <list> #include <utility> #include <vector> #include <cassert> #include <cppcms/config.h> #include <booster/regex.h> #include <booster/shared_ptr.h> #include <booster/thread.h> #include <booster/log.h> namespace cppcms { class application_specific_pool::_policy { public: bool lock_on_get_put; bool lock_on_request; _policy(application_specific_pool *self) : lock_on_get_put(true), lock_on_request(false), self_(self) { } virtual void prepopulate(cppcms::service &srv) = 0; virtual void application_requested(cppcms::service &) {} virtual ~_policy() {} virtual booster::intrusive_ptr<application> get_async(booster::aio::io_service &,cppcms::service *srv=0); virtual booster::intrusive_ptr<application> get(cppcms::service &srv) = 0; virtual void put(application *app) = 0; application *get_new(cppcms::service &srv) { return self_->get_new(srv); } protected: application_specific_pool *self_; }; booster::intrusive_ptr<application> application_specific_pool::_policy::get_async(booster::aio::io_service &,cppcms::service *) { throw cppcms_error("Is not implemented for synchronous application"); } class application_specific_pool::_tls_policy : public application_specific_pool::_policy { public: _tls_policy(application_specific_pool *self) : application_specific_pool::_policy(self) { lock_on_get_put=false; } virtual booster::intrusive_ptr<application> get(cppcms::service &srv) { application *app = tss_.release(); if(!app) return get_new(srv); return app; } virtual void put(application *app) { if(!app) return; tss_.reset(app); } virtual void prepopulate(cppcms::service &){} private: booster::thread_specific_ptr<application> tss_; }; class application_specific_pool::_pool_policy : public application_specific_pool::_policy{ public: _pool_policy(application_specific_pool *self,size_t n) : _policy(self) { apps_.resize(n,0); size_ = 0; } ~_pool_policy() { for(size_t i=0;i<size_;i++) delete apps_[i]; } virtual void application_requested(cppcms::service &) {} virtual void prepopulate(cppcms::service &srv) { if((self_->flags() & app::prepopulated) && !(self_->flags() & app::legacy)) { while(size_ < apps_.size()) { size_++; apps_[size_-1]= get_new(srv); } } } virtual booster::intrusive_ptr<application> get(cppcms::service &srv) { if(size_ == 0) return get_new(srv); size_ --; application *app = apps_[size_]; apps_[size_]=0; return app; } virtual void put(application *app) { if(!app) return; if(size_ >= apps_.size()) delete app; apps_[size_++] = app; } private: std::vector<application *> apps_; size_t size_; }; class application_specific_pool::_legacy_pool_policy : public application_specific_pool::_policy { public: _legacy_pool_policy(application_specific_pool *self,size_t n) : _policy(self), total_(0), pending_(0), size_(0), limit_(n) { apps_.resize(limit_,0); lock_on_request=true; } ~_legacy_pool_policy() { for(size_t i=0;i<size_;i++) { delete apps_[i]; apps_[i]=0; } } virtual void application_requested(cppcms::service &srv) { if(total_ >= limit_) return; pending_++; if(pending_ > size_) { apps_[size_] = get_new(srv); size_++; total_++; } } virtual void prepopulate(cppcms::service &) {} virtual booster::intrusive_ptr<application> get(cppcms::service &) { booster::intrusive_ptr<application> app; // must never happen start if(size_ == 0) return app; // must never happen end size_--; pending_--; app = apps_[size_]; apps_[size_] = 0; return app; } virtual void put(application *app) { if(!app) return; // must never heppen start if(size_ >= limit_) delete app; // must never happend end apps_[size_++] = app; } private: std::vector<application *> apps_; size_t total_; size_t pending_; size_t size_; size_t limit_; }; class application_specific_pool::_async_policy : public application_specific_pool::_policy{ public: _async_policy(application_specific_pool *self) : _policy(self), io_srv_(0) { } virtual void prepopulate(cppcms::service &srv) { if((self_->flags() & app::prepopulated) && !(self_->flags() & app::legacy)) { if(!app_) { app_ = get_new(srv); io_srv_ = &srv.get_io_service(); } } } virtual booster::intrusive_ptr<application> get(cppcms::service &srv) { if(!app_) { app_ = get_new(srv); if(app_) { io_srv_ = &srv.get_io_service(); } } return app_; } virtual void put(application *) { // SHOULD NEVER BE CALLED as when pool is destroyed and app_ is destroyed weak_ptr would be invalid } virtual booster::intrusive_ptr<application> get_async(booster::aio::io_service &io_srv,cppcms::service *srv = 0) { if(app_) { if(&io_srv == io_srv_) return app_; else throw cppcms_error("given booster::aio::io_service isn't main event loop io_service"); } if(!srv) return 0; return get(*srv); } private: booster::intrusive_ptr<application> app_; booster::aio::io_service *io_srv_; }; class application_specific_pool::_async_legacy_policy : public application_specific_pool::_policy{ public: _async_legacy_policy(application_specific_pool *self) : _policy(self), app_(0) { } virtual void prepopulate(cppcms::service &) {} virtual booster::intrusive_ptr<application> get(cppcms::service &srv) { if(self_->flags()==-1) return 0; if(!app_) app_ = get_new(srv); return app_; } virtual void put(application *app) { if(!app) return; delete app; app_ = 0; self_->flags(-1); } private: application *app_; }; struct application_specific_pool::_data { int flags; size_t size; booster::hold_ptr<application_specific_pool::_policy> policy; booster::recursive_mutex lock; }; void application_specific_pool::size(size_t s) { d->size = s; } void application_specific_pool::application_requested(cppcms::service &srv) { if(d->policy->lock_on_request) { booster::unique_lock<booster::recursive_mutex> g(d->lock); d->policy->application_requested(srv); } else { d->policy->application_requested(srv); } } application_specific_pool::~application_specific_pool() { } application_specific_pool::application_specific_pool() : d(new application_specific_pool::_data()) { d->flags = 0; } int application_specific_pool::flags() { return d->flags; } void application_specific_pool::flags(int flags) { if(d->flags == -1) return; if(flags != -1 && d->policy.get()) return; d->flags = flags; if(flags == -1) return; if(flags == (app::asynchronous | app::legacy)) { d->policy.reset(new _async_legacy_policy(this)); return; } if(flags == app::legacy) { d->policy.reset(new _legacy_pool_policy(this,d->size)); return; } if((flags & app::op_mode_mask) != app::synchronous) { d->policy.reset(new _async_policy(this)); return; } if(flags & app::thread_specific) { d->policy.reset(new _tls_policy(this)); } else { d->policy.reset(new _pool_policy(this,d->size)); } } booster::intrusive_ptr<application> application_specific_pool::asynchronous_application_by_io_service(booster::aio::io_service &ios,cppcms::service &srv) { booster::unique_lock<booster::recursive_mutex> g(d->lock); if(d->flags == -1) return 0; assert(d->policy.get()); return d->policy->get_async(ios,&srv); } booster::intrusive_ptr<application> application_specific_pool::asynchronous_application_by_io_service(booster::aio::io_service &ios) { booster::unique_lock<booster::recursive_mutex> g(d->lock); if(d->flags == -1) return 0; assert(d->policy.get()); return d->policy->get_async(ios); } application *application_specific_pool::get_new(service &srv) { application *a = new_application(srv); if(!a) return 0; a->set_pool(shared_from_this()); return a; } void application_specific_pool::put(application *a) { if(d->flags == -1) { delete a; return; } assert(d->policy.get()); if(d->policy->lock_on_get_put) { booster::unique_lock<booster::recursive_mutex> g(d->lock); d->policy->put(a); } else { d->policy->put(a); } } booster::intrusive_ptr<application> application_specific_pool::get(cppcms::service &srv) { if(d->flags == -1) return 0; assert(d->policy.get()); booster::intrusive_ptr<application> app; if(d->policy->lock_on_get_put) { booster::unique_lock<booster::recursive_mutex> g(d->lock); app = d->policy->get(srv); } else app = d->policy->get(srv); return app; } void application_specific_pool::prepopulate(cppcms::service &srv) { d->policy->prepopulate(srv); } namespace impl { class legacy_sync_pool : public application_specific_pool { public: legacy_sync_pool(std::unique_ptr<applications_pool::factory> f) { fact_ = std::move(f); } application *new_application(cppcms::service &srv) { std::unique_ptr<application> a = (*fact_)(srv); return a.release(); } private: std::unique_ptr<applications_pool::factory> fact_; }; class legacy_async_pool : public application_specific_pool { public: legacy_async_pool(booster::intrusive_ptr<application> app) { my_ = app.get(); } application *new_application(cppcms::service &) { application *a = my_; my_ = 0; return a; } private: application *my_; }; } // impl struct applications_pool::_data { struct attachment { mount_point mp; booster::shared_ptr<application_specific_pool> pool; attachment(booster::shared_ptr<application_specific_pool> p,mount_point const &m) : mp(m), pool(p) {} }; std::list<attachment> apps; std::list<attachment> legacy_async_apps; int thread_count; booster::recursive_mutex lock; }; applications_pool::applications_pool(service &srv,int /*unused*/) : srv_(&srv), d(new applications_pool::_data()) { d->thread_count = srv_->threads_no(); } applications_pool::~applications_pool() { } void applications_pool::mount(std::unique_ptr<factory> aps,mount_point const &mp) { booster::shared_ptr<application_specific_pool> p(new impl::legacy_sync_pool(std::move(aps))); p->size(d->thread_count); p->flags(app::legacy); booster::unique_lock<booster::recursive_mutex> lock(d->lock); d->apps.push_back(_data::attachment(p,mp)); } void applications_pool::mount(std::unique_ptr<factory> aps) { mount(std::move(aps),mount_point()); } void applications_pool::mount(booster::intrusive_ptr<application> app) { mount(app,mount_point()); } void applications_pool::mount(booster::intrusive_ptr<application> app,mount_point const &mp) { booster::shared_ptr<application_specific_pool> p(new impl::legacy_async_pool(app)); p->size(d->thread_count); p->flags(app::legacy | app::asynchronous); booster::unique_lock<booster::recursive_mutex> lock(d->lock); d->legacy_async_apps.push_back(_data::attachment(p,mp)); } void applications_pool::mount(booster::shared_ptr<application_specific_pool> gen,mount_point const &point,int flags) { if(flags & app::legacy) { throw cppcms_error("Direct specification of cppcms::app::legacy flag is forbidden"); } gen->size(d->thread_count); gen->flags(flags); if(flags & app::prepopulated) gen->prepopulate(*srv_); booster::unique_lock<booster::recursive_mutex> lock(d->lock); for(std::list<_data::attachment>::iterator it = d->apps.begin();it!=d->apps.end();++it) { if(it->pool == gen) throw cppcms_error("Attempt to mount application_specific_pool twice"); } d->apps.push_back(_data::attachment(gen,point)); } void applications_pool::mount(booster::shared_ptr<application_specific_pool> gen,int flags) { mount(gen,mount_point(),flags); } booster::shared_ptr<application_specific_pool> applications_pool::get_application_specific_pool(char const *host,char const *script_name,char const *path_info,std::string &match) { booster::unique_lock<booster::recursive_mutex> lock(d->lock); for(std::list<_data::attachment>::iterator it = d->apps.begin();it!=d->apps.end();++it) { std::pair<bool,std::string> m = it->mp.match(host,script_name,path_info); if(!m.first) continue; match = m.second; it->pool->application_requested(*srv_); return it->pool; } booster::shared_ptr<application_specific_pool> result; for(std::list<_data::attachment>::iterator itr = d->legacy_async_apps.begin();itr!=d->legacy_async_apps.end();) { std::list<_data::attachment>::iterator app_it = itr; ++itr; if(app_it->pool->flags() == -1) { d->legacy_async_apps.erase(app_it); } else if (!result) { std::pair<bool,std::string> m = app_it->mp.match(host,script_name,path_info); if(!m.first) continue; match = m.second; app_it->pool->application_requested(*srv_); result = app_it->pool; } } return result; } void applications_pool::unmount(booster::weak_ptr<application_specific_pool> wgen) { booster::shared_ptr<application_specific_pool> gen = wgen.lock(); if(!gen) return; booster::unique_lock<booster::recursive_mutex> lock(d->lock); for(std::list<_data::attachment>::iterator it = d->apps.begin();it!=d->apps.end();++it) { if(it->pool == gen) { d->apps.erase(it); return; } } } booster::intrusive_ptr<application> applications_pool::get( char const *, char const *, char const *, std::string &) { throw cppcms_error("THIS IS INTERNAL MEMBER FUNCTION METHOD MUST NOT BE USED"); } void applications_pool::put(application *) { BOOSTER_WARNING("cppcms") << "CALL OF INTERNAL METHOD"; } } //cppcms
24.569177
153
0.692494
[ "vector" ]
dba31ef14f80379c519d73c33f8a5b8aea2ad9ac
1,283
cpp
C++
src/model.cpp
dorodnic/shader_playground
fa66ffd18140c1b6b80a4451805cf9f7fe666c92
[ "Apache-2.0" ]
1
2018-08-11T18:05:18.000Z
2018-08-11T18:05:18.000Z
src/model.cpp
dorodnic/shader_playground
fa66ffd18140c1b6b80a4451805cf9f7fe666c92
[ "Apache-2.0" ]
null
null
null
src/model.cpp
dorodnic/shader_playground
fa66ffd18140c1b6b80a4451805cf9f7fe666c92
[ "Apache-2.0" ]
null
null
null
#include "model.h" void model::create(obj_file& loader) { for (auto& mesh : loader) { if (mesh.name == id || id == "*") { id = mesh.name; //if (curMesh.MeshMaterial.map_Kd != "") //{ // auto dir = get_directory(loader.Path); // auto diffuse_path = curMesh.MeshMaterial.map_Kd; // if (dir != "") diffuse_path = dir + "/" + diffuse_path; // diffuse.upload(diffuse_path); //} for (auto& p : mesh.positions) { auto length = p.x * p.x + p.y * p.y + p.z * p.z; _max = std::max(length, _max); } _max = sqrt(_max); for (auto& p : mesh.positions) { p.x /= _max; p.y /= _max; p.z /= _max; } _geometry = std::make_shared<vao>(mesh.positions.data(), mesh.uvs.data(), mesh.normals.data(), mesh.tangents.data(), mesh.positions.size(), mesh.indexes.data(), mesh.indexes.size()); } } } void model::render() { if (!_geometry) return; if (visible) _geometry->draw(); }
26.729167
73
0.41933
[ "mesh", "render", "model" ]
dbaa53f72097f5eaa00ab6cf8051c53f8c7e203a
4,722
cpp
C++
tools/handler.cpp
Nuvoton-Israel/phosphor-ipmi-flash
af7e0ab8141863fd898f638292083d677308419c
[ "Apache-2.0" ]
1
2020-06-22T13:37:17.000Z
2020-06-22T13:37:17.000Z
tools/handler.cpp
Nuvoton-Israel/phosphor-ipmi-flash
af7e0ab8141863fd898f638292083d677308419c
[ "Apache-2.0" ]
null
null
null
tools/handler.cpp
Nuvoton-Israel/phosphor-ipmi-flash
af7e0ab8141863fd898f638292083d677308419c
[ "Apache-2.0" ]
1
2019-09-11T05:29:42.000Z
2019-09-11T05:29:42.000Z
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "handler.hpp" #include "flags.hpp" #include "helper.hpp" #include "status.hpp" #include "tool_errors.hpp" #include "util.hpp" #include <algorithm> #include <cstdint> #include <cstring> #include <ipmiblob/blob_errors.hpp> #include <string> #include <vector> namespace host_tool { bool UpdateHandler::checkAvailable(const std::string& goalFirmware) { std::vector<std::string> blobs = blob->getBlobList(); auto blobInst = std::find_if( blobs.begin(), blobs.end(), [&goalFirmware](const std::string& iter) { /* Running into weird scenarios where the string comparison doesn't * work. TODO: revisit. */ return (0 == std::memcmp(goalFirmware.c_str(), iter.c_str(), goalFirmware.length())); // return (goalFirmware.compare(iter)); }); if (blobInst == blobs.end()) { std::fprintf(stderr, "%s not found\n", goalFirmware.c_str()); return false; } return true; } void UpdateHandler::sendFile(const std::string& target, const std::string& path) { std::uint16_t session; auto supported = handler->supportedType(); try { session = blob->openBlob( target, static_cast<std::uint16_t>(supported) | static_cast<std::uint16_t>( ipmi_flash::FirmwareFlags::UpdateFlags::openWrite)); } catch (const ipmiblob::BlobException& b) { throw ToolException("blob exception received: " + std::string(b.what())); } if (!handler->sendContents(path, session)) { /* Need to close the session on failure, or it's stuck open (until the * blob handler timeout is implemented, and even then, why make it wait. */ blob->closeBlob(session); throw ToolException("Failed to send contents of " + path); } blob->closeBlob(session); } bool UpdateHandler::verifyFile(const std::string& target, bool ignoreStatus) { std::uint16_t session; bool success = false; try { session = blob->openBlob( target, static_cast<std::uint16_t>( ipmi_flash::FirmwareFlags::UpdateFlags::openWrite)); } catch (const ipmiblob::BlobException& b) { throw ToolException("blob exception received: " + std::string(b.what())); } std::fprintf(stderr, "Committing to %s to trigger service\n", target.c_str()); try { blob->commit(session, {}); } catch (const ipmiblob::BlobException& b) { blob->closeBlob(session); throw ToolException("blob exception received: " + std::string(b.what())); } if (ignoreStatus) { // Skip checking the blob for status if ignoreStatus is enabled blob->closeBlob(session); return true; } std::fprintf(stderr, "Calling stat on %s session to check status\n", target.c_str()); if (pollStatus(session, blob)) { std::fprintf(stderr, "Returned success\n"); success = true; } else { std::fprintf(stderr, "Returned non-success (could still " "be running (unlikely))\n"); } blob->closeBlob(session); return (success == true); } void UpdateHandler::cleanArtifacts() { /* open(), commit(), close() */ std::uint16_t session; /* Errors aren't important for this call. */ try { std::fprintf(stderr, "Opening the cleanup blob\n"); session = blob->openBlob( ipmi_flash::cleanupBlobId, static_cast<std::uint16_t>( ipmi_flash::FirmwareFlags::UpdateFlags::openWrite)); } catch (...) { return; } try { std::fprintf(stderr, "Committing to the cleanup blob\n"); blob->commit(session, {}); std::fprintf(stderr, "Closing cleanup blob\n"); } catch (...) { } blob->closeBlob(session); } } // namespace host_tool
26.829545
80
0.589581
[ "vector" ]
dbaf87aa52836446032ebb7eea5e9835d5d2334d
18,999
cpp
C++
Engine/Source/Runtime/DatabaseSupport/Private/Database.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/DatabaseSupport/Private/Database.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/DatabaseSupport/Private/Database.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. // Precompiled header include. Can't add anything above this line. #include "DatabaseSupportPrivatePCH.h" DEFINE_LOG_CATEGORY_STATIC(LogDataBase, Log, All); #if USE_REMOTE_INTEGRATION /** * Sends a command to the database proxy. * * @param Cmd The command to be sent. */ bool ExecuteDBProxyCommand(FSocket *Socket, const TCHAR* Cmd) { check(Socket); check(Cmd); int32 CmdStrLength = FCString::Strlen(Cmd); int32 BytesSent = 0; // add 1 so we also send NULL ++CmdStrLength; TCHAR *SendBuf = (TCHAR*)FMemory::Malloc(CmdStrLength * sizeof(TCHAR)); // convert to network byte ordering. This is important for running on the ps3 and xenon for(int32 BufIndex = 0; BufIndex < CmdStrLength; ++BufIndex) { SendBuf[BufIndex] = htons(Cmd[BufIndex]); } bool bRet = Socket->Send((uint8*)SendBuf, CmdStrLength * sizeof(TCHAR), BytesSent); FMemory::Free(SendBuf); return bRet; } ////////////////////////////////////////////// FRemoteDatabaseConnection /////////////////////////////////////////////////////// /** * Constructor. */ FRemoteDatabaseConnection::FRemoteDatabaseConnection() : Socket(NULL) { check(GSocketSubsystem); // The socket won't work if secure connections are enabled, so don't try if (GSocketSubsystem->RequiresEncryptedPackets() == false) { Socket = GSocketSubsystem->CreateSocket(NAME_Stream, TEXT("remote database connection")); } } /** * Destructor. */ FRemoteDatabaseConnection::~FRemoteDatabaseConnection() { check(GSocketSubsystem); if ( Socket ) { GSocketSubsystem->DestroySocket(Socket); Socket = NULL; } } /** * Opens a connection to the database. * * @param ConnectionString Connection string passed to database layer * @param RemoteConnectionIP The IP address which the RemoteConnection should connect to * @param RemoteConnectionStringOverride The connection string which the RemoteConnection is going to utilize * * @return true if connection was successfully established, false otherwise */ bool FRemoteDatabaseConnection::Open( const TCHAR* ConnectionString, const TCHAR* RemoteConnectionIP, const TCHAR* RemoteConnectionStringOverride ) { bool bIsValid = false; if ( Socket ) { FInternetAddr Address; Address.SetIp(RemoteConnectionIP, bIsValid); Address.SetPort(10500); if(bIsValid) { bIsValid = Socket->Connect(Address); if(bIsValid && RemoteConnectionStringOverride) { SetConnectionString(RemoteConnectionStringOverride); } } } return bIsValid; } /** * Closes connection to database. */ void FRemoteDatabaseConnection::Close() { if ( Socket ) { Socket->Close(); } } /** * Executes the passed in command on the database. * * @param CommandString Command to execute * * @return true if execution was successful, false otherwise */ bool FRemoteDatabaseConnection::Execute(const TCHAR* CommandString) { FString Cmd = FString::Printf(TEXT("<command results=\"false\">%s</command>"), CommandString); return ExecuteDBProxyCommand(Socket, *Cmd); } /** * Executes the passed in command on the database. The caller is responsible for deleting * the created RecordSet. * * @param CommandString Command to execute * @param RecordSet Reference to recordset pointer that is going to hold result * * @return true if execution was successful, false otherwise */ bool FRemoteDatabaseConnection::Execute(const TCHAR* CommandString, FDataBaseRecordSet*& RecordSet) { RecordSet = NULL; FString Cmd = FString::Printf(TEXT("<command results=\"true\">%s</command>"), CommandString); bool bRetVal = ExecuteDBProxyCommand(Socket, *Cmd); int32 ResultID = 0; int32 BytesRead; if(bRetVal) { Socket->Recv((uint8*)&ResultID, sizeof(int32), BytesRead); bRetVal = BytesRead == sizeof(int32); if(bRetVal) { RecordSet = new FRemoteDataBaseRecordSet(ResultID, Socket); } } return bRetVal; } /** * Sets the connection string to be used for this connection in the DB proxy. * * @param ConnectionString The new connection string to use. */ bool FRemoteDatabaseConnection::SetConnectionString(const TCHAR* ConnectionString) { FString Cmd = FString::Printf(TEXT("<connectionString>%s</connectionString>"), ConnectionString); return ExecuteDBProxyCommand(Socket, *Cmd); } ////////////////////////////////////////////// FRemoteDataBaseRecordSet /////////////////////////////////////////////////////// /** Moves to the first record in the set. */ void FRemoteDataBaseRecordSet::MoveToFirst() { ExecuteDBProxyCommand(Socket, *FString::Printf(TEXT("<movetofirst resultset=\"%s\"/>"), *ID)); } /** Moves to the next record in the set. */ void FRemoteDataBaseRecordSet::MoveToNext() { ExecuteDBProxyCommand(Socket, *FString::Printf(TEXT("<movetonext resultset=\"%s\"/>"), *ID)); } /** * Returns whether we are at the end. * * @return true if at the end, false otherwise */ bool FRemoteDataBaseRecordSet::IsAtEnd() const { ExecuteDBProxyCommand(Socket, *FString::Printf(TEXT("<isatend resultset=\"%s\"/>"), *ID)); int32 BytesRead; bool bResult; Socket->Recv((uint8*)&bResult, sizeof(bool), BytesRead); if(BytesRead != sizeof(bool)) { bResult = false; } else { bResult = ntohl(bResult); } return bResult; } /** * Returns a string associated with the passed in field/ column for the current row. * * @param Column Name of column to retrieve data for in current row */ FString FRemoteDataBaseRecordSet::GetString( const TCHAR* Column ) const { ExecuteDBProxyCommand(Socket, *FString::Printf(TEXT("<getstring resultset=\"%s\">%s</getstring>"), *ID, Column)); const int32 BUFSIZE = 2048; int32 BytesRead; int32 StrLength; TCHAR Buf[BUFSIZE]; Socket->Recv((uint8*)&StrLength, sizeof(int32), BytesRead); StrLength = ntohl(StrLength); if(BytesRead != sizeof(int32) || StrLength <= 0) { return TEXT(""); } if(StrLength > BUFSIZE - 1) { StrLength = BUFSIZE - 1; } Socket->Recv((uint8*)Buf, StrLength * sizeof(TCHAR), BytesRead); // TCHAR is assumed to be wchar_t so if we recv an odd # of bytes something messed up occured. Round down to the nearest wchar_t and then convert to number of TCHAR's. BytesRead -= BytesRead & 1; // rounding down BytesRead >>= 1; // conversion // convert from network to host byte order for(int i = 0; i < BytesRead; ++i) { Buf[i] = ntohs(Buf[i]); } Buf[BytesRead] = 0; return FString(Buf); } /** * Returns an integer associated with the passed in field/ column for the current row. * * @param Column Name of column to retrieve data for in current row */ int32 FRemoteDataBaseRecordSet::GetInt( const TCHAR* Column ) const { ExecuteDBProxyCommand(Socket, *FString::Printf(TEXT("<getint resultset=\"%s\">%s</getint>"), *ID, Column)); int32 BytesRead; int32 Value; Socket->Recv((uint8*)&Value, sizeof(int32), BytesRead); return ntohl(Value); } /** * Returns a float associated with the passed in field/ column for the current row. * * @param Column Name of column to retrieve data for in current row */ float FRemoteDataBaseRecordSet::GetFloat( const TCHAR* Column ) const { ExecuteDBProxyCommand(Socket, *FString::Printf(TEXT("<getfloat resultset=\"%s\">%s</getfloat>"), *ID, Column)); int32 BytesRead; int32 Temp; Socket->Recv((uint8*)&Temp, sizeof(int32), BytesRead); Temp = ntohl(Temp); float Value = *((float*)&Temp); return Value; } /** Constructor. */ FRemoteDataBaseRecordSet::FRemoteDataBaseRecordSet(int32 ResultSetID, FSocket *Connection) : Socket(NULL) { check(ResultSetID >= 0); check(Connection); // NOTE: This socket will be deleted by whatever created it (prob an FRemoteDatabaseConnection), not this class. Socket = Connection; ID = FString::Printf(TEXT("%i"), ResultSetID); } /** Virtual destructor as class has virtual functions. */ FRemoteDataBaseRecordSet::~FRemoteDataBaseRecordSet() { // tell the DB proxy to clean up the resources allocated for the result set. ExecuteDBProxyCommand(Socket, *FString::Printf(TEXT("<closeresultset resultset=\"%s\"/>"), *ID)); } #endif #if USE_ADO_INTEGRATION #include "AllowWindowsPlatformTypes.h" /*----------------------------------------------------------------------------- ADO integration for database connectivity -----------------------------------------------------------------------------*/ // Using import allows making use of smart pointers easily. Please post to the list if a workaround such as // using %COMMONFILES% works to hide the localization issues and non default program file folders. //#import "C:\Program files\Common Files\System\Ado\msado15.dll" rename("EOF", "ADOEOF") #import "System\ADO\msado15.dll" rename("EOF", "ADOEOF") //lint !e322 /*----------------------------------------------------------------------------- FADODataBaseRecordSet implementation. -----------------------------------------------------------------------------*/ /** * ADO implementation of database record set. */ class FADODataBaseRecordSet : public FDataBaseRecordSet { private: ADODB::_RecordsetPtr ADORecordSet; protected: /** Moves to the first record in the set. */ virtual void MoveToFirst() { if( !ADORecordSet->BOF || !ADORecordSet->ADOEOF ) { ADORecordSet->MoveFirst(); } } /** Moves to the next record in the set. */ virtual void MoveToNext() { if( !ADORecordSet->ADOEOF ) { ADORecordSet->MoveNext(); } } /** * Returns whether we are at the end. * * @return true if at the end, false otherwise */ virtual bool IsAtEnd() const { return !!ADORecordSet->ADOEOF; } public: /** * Returns a count of the number of records in the record set */ virtual int32 GetRecordCount() const { return ADORecordSet->RecordCount; } /** * Returns a string associated with the passed in field/ column for the current row. * * @param Column Name of column to retrieve data for in current row */ virtual FString GetString( const TCHAR* Column ) const { FString ReturnString; // Retrieve specified column field value for selected row. _variant_t Value = ADORecordSet->GetCollect( Column ); // Check variant type for validity and cast to specified type. _variant_t has overloaded cast operators. if( Value.vt != VT_NULL ) { ReturnString = (TCHAR*)_bstr_t(Value); } // Unknown column. else { ReturnString = TEXT("Unknown Column"); } return ReturnString; } /** * Returns an integer associated with the passed in field/ column for the current row. * * @param Column Name of column to retrieve data for in current row */ virtual int32 GetInt( const TCHAR* Column ) const { int32 ReturnValue = 0; // Retrieve specified column field value for selected row. _variant_t Value = ADORecordSet->GetCollect( Column ); // Check variant type for validity and cast to specified type. _variant_t has overloaded cast operators. if( Value.vt != VT_NULL ) { ReturnValue = (int32)Value; } // Unknown column. else { UE_LOG(LogDataBase, Log, TEXT("Failure retrieving int32 value for column [%s]"),Column); } return ReturnValue; } /** * Returns a float associated with the passed in field/ column for the current row. * * @param Column Name of column to retrieve data for in current row */ virtual float GetFloat( const TCHAR* Column ) const { float ReturnValue = 0; // Retrieve specified column field value for selected row. _variant_t Value = ADORecordSet->GetCollect( Column ); // Check variant type for validity and cast to specified type. _variant_t has overloaded cast operators. if( Value.vt != VT_NULL ) { ReturnValue = (float)Value; } // Unknown column. else { UE_LOG(LogDataBase, Log, TEXT("Failure retrieving float value for column [%s]"),Column); } return ReturnValue; } /** * Returns an int64 associated with the passed in field/ column for the current row. * * @param Column Name of column to retrieve data for in current row */ virtual int64 GetBigInt( const TCHAR* Column ) const { int64 ReturnValue = 0; // Retrieve specified column field value for selected row. _variant_t Value = ADORecordSet->GetCollect( Column ); // Check variant type for validity and cast to specified type. _variant_t has overloaded cast operators. if( Value.vt != VT_NULL ) { ReturnValue = (int64)Value; } // Unknown column. else { UE_LOG(LogDataBase, Log, TEXT("Failure retrieving BIGINT value for column [%s]"),Column); } return ReturnValue; } /** * Returns the set of column names for this Recordset. This is useful for determining * what you can actually ask the record set for without having to hard code those ahead of time. */ virtual TArray<FDatabaseColumnInfo> GetColumnNames() const { TArray<FDatabaseColumnInfo> Retval; if( !ADORecordSet->BOF || !ADORecordSet->ADOEOF ) { ADORecordSet->MoveFirst(); for( int16 i = 0; i < ADORecordSet->Fields->Count; ++i ) { _bstr_t bstrName = ADORecordSet->Fields->Item[i]->Name; _variant_t varValue = ADORecordSet->Fields->Item[i]->Value; ADODB::DataTypeEnum DataType = ADORecordSet->Fields->Item[i]->Type; FDatabaseColumnInfo NewInfo; NewInfo.ColumnName = FString((TCHAR*)_bstr_t(bstrName)); // from http://www.w3schools.com/ado/prop_field_type.asp#datatypeenum switch( DataType ) { case ADODB::adInteger: case ADODB::adBigInt: NewInfo.DataType = DBT_INT; break; case ADODB::adSingle: case ADODB::adDouble: NewInfo.DataType = DBT_FLOAT; break; case ADODB::adWChar: case ADODB::adVarWChar: NewInfo.DataType = DBT_STRING; break; default: UE_LOG(LogDataBase, Warning, TEXT("Unable to find a EDataBaseUE3Types (%s) from DODB::DataTypeEnum DataType: %d "), *NewInfo.ColumnName, static_cast<int32>(DataType) ); NewInfo.DataType = DBT_UNKOWN; break; } Retval.Add( NewInfo ); } } // here for debugging as this code is new. for( int32 i = 0; i < Retval.Num(); ++i ) { UE_LOG(LogDataBase, Warning, TEXT( "ColumnName %d: Name: %s Type: %d"), i, *Retval[i].ColumnName, static_cast<int32>(Retval[i].DataType) ); } return Retval; } /** * Constructor, used to associate ADO record set with this class. * * @param InADORecordSet ADO record set to use */ FADODataBaseRecordSet( ADODB::_RecordsetPtr InADORecordSet ) : ADORecordSet( InADORecordSet ) { } /** Destructor, cleaning up ADO record set. */ virtual ~FADODataBaseRecordSet() { if(ADORecordSet && (ADORecordSet->State & ADODB::adStateOpen)) { // We're using smart pointers so all we need to do is close and assign NULL. ADORecordSet->Close(); } ADORecordSet = NULL; } }; /*----------------------------------------------------------------------------- FADODataBaseConnection implementation. -----------------------------------------------------------------------------*/ /** * Data base connection class using ADO C++ interface to communicate with SQL server. */ class FADODataBaseConnection : public FDataBaseConnection { private: /** ADO database connection object. */ ADODB::_ConnectionPtr DataBaseConnection; public: /** Constructor, initializing all member variables. */ FADODataBaseConnection() { DataBaseConnection = NULL; } /** Destructor, tearing down connection. */ virtual ~FADODataBaseConnection() { Close(); } /** * Opens a connection to the database. * * @param ConnectionString Connection string passed to database layer * @param RemoteConnectionIP The IP address which the RemoteConnection should connect to * @param RemoteConnectionStringOverride The connection string which the RemoteConnection is going to utilize * * @return true if connection was successfully established, false otherwise */ virtual bool Open( const TCHAR* ConnectionString, const TCHAR* RemoteConnectionIP, const TCHAR* RemoteConnectionStringOverride ) { if (!FWindowsPlatformMisc::CoInitialize()) { return false; } // Create instance of DB connection object. HRESULT hr = DataBaseConnection.CreateInstance(__uuidof(ADODB::Connection)); if (FAILED(hr)) { FWindowsPlatformMisc::CoUninitialize(); throw _com_error(hr); } // Open the connection. Operation is synchronous. DataBaseConnection->Open( ConnectionString, TEXT(""), TEXT(""), ADODB::adConnectUnspecified ); return true; } /** * Closes connection to database. */ virtual void Close() { // Close database connection if exists and free smart pointer. if( DataBaseConnection && (DataBaseConnection->State & ADODB::adStateOpen)) { DataBaseConnection->Close(); FWindowsPlatformMisc::CoUninitialize(); } DataBaseConnection = NULL; } /** * Executes the passed in command on the database. * * @param CommandString Command to execute * * @return true if execution was successful, false otherwise */ virtual bool Execute( const TCHAR* CommandString ) { // Execute command, passing in optimization to tell DB to not return records. DataBaseConnection->Execute( CommandString, NULL, ADODB::adExecuteNoRecords ); return true; } /** * Executes the passed in command on the database. The caller is responsible for deleting * the created RecordSet. * * @param CommandString Command to execute * @param RecordSet Reference to recordset pointer that is going to hold result * * @return true if execution was successful, false otherwise */ virtual bool Execute( const TCHAR* CommandString, FDataBaseRecordSet*& RecordSet ) { // Initialize return value. RecordSet = NULL; // Create instance of record set. ADODB::_RecordsetPtr ADORecordSet = NULL; ADORecordSet.CreateInstance(__uuidof(ADODB::Recordset) ); // Execute the passed in command on the record set. The recordset returned will be in open state so you can call Get* on it directly. ADORecordSet->Open( CommandString, _variant_t((IDispatch *) DataBaseConnection), ADODB::adOpenStatic, ADODB::adLockReadOnly, ADODB::adCmdText ); // Create record set from returned data. RecordSet = new FADODataBaseRecordSet( ADORecordSet ); return RecordSet != NULL; } }; #include "HideWindowsPlatformTypes.h" #endif // USE_ADO_INTEGRATION /*----------------------------------------------------------------------------- FDataBaseConnection implementation. -----------------------------------------------------------------------------*/ /** * Static function creating appropriate database connection object. * * @return instance of platform specific database connection object */ FDataBaseConnection* FDataBaseConnection::CreateObject() { if( FParse::Param( FCommandLine::Get(), TEXT("NODATABASE") ) ) { UE_LOG(LogDataBase, Log, TEXT("DB usage disabled, please ignore failure messages.")); return NULL; } #if USE_ADO_INTEGRATION return new FADODataBaseConnection(); #elif USE_REMOTE_INTEGRATION return new FRemoteDatabaseConnection(); #else return new FDataBaseConnection(); #endif }
27.336691
175
0.682457
[ "object" ]
dbafdfd81028f0af92c2c1a694954f5c0cda4b34
86,516
cpp
C++
src/mod/pop/ecattr_extensions.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
7
2021-03-02T02:27:18.000Z
2022-02-18T00:56:28.000Z
src/mod/pop/ecattr_extensions.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
3
2021-11-29T15:53:02.000Z
2022-02-21T13:09:22.000Z
src/mod/pop/ecattr_extensions.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
5
2021-03-04T20:26:11.000Z
2021-11-26T07:09:24.000Z
#include "mod.h" #include "mod/pop/kv_conditional.h" #include "stub/tfbot.h" #include "stub/populators.h" #include "stub/strings.h" #include "stub/gamerules.h" #include "stub/tfbot_behavior.h" #include "stub/misc.h" #include "stub/server.h" #include "stub/particles.h" #include "util/iterate.h" #include "util/clientmsg.h" #include "mod/pop/pointtemplate.h" #include "mod/pop/common.h" #include "mod/pop/popmgr_extensions.h" // update data with every call to: // - CTFBot::OnEventChangeAttributes // (verify that this does get called even for the initial default set of settings when spawning) // clear data with every call to: // - CTFBot::~CTFBot (D0+D2) // - CTFBot::Event_Killed // - CTFBot::ChangeTeam(TEAM_SPECTATOR) // - CTFBot::ForceChangeTeam(TEAM_SPECTATOR) // we probably want maps of: // - CHandle<CTFBot> -> their CTFBotSpawner of origin // - CHandle<CTFBot> -> their current EventChangeAttributes_t * (in their CTFBotSpawner of origin) #define PLAYER_ANIM_WEARABLE_ITEM_ID 12138 class PlayerBody : public IBody { public: CBaseEntity * GetEntity() {return vt_GetEntity(this);} private: static MemberVFuncThunk<PlayerBody *, CBaseEntity*> vt_GetEntity; }; MemberVFuncThunk<PlayerBody *, CBaseEntity* > PlayerBody::vt_GetEntity (TypeName<PlayerBody>(), "PlayerBody::GetEntity"); #ifdef ADD_EXTATTR namespace Mod::Pop::ECAttr_Extensions { IForward *custom_item_get_def_id; IForward *custom_item_equip_itemname; IForward *custom_item_set_attribute; struct HomingRockets { bool enable = false; bool ignore_disguised_spies = true; bool ignore_stealthed_spies = true; bool follow_crosshair = false; float speed = 1.0f; float turn_power = 10.0f; float min_dot_product = -0.25f; float aim_time = 9999.0f; float acceleration = 0.0f; float acceleration_time = 9999.0f; float acceleration_start = 0.0f; float gravity = 0.0f; }; enum AimAt { AIM_DEFAULT, AIM_HEAD, AIM_BODY, AIM_FEET }; struct EventChangeAttributesData { std::map<std::string,std::map<std::string, std::string>> custom_attrs; int skin = -1; std::map<std::string, int> bodygroup; AimAt aim_at = AIM_DEFAULT; Vector aim_offset = vec3_origin; float aim_lead_target_speed = 0.0f; int rocket_jump_type = 0; float head_rotate_speed = -1.0f; float tracking_interval = -1.0f; std::string use_custom_model; // 1 - No sap attribute // 2 - Can be sapped int use_human_model = 0; bool use_buster_model = false; bool use_human_animations = false; float ring_of_fire = -1.0f; bool use_melee_threat_prioritization = false; bool always_glow = false; bool no_glow = false; bool no_bomb_upgrade = false; bool use_best_weapon = false; bool fast_update = false; bool no_pushaway = false; bool no_crouch_button_release = false; float scale_speed = 1.0f; float spell_drop_rate_common = 0.0f; float spell_drop_rate_rare = 0.0f; bool spell_drop = false; bool eye_particle_color = false; uint8 eye_particle_r = 0; uint8 eye_particle_g = 0; uint8 eye_particle_b = 0; std::string death_sound = "DEF"; std::string pain_sound = "DEF"; std::map<CHandle<CTFWeaponBase>, float> projectile_speed_cache; std::vector<ShootTemplateData> shoot_templ; std::string fire_sound = ""; std::map<int, std::string> custom_weapon_models; std::string rocket_custom_model; std::string rocket_custom_particle; std::string custom_eye_particle = ""; HomingRockets homing_rockets; std::map<int, float> weapon_resists; std::map<std::string, color32> item_colors; std::map<std::string, std::string> item_models; std::vector<int> strip_item_slot; std::vector<AddCond> dmgappliesconds; std::vector<AddCond> addconds; std::vector<PeriodicTaskImpl> periodic_tasks; bool has_override_step_sound; std::string override_step_sound; std::vector<std::string> strip_item; CRC32_t spray_file; }; /* maps ECAttr instances -> extra data instances */ std::map<CTFBot::EventChangeAttributes_t *, EventChangeAttributesData> extdata; /* maps CTFBot instances -> their current ECAttr instance */ std::unordered_map<CTFBot *, EventChangeAttributesData *> ecattr_map; std::vector<DelayedAddCond> delayed_addconds; std::vector<PeriodicTask> pending_periodic_tasks; #if 0 /* maps CTFBot instances -> their current ECAttr name */ std::map<CHandle<CTFBot>, std::string> ecattr_map; #endif std::unordered_map<std::string, CTFItemDefinition*> item_defs; std::unordered_map<std::string, bool> item_custom_remap; #if 0 const std::string& GetCurrentTFBotECAttrName(CTFBot *bot) { CHandle<CTFBot> handle = bot; auto it = ecattr_map.find(handle); if (it == ecattr_map.end()) { return "default"; } return *it; } #endif // ecattr_map: // clear in OnUnload and SetEnabled(false) // update every time CTFBot::OnEventChangeAttributes is called // EventChangeAttributesData *GetDataForBot(CTFBot *bot) { if (bot == nullptr) return nullptr; auto it = ecattr_map.find(bot); if (it == ecattr_map.end()) { return nullptr; } return it->second; } EventChangeAttributesData *GetDataForBot(CBaseEntity *bot) { return GetDataForBot(ToTFBot(bot)); } enum ClearAction { DESTRUCT, DIE, CHANGE }; void ClearAllData() { ecattr_map.clear(); extdata.clear(); item_defs.clear(); item_custom_remap.clear(); delayed_addconds.clear(); pending_periodic_tasks.clear(); } void ClearDataForBot(CTFBot *bot, ClearAction clear_action) { if (clear_action != DESTRUCT) { auto data = GetDataForBot(bot); if (data != nullptr && data->use_human_animations) { for(int i = 0; i < bot->GetNumWearables(); i++) { CEconWearable *wearable = bot->GetWearable(i); if (wearable != nullptr && wearable->GetItem() != nullptr && wearable->GetItem()->m_iItemDefinitionIndex == PLAYER_ANIM_WEARABLE_ITEM_ID) { int model_index = wearable->m_nModelIndexOverrides[0]; bot->GetPlayerClass()->SetCustomModel(modelinfo->GetModelName(modelinfo->GetModel(model_index)), true); wearable->Remove(); } } if (bot->GetRenderMode() == 1) { servertools->SetKeyValue(bot, "rendermode", "0"); bot->SetRenderColorA(255); } } } ecattr_map.erase(bot); for (auto it = delayed_addconds.begin(); it != delayed_addconds.end(); ) { if ((*it).bot == bot) { it = delayed_addconds.erase(it); } else { ++it; } } for (auto it = pending_periodic_tasks.begin(); it != pending_periodic_tasks.end(); ) { if ((*it).bot == bot) { it = pending_periodic_tasks.erase(it); } else { ++it; } } } DETOUR_DECL_MEMBER(void, CTFBot_dtor0) { auto bot = reinterpret_cast<CTFBot *>(this); // DevMsg("CTFBot %08x: dtor0, clearing data\n", (uintptr_t)bot); ClearDataForBot(bot, DESTRUCT); DETOUR_MEMBER_CALL(CTFBot_dtor0)(); } DETOUR_DECL_MEMBER(void, CTFBot_dtor2) { auto bot = reinterpret_cast<CTFBot *>(this); // DevMsg("CTFBot %08x: dtor2, clearing data\n", (uintptr_t)bot); ClearDataForBot(bot, DESTRUCT); DETOUR_MEMBER_CALL(CTFBot_dtor2)(); } DETOUR_DECL_MEMBER(void, CTFPlayer_StateEnter, int nState) { auto player = reinterpret_cast<CTFPlayer *>(this); if (nState == TF_STATE_WELCOME || nState == TF_STATE_OBSERVER) { CTFBot *bot = ToTFBot(player); if (bot != nullptr) { ClearDataForBot(bot, DIE); } } DETOUR_MEMBER_CALL(CTFPlayer_StateEnter)(nState); } DETOUR_DECL_MEMBER(void, CTFPlayer_StateLeave) { auto player = reinterpret_cast<CTFPlayer *>(this); if (player->StateGet() == TF_STATE_WELCOME || player->StateGet() == TF_STATE_OBSERVER) { CTFBot *bot = ToTFBot(player); if (bot != nullptr) { // DevMsg("Bot #%d [\"%s\"]: StateLeave %s, clearing data\n", ENTINDEX(bot), bot->GetPlayerName(), GetStateName(bot->StateGet())); ClearDataForBot(bot, DIE); } } DETOUR_MEMBER_CALL(CTFPlayer_StateLeave)(); } CTFBotSpawner *current_spawner = nullptr; KeyValues *current_spawner_kv = nullptr; //Contains ecattr extra data for the currently parsed spawner std::unordered_map<int, EventChangeAttributesData> spawner_ecattr; void CopyEvent(CTFBot::EventChangeAttributes_t& orig, const CTFBot::EventChangeAttributes_t& copy) { orig.m_iSkill = copy.m_iSkill; orig.m_nWeaponRestrict = copy.m_nWeaponRestrict; orig.m_nMission = copy.m_nMission; orig.pad_10 = copy.pad_10; orig.m_nBotAttrs = copy.m_nBotAttrs; orig.m_flVisionRange = copy.m_flVisionRange; orig.m_ItemNames.RemoveAll(); orig.m_ItemAttrs.RemoveAll(); orig.m_CharAttrs.RemoveAll(); orig.m_Tags.RemoveAll(); for (int i=0; i<copy.m_ItemNames.Count(); ++i) { orig.m_ItemNames.CopyAndAddToTail(copy.m_ItemNames[i]); } orig.m_ItemAttrs = copy.m_ItemAttrs; orig.m_CharAttrs = copy.m_CharAttrs; for (int i=0; i<copy.m_Tags.Count(); ++i) { orig.m_Tags.CopyAndAddToTail(copy.m_Tags[i]); } } DETOUR_DECL_MEMBER(bool, CTFBotSpawner_Parse, KeyValues *kv_orig) { auto spawner = reinterpret_cast<CTFBotSpawner *>(this); current_spawner = spawner; current_spawner_kv = kv_orig; spawner_ecattr.clear(); auto result = DETOUR_MEMBER_CALL(CTFBotSpawner_Parse)(kv_orig); CTFBot::EventChangeAttributes_t *default_ecattr = nullptr; for (int i = 0; i < spawner->m_ECAttrs.Count(); i++) { extdata[&spawner->m_ECAttrs[i]] = spawner_ecattr[i+1]; if (default_ecattr == nullptr && strcmp(spawner->m_ECAttrs[i].m_strName.Get(), "DefaultSigOverride") == 0) { default_ecattr = &spawner->m_ECAttrs[i]; default_ecattr->m_strName.Set("Default"); CopyEvent(spawner->m_DefaultAttrs, *default_ecattr); extdata[&spawner->m_DefaultAttrs] = spawner_ecattr[i + 1]; } } if (default_ecattr == nullptr) { extdata[&spawner->m_DefaultAttrs] = spawner_ecattr[0]; } return result; } ConVar cvar_no_romevision("sig_no_romevision_cosmetics", "0", FCVAR_NONE, "Disable romevision cosmetics"); ConVar cvar_creators_custom_item("sig_creators_custom_item", "0", FCVAR_NONE, "Enable fallback to creators custom item"); void Parse_WeaponResist(EventChangeAttributesData &data, KeyValues *kv) { FOR_EACH_SUBKEY(kv, subkey) { const char *name = subkey->GetName(); int weapon_id = GetWeaponId(name); if (weapon_id == TF_WEAPON_NONE) { Warning("Unknown weapon ID \'%s\' in WeaponResist block.\n", name); continue; } DevMsg("CTFBotSpawner %08x: resist %s (0x%02x): %4.02f\n", (uintptr_t)&data, name, weapon_id, subkey->GetFloat()); data.weapon_resists[weapon_id] = subkey->GetFloat(); } } void Parse_ItemColor(EventChangeAttributesData &data, KeyValues *kv) { const char *item_name = ""; int color_r = 0x00; int color_g = 0x00; int color_b = 0x00; bool got_name = false; bool got_col_r = false; bool got_col_g = false; bool got_col_b = false; FOR_EACH_SUBKEY(kv, subkey) { const char *name = subkey->GetName(); if (FStrEq(name, "ItemName")) { item_name = subkey->GetString(); got_name = true; } else if (FStrEq(name, "Red")) { color_r = Clamp(subkey->GetInt(), 0x00, 0xff); got_col_r = true; } else if (FStrEq(name, "Green")) { color_g = Clamp(subkey->GetInt(), 0x00, 0xff); got_col_g = true; } else if (FStrEq(name, "Blue")) { color_b = Clamp(subkey->GetInt(), 0x00, 0xff); got_col_b = true; } else { Warning("Unknown key \'%s\' in ItemColor block.\n", name); } } if (!got_name) { Warning("No ItemName specified in ItemColor block.\n"); return; } if (!got_col_r) { Warning("No Red color value specified in ItemColor block.\n"); return; } if (!got_col_g) { Warning("No Green color value specified in ItemColor block.\n"); return; } if (!got_col_b) { Warning("No Blue color value specified in ItemColor block.\n"); return; } DevMsg("CTFBotSpawner %08x: add ItemColor(\"%s\", %02X%02X%02X)\n", (uintptr_t)&data, item_name, color_r, color_g, color_b); data.item_colors[item_name] = { color_r, color_g, color_b, 0xff }; } void Parse_ItemModel(EventChangeAttributesData &data, KeyValues *kv) { const char *item_name = ""; const char *model_name = ""; bool got_name = false; bool got_model = false; FOR_EACH_SUBKEY(kv, subkey) { const char *name = subkey->GetName(); if (FStrEq(name, "ItemName")) { item_name = subkey->GetString(); got_name = true; } else if (FStrEq(name, "Model")) { model_name = subkey->GetString(); got_model = true; } else { Warning("Unknown key \'%s\' in ItemModel block.\n", name); } } if (!got_name) { Warning("No ItemName specified in ItemModel block.\n"); return; } if (!got_model) { Warning("No Model value specified in ItemModel block.\n"); return; } DevMsg("CTFBotSpawner %08x: add ItemModel(\"%s\", \"%s\")\n", (uintptr_t)&data, item_name, model_name); data.item_models[item_name] = model_name; } void Parse_CustomWeaponModel(EventChangeAttributesData &data, KeyValues *kv) { int slot = -1; const char *path = ""; bool got_slot = false; bool got_path = false; FOR_EACH_SUBKEY(kv, subkey) { const char *name = subkey->GetName(); if (FStrEq(name, "Slot")) { if (subkey->GetDataType() == KeyValues::TYPE_STRING) { slot = GetLoadoutSlotByName(subkey->GetString()); } else { slot = subkey->GetInt(); } got_slot = true; } else if (FStrEq(name, "Model")) { path = subkey->GetString(); got_path = true; } else { Warning("Unknown key \'%s\' in CustomWeaponModel block.\n", name); } } if (!got_slot) { Warning("No weapon slot specified in CustomWeaponModel block.\n"); return; } if (!got_path) { Warning("No Model path specified in CustomWeaponModel block.\n"); return; } if (slot < LOADOUT_POSITION_PRIMARY || slot > LOADOUT_POSITION_PDA2) { Warning("CustomWeaponModel Slot must be in the inclusive range [LOADOUT_POSITION_PRIMARY, LOADOUT_POSITION_PDA2], i.e. [%d, %d].\n", (int)LOADOUT_POSITION_PRIMARY, (int)LOADOUT_POSITION_PDA2); return; } DevMsg("CTFBotSpawner %08x: add CustomWeaponModel(%d, \"%s\")\n", (uintptr_t)&data, slot, path); data.custom_weapon_models[slot] = path; } void Parse_HomingRockets(EventChangeAttributesData &data, KeyValues *kv) { HomingRockets& hr = data.homing_rockets; hr.enable = true; FOR_EACH_SUBKEY(kv, subkey) { const char *name = subkey->GetName(); if (FStrEq(name, "IgnoreDisguisedSpies")) { hr.ignore_disguised_spies = subkey->GetBool(); } else if (FStrEq(name, "IgnoreStealthedSpies")) { hr.ignore_stealthed_spies = subkey->GetBool(); } else if (FStrEq(name, "FollowCrosshair")) { hr.follow_crosshair = subkey->GetBool(); } else if (FStrEq(name, "RocketSpeed")) { hr.speed = subkey->GetFloat(); } else if (FStrEq(name, "TurnPower")) { hr.turn_power = subkey->GetFloat(); } else if (FStrEq(name, "MinDotProduct")) { hr.min_dot_product = Clamp(subkey->GetFloat(), -1.0f, 1.0f); } else if (FStrEq(name, "MaxAimError")) { hr.min_dot_product = std::cos(DEG2RAD(Clamp(subkey->GetFloat(), 0.0f, 180.0f))); } else if (FStrEq(name, "AimTime")) { hr.aim_time = subkey->GetFloat(); } else if (FStrEq(name, "Acceleration")) { hr.acceleration = subkey->GetFloat(); } else if (FStrEq(name, "AccelerationTime")) { hr.acceleration_time = subkey->GetFloat(); } else if (FStrEq(name, "AccelerationStartTime")) { hr.acceleration_start = subkey->GetFloat(); } else if (FStrEq(name, "Gravity")) { hr.gravity = subkey->GetFloat(); } else if (FStrEq(name, "Enable")) { /* this used to be a parameter but it was redundant and has been removed; * ignore it without issuing a warning */ } else { Warning("Unknown key \'%s\' in HomingRockets block.\n", name); } } DevMsg("CTFBotSpawner %08x: set HomingRockets(%s, %s, %.2f, %.1f, %.2f)\n", (uintptr_t)&data, (hr.ignore_disguised_spies ? "true" : "false"), (hr.ignore_stealthed_spies ? "true" : "false"), hr.speed, hr.turn_power, hr.min_dot_product); } void Parse_DamageAppliesCond(EventChangeAttributesData &data, KeyValues *kv) { AddCond addcond; bool got_cond = false; bool got_duration = false; FOR_EACH_SUBKEY(kv, subkey) { const char *name = subkey->GetName(); if (FStrEq(name, "Index")) { addcond.cond = (ETFCond)subkey->GetInt(); got_cond = true; } else if (FStrEq(name, "Name")) { ETFCond cond = GetTFConditionFromName(subkey->GetString()); if (cond != -1) { addcond.cond = cond; got_cond = true; } else { Warning("Unrecognized condition name \"%s\" in DamageAppliesCond block.\n", subkey->GetString()); } } else if (FStrEq(name, "Duration")) { addcond.duration = subkey->GetFloat(); got_duration = true; } else if (FStrEq(name, "IfHealthBelow")) { addcond.health_below = subkey->GetInt(); } else if (FStrEq(name, "IfHealthAbove")) { addcond.health_above = subkey->GetInt(); } else { Warning("Unknown key \'%s\' in DamageAppliesCond block.\n", name); } } if (!got_cond) { Warning("Could not find a valid condition index/name in DamageAppliesCond block.\n"); return; } DevMsg("CTFBotSpawner %08x: add DamageAppliesCond(%d, %f)\n", (uintptr_t)&data, addcond.cond, addcond.duration); data.dmgappliesconds.push_back(addcond); } void Parse_Bodygroup(EventChangeAttributesData &data, KeyValues *kv) { const char *bodygroup = nullptr; int value = -1; FOR_EACH_SUBKEY(kv, subkey) { const char *name = subkey->GetName(); if (FStrEq(name, "Name")) { bodygroup = subkey->GetString(); } else if (FStrEq(name, "Value")) { value = subkey->GetInt(); } else { Warning("Unknown key \'%s\' in Bodygroup block.\n", name); } } if (value == -1 || bodygroup == nullptr) { Warning("Invalid Bodygroup block.\n"); return; } data.bodygroup[bodygroup] = value; } AimAt Parse_AimAt(KeyValues *kv) { const char * aim = kv->GetString(); if (FStrEq(aim, "Default")){ return AIM_DEFAULT; } else if (FStrEq(aim, "Head")){ return AIM_HEAD; } else if (FStrEq(aim, "Body")){ return AIM_BODY; } else if (FStrEq(aim, "Feet")){ return AIM_FEET; } else return AIM_DEFAULT; } void Parse_SprayFile(EventChangeAttributesData &data, KeyValues *kv) { CRC32_t value; if (LoadUserDataFile(value, kv->GetString())) { data.spray_file = value; } else { Warning("CTFBotSpawner: Spray file %s not found\n", kv->GetString()); } } CTFBot::EventChangeAttributes_t *default_ecattr = nullptr; CTFBotSpawner *last_spawner = nullptr; CTFBot::EventChangeAttributes_t *last_ecattr = nullptr; int parse_dynamic_index = 0; #warning __gcc_regcall detours considered harmful! DETOUR_DECL_STATIC_CALL_CONVENTION(__gcc_regcall, bool, ParseDynamicAttributes, CTFBot::EventChangeAttributes_t &ecattr, KeyValues *kv) { // Copy from default ecattr to this ecattr int data_index = parse_dynamic_index; if (parse_dynamic_index == 0 && default_ecattr != nullptr) { data_index = last_spawner->m_ECAttrs.Count(); if (last_ecattr != &ecattr) { CTFBot::EventChangeAttributes_t * copy_from = default_ecattr; //int copy_from_index = -1; for (int i = 0; i < last_spawner->m_ECAttrs.Count(); i++) { if (&ecattr != &last_spawner->m_ECAttrs[i] && FStrEq(last_spawner->m_ECAttrs[i].m_strName.Get(), ecattr.m_strName.Get())) { parse_dynamic_index = i + 1; bool result = Detour_ParseDynamicAttributes(current_spawner->m_ECAttrs[i], kv); parse_dynamic_index = 0; return result; //copy_from = &last_spawner->m_ECAttrs[i]; //copy_from_index = i; //break; } } last_ecattr = &ecattr; //if (copy) CopyEvent(ecattr, *copy_from); spawner_ecattr[data_index] = spawner_ecattr[0]; } } // Copy from this default ecattr to all ecattr if ((&ecattr) == &current_spawner->m_DefaultAttrs) { for (int i = 0; i < current_spawner->m_ECAttrs.Count(); i++) { parse_dynamic_index = i + 1; if (!Detour_ParseDynamicAttributes(current_spawner->m_ECAttrs[i], kv)){ parse_dynamic_index = 0; return false; } parse_dynamic_index = 0; } } auto &data = spawner_ecattr[data_index]; const char *name = kv->GetName(); bool found = true; if (FStrEq(name, "Skin")) { data.skin = kv->GetInt(); } else if (FStrEq(name, "AimAt")) { data.aim_at = Parse_AimAt(kv); } else if (FStrEq(name, "AimOffset")) { Vector offset; sscanf(kv->GetString(),"%f %f %f",&offset.x,&offset.y,&offset.z); data.aim_offset = offset; } else if (FStrEq(name, "AimLeadProjectileSpeed")) { data.aim_lead_target_speed = kv->GetFloat(); } else if (FStrEq(name, "RocketJump")) { data.rocket_jump_type = kv->GetInt(); } else if (FStrEq(name, "AimTrackingInterval")) { data.tracking_interval = kv->GetFloat(); } else if (FStrEq(name, "HeadRotateSpeed")) { data.head_rotate_speed = kv->GetFloat(); } else if (FStrEq(name, "WeaponRestrictions")) { const char *val = kv->GetString(); if (FStrEq(val, "PDAOnly")) ecattr.m_nWeaponRestrict = CTFBot::WeaponRestriction::PDA_ONLY; else if (FStrEq(val, "BuildingOnly")) ecattr.m_nWeaponRestrict = CTFBot::WeaponRestriction::BUILDING_ONLY; else found = false; } else if (FStrEq(name, "UseBusterModel")) { data.use_buster_model = kv->GetBool(); } else if (FStrEq(name, "UseCustomModel")) { data.use_custom_model = kv->GetString(); } else if (FStrEq(name, "UseHumanModel")) { data.use_human_model = kv->GetInt(); } else if (FStrEq(name, "UseHumanAnimations")) { data.use_human_animations = kv->GetBool(); } else if (FStrEq(name, "AlwaysGlow")) { data.always_glow = kv->GetBool(); } else if (FStrEq(name, "NoGlow")) { data.always_glow = kv->GetBool(); } else if (FStrEq(name, "UseBestWeapon")) { data.use_best_weapon = kv->GetBool(); } else if (FStrEq(name, "RingOfFire")) { data.ring_of_fire = kv->GetFloat(); } else if (FStrEq(name, "UseMeleeThreatPrioritization")) { data.use_melee_threat_prioritization = kv->GetBool(); } else if (FStrEq(name, "NoBombUpgrades")) { data.no_bomb_upgrade = kv->GetBool(); } else if (FStrEq(name, "DeathSound")) { data.death_sound = kv->GetString(); if (!enginesound->PrecacheSound(kv->GetString(), true)) CBaseEntity::PrecacheScriptSound(kv->GetString()); } else if (FStrEq(name, "PainSound")) { data.pain_sound = kv->GetString(); if (!enginesound->PrecacheSound(kv->GetString(), true)) CBaseEntity::PrecacheScriptSound(kv->GetString()); } else if (FStrEq(name, "WeaponResist")) { Parse_WeaponResist(data, kv); } else if (FStrEq(name, "ItemColor")) { Parse_ItemColor(data, kv); } else if (FStrEq(name, "ItemModel")) { Parse_ItemModel(data, kv); } else if (FStrEq(name, "HomingRockets")) { Parse_HomingRockets(data, kv); } else if (FStrEq(name, "CustomWeaponModel")) { Parse_CustomWeaponModel(data, kv); } else if (FStrEq(name, "RocketCustomModel")) { data.rocket_custom_model = kv->GetString(); } else if (FStrEq(name, "RocketCustomParticle")) { data.rocket_custom_particle = kv->GetString(); } else if (FStrEq(name, "ShootTemplate")) { ShootTemplateData shootdata; if (Parse_ShootTemplate(shootdata, kv)) data.shoot_templ.push_back(shootdata); } else if (FStrEq(name, "DamageAppliesCond")) { Parse_DamageAppliesCond(data, kv); } else if (FStrEq(name, "FireSound")) { data.fire_sound = kv->GetString();//AllocPooledString(subkey->GetString()); if (!enginesound->PrecacheSound(kv->GetString(), true)) CBaseEntity::PrecacheScriptSound(kv->GetString()); } else if (FStrEq(name, "Bodygroup")) { Parse_Bodygroup(data, kv); } else if (FStrEq(name, "FastUpdate")) { data.fast_update = kv->GetBool(); } else if (FStrEq(name, "NoPushaway")) { data.no_pushaway = kv->GetBool(); } else if (FStrEq(name, "BodyPartScaleSpeed")) { data.scale_speed = kv->GetFloat(); } else if (FStrEq(name, "NoCrouchButtonRelease")) { data.no_crouch_button_release = kv->GetBool(); } else if (FStrEq(name, "CustomEyeParticle")) { data.custom_eye_particle = kv->GetString(); } else if (FStrEq(name, "CustomEyeGlowColor")) { data.eye_particle_color = true; sscanf(kv->GetString(), "%d %d %d", &data.eye_particle_r, &data.eye_particle_g, &data.eye_particle_b); } else if (FStrEq(name, "StripItemSlot")) { int val = GetLoadoutSlotByName(kv->GetString()); data.strip_item_slot.push_back(val == -1 ? kv->GetInt() : val); } else if (FStrEq(name, "SprayFile")) { Parse_SprayFile(data, kv); } else if (FStrEq(name, "SpellDropRateCommon")) { data.spell_drop_rate_common = Clamp(kv->GetFloat(), 0.0f, 1.0f); data.spell_drop = true; } else if (FStrEq(name, "SpellDropRateRare")) { data.spell_drop_rate_rare = Clamp(kv->GetFloat(), 0.0f, 1.0f); data.spell_drop = true; } else if (FStrEq(name, "AdditionalStepSound")) { data.override_step_sound = kv->GetString(); data.has_override_step_sound = true; if (!enginesound->PrecacheSound(kv->GetString(), true)) CBaseEntity::PrecacheScriptSound(kv->GetString()); } else if (FStrEq(name, "StripItem")) { data.strip_item.push_back(kv->GetString()); } else { found = false; } // Separate conditions that do not apply on default ecattr if (!found && default_ecattr != nullptr) { found = true; if (FStrEq(name, "AddCond")) { Parse_AddCond(data.addconds, kv); } else if (Parse_PeriodicTask(data.periodic_tasks, kv, name)) { } else { found = false; } } if (found) return true; if (!cvar_creators_custom_item.GetBool()) return DETOUR_STATIC_CALL(ParseDynamicAttributes)(ecattr, kv); //DevMsg("ParseDynamicAttributesTFBot: \"%s\" \"%s\"\n", kv->GetName(), kv->GetString()); CFastTimer timer2; timer2.Start(); if (FStrEq(kv->GetName(), "ItemAttributes")) { //DevMsg("Item Attributes\n"); std::map<std::string, std::string> attribs; std::string item_name = ""; std::vector<KeyValues *> del_kv; std::string classname; FOR_EACH_SUBKEY( kv, subkey ) { if (FStrEq(subkey->GetName(), "ItemName")) { item_name = subkey->GetString(); auto it = item_defs.find(item_name); CTFItemDefinition *item_def; if (it != item_defs.end()) { item_def = it->second; } else { item_def = static_cast<CTFItemDefinition *>(GetItemSchema()->GetItemDefinitionByName(item_name.c_str())); item_defs[item_name] = item_def; } if (item_def == nullptr) { auto it_remap = item_custom_remap.find(item_name); if (it_remap == item_custom_remap.end() || it_remap->second) { int class_index = current_spawner->m_iClass; if (class_index == 0) { classname = current_spawner_kv->GetString("Class", ""); class_index = GetClassIndexFromString(classname.c_str()); } // Creators.tf Custom Weapons handling // engine->ServerCommand(CFmtStr("ce_mvm_get_itemdef_id \"%s\" \"%s\"\n", item_name.c_str(), classname.c_str())); // engine->ServerExecute(); cell_t result = 0; cell_t item_id_result = -1; custom_item_get_def_id->PushString(item_name.c_str()); custom_item_get_def_id->PushCell(class_index); custom_item_get_def_id->PushCellByRef(&item_id_result); custom_item_get_def_id->Execute(&result); DevMsg("Custom item name %s\n",item_name.c_str()); if (item_id_result != -1) { item_def = static_cast<CTFItemDefinition *>(GetItemSchema()->GetItemDefinition(item_id_result)); std::string newname = item_def->GetName(""); item_custom_remap[item_name] = true; DevMsg("Added custom item %s to reg %s\n",item_name.c_str(), newname.c_str()); subkey->SetStringValue(newname.c_str()); item_name = newname; } else { item_custom_remap[item_name] = false; DevMsg("Not found item %s, shown %d\n",item_name.c_str(),item_id_result); //item_custom_remap[item_name] = ""; } } } } else { //DevMsg("attribute Name %s\n",subkey->GetName()); if (current_spawner != nullptr && GetItemSchema()->GetAttributeDefinitionByName(subkey->GetName()) == nullptr) { DevMsg("Found unknown attribute %s\n",subkey->GetName()); attribs[subkey->GetName()] = subkey->GetString(); del_kv.push_back(subkey); } } } for (auto subkey : del_kv) { kv->RemoveSubKey(subkey); subkey->deleteThis(); } data.custom_attrs[item_name] = attribs; //DevMsg("put event changed attributes data %s %d %d\n",item_name.c_str(), attribs.size(), &ecattr); } //DevMsg(" Passing through to actual ParseDynamicAttributes\n"); return DETOUR_STATIC_CALL(ParseDynamicAttributes)(ecattr, kv); } DETOUR_DECL_MEMBER(bool, CPopulationManager_Parse) { ClearAllData(); return DETOUR_MEMBER_CALL(CPopulationManager_Parse)(); } DETOUR_DECL_MEMBER(bool, CTFBotSpawner_ParseEventChangeAttributes, KeyValues *data) { FOR_EACH_SUBKEY(data, subkey) { if (FStrEq(subkey->GetName(),"Default")) { subkey->SetName("DefaultSigOverride"); } } default_ecattr = &reinterpret_cast<CTFBotSpawner *>(this)->m_DefaultAttrs; last_ecattr = nullptr; last_spawner = reinterpret_cast<CTFBotSpawner *>(this); bool result = DETOUR_MEMBER_CALL(CTFBotSpawner_ParseEventChangeAttributes)(data); default_ecattr = nullptr; return result; } bool HasRobotBlood(CTFPlayer *player) { static ConVarRef sig_mvm_bots_bleed("sig_mvm_bots_bleed"); //static ConVarRef sig_mvm_bots_are_humans("sig_mvm_bots_are_humans"); if (*(player->GetPlayerClass()->GetCustomModel()) == 0 ) return true; if (sig_mvm_bots_bleed.GetBool()) return true; auto data = GetDataForBot(player); if (data != nullptr && data->use_human_model) return true; return false; } void SetEyeColorForDiff(Vector &vec, int difficulty) { switch (difficulty) { case 0: vec.Init( 0, 240, 255 ); break; case 1: vec.Init( 0, 120, 255 ); break; case 2: vec.Init( 255, 100, 36); break; case 3: vec.Init( 255, 180, 36); break; default: vec.Init( 0, 240, 255 ); } } THINK_FUNC_DECL(EyeParticle) { auto player = reinterpret_cast<CTFBot *>(this); auto data = GetDataForBot(player); if (data == nullptr) return; StopParticleEffects(player); Vector vColor; SetEyeColorForDiff(vColor, player->m_nBotSkill); if (data->eye_particle_color) { vColor.x = data->eye_particle_r; vColor.y = data->eye_particle_g; vColor.z = data->eye_particle_b; } Vector vColorL = vColor / 255; const char *particle = "bot_eye_glow"; if (!data->custom_eye_particle.empty()) particle = data->custom_eye_particle.c_str(); CReliableBroadcastRecipientFilter filter; te_tf_particle_effects_control_point_t cp = { PATTACH_ABSORIGIN, vColor }; const char *eye1 = player->IsMiniBoss() ? "eye_boss_1" : "eye_1"; if (player->LookupAttachment(eye1) == 0) eye1 = "eyeglow_L"; DispatchParticleEffect(particle, PATTACH_POINT_FOLLOW, player, eye1, vec3_origin, true, vColorL, vColorL, true, false, &cp, &filter); const char *eye2 = player->IsMiniBoss() ? "eye_boss_2" : "eye_2"; if (player->LookupAttachment(eye2) == 0) eye2 = "eyeglow_R"; DispatchParticleEffect(particle, PATTACH_POINT_FOLLOW, player, eye2, vec3_origin, true, vColorL, vColorL, true, false, &cp, &filter); } THINK_FUNC_DECL(SetBodygroup) { auto bot = reinterpret_cast<CTFBot *>(this); auto data = GetDataForBot(bot); if (data == nullptr) return; for (const auto& pair : data->bodygroup) { const char *name = pair.first.c_str(); int value = pair.second; int group = bot->FindBodygroupByName(name); if (group != -1) { bot->SetBodygroup(group, value); } DevMsg("Group %s %d %d\n", name, value, group); int count = bot->GetNumBodyGroups(); for (int i = 0; i < count; i++) { name = bot->GetBodygroupName(i); DevMsg("Group sp %s %d\n", name, bot->GetBodygroupCount(i)); } } } void ApplyCurrentEventChangeAttributes(CTFBot *bot) { auto data = GetDataForBot(bot); if (data != nullptr) { for(auto ititem = data->custom_attrs.begin(); ititem != data->custom_attrs.end(); ititem++) { ForEachTFPlayerEconEntity(bot, [&](CEconEntity *entity) { CEconItemView *item_view = entity->GetItem(); if (item_view == nullptr) return; //DevMsg("Compare item to name %s %s\n",item_view->GetStaticData()->GetName(), ititem->first.c_str()); if (FStrEq(item_view->GetStaticData()->GetName(), ititem->first.c_str())) { //DevMsg("Custom attrib count %d\n ",ititem->second.size()); for(auto itattr = ititem->second.begin(); itattr != ititem->second.end(); itattr++) { DevMsg("Added custom attribute %s\n",itattr->first.c_str()); cell_t result = 0; custom_item_set_attribute->PushCell(ENTINDEX(entity)); custom_item_set_attribute->PushString(itattr->first.c_str()); custom_item_set_attribute->PushString(itattr->second.c_str()); custom_item_set_attribute->Execute(&result); // engine->ServerCommand(CFmtStr("ce_mvm_set_attribute %d \"%s\" %s\n", ENTINDEX(entity), itattr->first.c_str(), itattr->second.c_str())); // engine->ServerExecute(); } } }); } ApplyAddCond(bot, data->addconds, delayed_addconds); ApplyPendingTask(bot, data->periodic_tasks, pending_periodic_tasks); if (data->skin != -1){ bot->SetForcedSkin(data->skin); } else bot->ResetForcedSkin(); static ConVarRef sig_mvm_bots_are_humans("sig_mvm_bots_are_humans"); static ConVarRef sig_mvm_bots_bleed("sig_mvm_bots_bleed"); if (!data->use_custom_model.empty()) { bot->GetPlayerClass()->SetCustomModel(data->use_custom_model.c_str(), true); bot->UpdateModel(); bot->SetBloodColor(DONT_BLEED); // TODO: RomeVision...? } else if (data->use_buster_model) { // here we mimic what CMissionPopulator::UpdateMissionDestroySentries does bot->GetPlayerClass()->SetCustomModel("models/bots/demo/bot_sentry_buster.mdl", true); bot->UpdateModel(); bot->SetBloodColor(DONT_BLEED); // TODO: filter-out addition of Romevision cosmetics to UseBusterModel bots // TODO: manually add Romevision cosmetic for SentryBuster to UseBusterModel bots } else if (data->use_human_model != 0 || sig_mvm_bots_are_humans.GetBool()) { bool can_be_sapped = data->use_human_model == 2 || sig_mvm_bots_are_humans.GetInt() == 2; // calling SetCustomModel with a nullptr string *seems* to reset the model // dunno what the bool parameter should be; I think it doesn't matter for the nullptr case bot->GetPlayerClass()->SetCustomModel(nullptr, true); bot->UpdateModel(); bot->SetBloodColor(BLOOD_COLOR_RED); //Cannot be sapped custom attribute if (!can_be_sapped) { auto sap_def = GetItemSchema()->GetAttributeDefinitionByName("cannot be sapped"); if (sap_def != nullptr) bot->GetAttributeList()->SetRuntimeAttributeValue(sap_def, 1.0f); } // TODO: filter-out addition of Romevision cosmetics to UseHumanModel bots } if (HasRobotBlood(bot)) { bot->SetBloodColor(BLOOD_COLOR_RED); } if (data->use_human_animations) { CEconWearable *wearable = static_cast<CEconWearable *>(ItemGeneration()->SpawnItem(PLAYER_ANIM_WEARABLE_ITEM_ID, Vector(0,0,0), QAngle(0,0,0), 6, 9999, "tf_wearable")); DevMsg("Use human anims %d\n", wearable != nullptr); if (wearable != nullptr) { wearable->m_bValidatedAttachedEntity = true; wearable->GiveTo(bot); servertools->SetKeyValue(bot, "rendermode", "1"); bot->SetRenderColorA(0); bot->EquipWearable(wearable); const char *path = bot->GetPlayerClass()->GetCustomModel(); int model_index = CBaseEntity::PrecacheModel(path); wearable->SetModelIndex(model_index); for (int j = 0; j < MAX_VISION_MODES; ++j) { wearable->SetModelIndexOverride(j, model_index); } bot->GetPlayerClass()->SetCustomModel(nullptr, true); } } for (const auto& pair : data->item_colors) { const char *item_name = pair.first.c_str(); const color32& item_color = pair.second; CEconEntity *entity = bot->GetEconEntityByName(item_name); if (entity != nullptr) { DevMsg("CTFBotSpawner %08x: applying color %02X%02X%02X to item \"%s\"\n", (uintptr_t)&data, item_color.r, item_color.g, item_color.b, item_name); entity->SetRenderColorR(item_color.r); entity->SetRenderColorG(item_color.g); entity->SetRenderColorB(item_color.b); } } for (const auto& pair : data->item_models) { const char *item_name = pair.first.c_str(); const char *item_model = pair.second.c_str(); CEconEntity *entity = bot->GetEconEntityByName(item_name); if (entity != nullptr) { int model_index = CBaseEntity::PrecacheModel(item_model); entity->SetModelIndex(model_index); for (int i = 0; i < MAX_VISION_MODES; ++i) { entity->SetModelIndexOverride(i, model_index); } } } CTFWearable *pActionSlotEntity = bot->GetEquippedWearableForLoadoutSlot( LOADOUT_POSITION_ACTION ); if ( pActionSlotEntity != nullptr) { // get the equipped item and see what it is CTFPowerupBottle *pPowerupBottle = rtti_cast< CTFPowerupBottle* >( pActionSlotEntity ); if (pPowerupBottle != nullptr) { int val=0; CALL_ATTRIB_HOOK_INT_ON_OTHER(pPowerupBottle, val, powerup_charges); pPowerupBottle->m_usNumCharges = val; } } for (const auto& pair : data->custom_weapon_models) { int slot = pair.first; const char *path = pair.second.c_str(); CBaseEntity *item; if ((item = bot->GetEquippedWearableForLoadoutSlot(slot)) == nullptr && (item = bot->Weapon_GetSlot(slot)) == nullptr) { DevMsg("CTFBotSpawner %08x: can't find item slot %d for CustomWeaponModel\n", (uintptr_t)&data, slot); continue; } DevMsg("CTFBotSpawner %08x: item slot %d is entity #%d classname \"%s\"\n", (uintptr_t)&data, slot, ENTINDEX(item), item->GetClassname()); DevMsg("CTFBotSpawner %08x: changing item model to \"%s\"\n", (uintptr_t)&data, path); int model_index = CBaseEntity::PrecacheModel(path); for (int i = 0; i < MAX_VISION_MODES; ++i) { item->SetModelIndexOverride(i, model_index); } } if (!data->bodygroup.empty()) { THINK_FUNC_SET(bot, SetBodygroup, gpGlobals->curtime + 0.1f); } if (data->custom_eye_particle != "" || data->eye_particle_color) { THINK_FUNC_SET(bot, EyeParticle, gpGlobals->curtime + 0.1f); } //Replenish clip, if clip bonus is being applied for (int i = 0; i < bot->WeaponCount(); ++i) { CBaseCombatWeapon *weapon = bot->GetWeapon(i); if (weapon == nullptr) continue; int fire_when_full = 0; CALL_ATTRIB_HOOK_INT_ON_OTHER(weapon, fire_when_full, auto_fires_full_clip); if (fire_when_full == 0) weapon->m_iClip1 = weapon->GetMaxClip1(); } CBaseClient *client = static_cast<CBaseClient *> (sv->GetClient(ENTINDEX(bot) - 1)); client->m_nCustomFiles[0].crc = data->spray_file; if (!data->strip_item.empty()) { for (std::string &itemname : data->strip_item) { ForEachTFPlayerEconEntity(bot, [&](CEconEntity *entity){ if (entity->GetItem() != nullptr && FStrEq(entity->GetItem()->GetItemDefinition()->GetName(), itemname.c_str())) { if (entity->MyCombatWeaponPointer() != nullptr) { bot->Weapon_Detach(entity->MyCombatWeaponPointer()); } entity->Remove(); } }); } bot->EquipBestWeaponForThreat(nullptr); } } } RefCount rc_CTFBotSpawner_Spawn; DETOUR_DECL_MEMBER(bool, CTFBotSpawner_Spawn, const Vector& where, CUtlVector<CHandle<CBaseEntity>> *ents) { SCOPED_INCREMENT(rc_CTFBotSpawner_Spawn); auto spawner = reinterpret_cast<CTFBotSpawner *>(this); auto result = DETOUR_MEMBER_CALL(CTFBotSpawner_Spawn)(where, ents); // Delay execution of the first event change attributes if (result) { if (ents != nullptr && !ents->IsEmpty()) { CTFBot *bot = ToTFBot(ents->Tail()); if (bot != nullptr) { ApplyCurrentEventChangeAttributes(bot); } } } return result; } RefCount rc_CTFBot_OnEventChangeAttributes; DETOUR_DECL_MEMBER(void, CTFBot_OnEventChangeAttributes, CTFBot::EventChangeAttributes_t *ecattr) { SCOPED_INCREMENT(rc_CTFBot_OnEventChangeAttributes); CTFBot *bot = reinterpret_cast<CTFBot *>(this); if (GetDataForBot(bot) != nullptr) { ClearDataForBot(bot, CHANGE); } // Load ctfbot's ecattr data auto data = &extdata[ecattr]; ecattr_map[bot] = data; for (int slot : data->strip_item_slot) { CBaseEntity *item; bool held_item = false; if ((item = bot->GetEquippedWearableForLoadoutSlot(slot)) != nullptr || (item = bot->Weapon_GetSlot(slot)) != nullptr) { CBaseCombatWeapon *weapon; if (bot->GetActiveTFWeapon() == item) { held_item = true; } if ((weapon = item->MyCombatWeaponPointer()) != nullptr) { bot->Weapon_Detach(weapon); } item->Remove(); } //if (held_item) bot->EquipBestWeaponForThreat(nullptr); } DETOUR_MEMBER_CALL(CTFBot_OnEventChangeAttributes)(ecattr); if (!rc_CTFBotSpawner_Spawn) ApplyCurrentEventChangeAttributes(bot); else // Reset model to default (prevent sentry buster model lingering on common bots on halloween missions) bot->GetPlayerClass()->SetCustomModel("", true); //DevMsg("OnEventChange %d %d %d %d\n",bot != nullptr, data != nullptr, ecattr, current_spawner); } RefCount rc_CTFBot_AddItem; DETOUR_DECL_MEMBER(int, CTFItemDefinition_GetLoadoutSlot, int classIndex) { CTFItemDefinition *item_def=reinterpret_cast<CTFItemDefinition *>(this); int slot = DETOUR_MEMBER_CALL(CTFItemDefinition_GetLoadoutSlot)(classIndex); if (rc_CTFBot_OnEventChangeAttributes) { const char *name = item_def->GetItemClass(); if (rc_CTFBot_AddItem && (FStrEq(name,"tf_weapon_buff_item") || FStrEq(name,"tf_weapon_parachute") || strncmp(name,"tf_wearable", strlen("tf_wearable")) == 0)) return slot; if (slot == -1){ if(FStrEq(name,"tf_weapon_revolver")) slot = 0; else slot = item_def->GetLoadoutSlot(TF_CLASS_UNDEFINED); } } return slot; } bool is_revolver; const char *classname_gl; const char *item_name; CTFBot *bot_additem; int bot_classnum = TF_CLASS_UNDEFINED; DETOUR_DECL_MEMBER(void *, CItemGeneration_GenerateRandomItem, void *criteria, const Vector &vec, const QAngle &ang) { if (rc_CTFBot_AddItem > 0) { auto it = item_defs.find(item_name); CTFItemDefinition *item_def; void *ret = nullptr; if (it != item_defs.end()){ item_def = it->second; } else { item_def = static_cast<CTFItemDefinition *>(GetItemSchema()->GetItemDefinitionByName(item_name)); //if (item_def == nullptr) // item_def = Mod::Pop::PopMgr_Extensions::GetCustomWeaponItemDef(item_name); item_defs[item_name] = item_def; } if (item_def != nullptr) { //No romevision cosmetics if (item_def->m_iItemDefIndex >= 30143 && item_def->m_iItemDefIndex <= 30161 && cvar_no_romevision.GetBool()) return nullptr; const char *classname = TranslateWeaponEntForClass_improved(item_def->GetItemClass(), bot_classnum); //CEconItemView *item_view= CEconItemView::Create(); //item_view->Init(item_def->m_iItemDefIndex, 6, 9999, 0); ret = ItemGeneration()->SpawnItem(item_def->m_iItemDefIndex,vec, ang, 6, 9999, classname); //CEconItemView::Destroy(item_view); if (ret != nullptr) Mod::Pop::PopMgr_Extensions::AddCustomWeaponAttributes(item_name, reinterpret_cast<CEconEntity *>(ret)->GetItem()); } if (ret == nullptr){ if (cvar_creators_custom_item.GetBool() && bot_additem ) { DevMsg("equip custom ctf item %s\n", item_name); cell_t result = 0; custom_item_equip_itemname->PushCell(ENTINDEX(bot_additem)); custom_item_equip_itemname->PushString(item_name); custom_item_equip_itemname->Execute(&result); //engine->ServerCommand(CFmtStr("ce_mvm_equip_itemname %d \"%s\"\n", ENTINDEX(bot_additem), item_name)); //engine->ServerExecute(); // static ConVarRef ce_mvm_equip_itemname_cvar("sig_mvm_set_credit_team"); // if (sig_mvm_set_credit_team.IsValid() && sig_mvm_set_credit_team.GetBool()) { // return sig_mvm_set_credit_team.GetInt(); // } bot_additem = nullptr; } else ret = DETOUR_MEMBER_CALL(CItemGeneration_GenerateRandomItem)(criteria,vec,ang); } return ret; } return DETOUR_MEMBER_CALL(CItemGeneration_GenerateRandomItem)(criteria,vec,ang); } DETOUR_DECL_MEMBER(bool, CTFBot_EquipRequiredWeapon) { auto result = DETOUR_MEMBER_CALL(CTFBot_EquipRequiredWeapon)(); if (!result) { auto bot = reinterpret_cast<CTFBot *>(this); if (bot->m_iWeaponRestrictionFlags & CTFBot::PDA_ONLY) { bot->Weapon_Switch(bot->Weapon_GetSlot(TF_WPN_TYPE_PDA)); return true; } if (bot->m_iWeaponRestrictionFlags & CTFBot::BUILDING_ONLY) { bot->Weapon_Switch(bot->Weapon_GetSlot(TF_WPN_TYPE_BUILDING)); return true; } } return result; } DETOUR_DECL_MEMBER(CEconItemDefinition *, CEconItemSchema_GetItemDefinitionByName, const char *name) { name = Mod::Pop::PopMgr_Extensions::GetCustomWeaponNameOverride(name); return DETOUR_MEMBER_CALL(CEconItemSchema_GetItemDefinitionByName)(name); } // DETOUR_DECL_MEMBER(void *, CSchemaFieldHandle_CEconItemDefinition, const char* name) { // DevMsg("CShemaItemDefHandle 1 %s %d\n",name, rc_CTFBot_OnEventChangeAttributes); // return DETOUR_MEMBER_CALL(CSchemaFieldHandle_CEconItemDefinition)(name); // } // DETOUR_DECL_MEMBER(void *, CSchemaFieldHandle_CEconItemDefinition2, const char* name) { // DevMsg("CShemaItemDefHandle 2 %s %d\n",name, rc_CTFBot_OnEventChangeAttributes); // return DETOUR_MEMBER_CALL(CSchemaFieldHandle_CEconItemDefinition2)(name); // } DETOUR_DECL_MEMBER(void, CTFBot_AddItem, const char *item) { SCOPED_INCREMENT(rc_CTFBot_AddItem); //clock_t start = clock(); item_name = item; bot_additem = reinterpret_cast<CTFBot *>(this); bot_classnum = bot_additem->GetPlayerClass()->GetClassIndex(); DETOUR_MEMBER_CALL(CTFBot_AddItem)(item); } bool ShouldRocketJump(CTFBot *bot, EventChangeAttributesData *data, bool release_fire) { if (data->rocket_jump_type == 0) return false; if (bot->m_Shared->InCond( TF_COND_BLASTJUMPING )) return false; CTFWeaponBase *weapon = bot->GetActiveTFWeapon(); if (weapon == nullptr) return false; if (data->rocket_jump_type == 2 && weapon->m_iClip1 < weapon->GetMaxClip1()) return false; return true; // int almost_ready_clip = weapon->m_iClip1; // if (release_fire && weapon->m_flNextPrimaryAttack < gpGlobals->curtime + 0.2f) // almost_ready_clip += 1; // return almost_ready_clip > 0 && weapon->m_flNextPrimaryAttack < gpGlobals->curtime && bot->GetItem() == nullptr // && (data->rocket_jump_type == 1 || (data->rocket_jump_type == 2 && weapon->GetMaxClip1() <= almost_ready_clip)) && !bot->m_Shared->InCond( TF_COND_BLASTJUMPING ); } DETOUR_DECL_MEMBER(Vector, CTFBotMainAction_SelectTargetPoint, const INextBot *nextbot, CBaseCombatCharacter *subject) { auto bot = ToTFBot(nextbot->GetEntity()); if (bot != nullptr) { auto data = GetDataForBot(bot); if (data != nullptr) { Vector aim = subject->WorldSpaceCenter(); auto weapon = bot->GetActiveTFWeapon(); if (data->aim_at != AIM_DEFAULT) { if ( data->aim_at == AIM_FEET && bot->GetVisionInterface()->IsAbleToSee( subject->GetAbsOrigin(), IVision::FieldOfViewCheckType::DISREGARD_FOV ) ) aim = subject->GetAbsOrigin(); else if ( data->aim_at == AIM_HEAD && bot->GetVisionInterface()->IsAbleToSee( subject->EyePosition(), IVision::FieldOfViewCheckType::DISREGARD_FOV) ) aim = subject->EyePosition(); } else aim = DETOUR_MEMBER_CALL(CTFBotMainAction_SelectTargetPoint)(nextbot,subject); aim += data->aim_offset; if (data->aim_lead_target_speed > 0) { float speed = data->aim_lead_target_speed; if (speed == 1.0f) { auto find = data->projectile_speed_cache.find(weapon); if (find == data->projectile_speed_cache.end() || gpGlobals->tickcount % 10 == 0) { data->projectile_speed_cache[weapon] = speed = CalculateProjectileSpeed(rtti_cast<CTFWeaponBaseGun *>(weapon)); } else { speed = data->projectile_speed_cache[weapon]; } } auto distance = nextbot->GetRangeTo(subject->GetAbsOrigin()); float time_to_travel = distance / speed; Vector target_pos = aim + time_to_travel * subject->GetAbsVelocity(); if (bot->GetVisionInterface()->IsAbleToSee( target_pos, IVision::FieldOfViewCheckType::DISREGARD_FOV)) aim = target_pos; } return aim; } } return DETOUR_MEMBER_CALL(CTFBotMainAction_SelectTargetPoint)(nextbot,subject); } ConVar cvar_head_tracking_interval("sig_head_tracking_interval_multiplier", "1", FCVAR_NONE, "Head tracking interval multiplier"); DETOUR_DECL_MEMBER(float, CTFBotBody_GetHeadAimTrackingInterval) { auto body = reinterpret_cast<PlayerBody *>(this); float mult = cvar_head_tracking_interval.GetFloat(); auto bot = body->GetEntity(); auto data = GetDataForBot(bot); if (data != nullptr && data->tracking_interval >= 0.f) { return data->tracking_interval; } else return DETOUR_MEMBER_CALL(CTFBotBody_GetHeadAimTrackingInterval)() * mult; } DETOUR_DECL_MEMBER(float, PlayerBody_GetMaxHeadAngularVelocity) { auto body = reinterpret_cast<PlayerBody *>(this); float mult = cvar_head_tracking_interval.GetFloat(); auto bot = ToTFBot(body->GetEntity()); auto data = GetDataForBot(bot); if (data != nullptr && bot != nullptr && ShouldRocketJump(bot, data, false)) { mult *= 2.5f; } if (data != nullptr && data->head_rotate_speed >= 0.f) { return data->head_rotate_speed; } if (data != nullptr && data->tracking_interval >= 0.f && data->tracking_interval < 0.05f) return 10000.0f; else return DETOUR_MEMBER_CALL(PlayerBody_GetMaxHeadAngularVelocity)(); } DETOUR_DECL_MEMBER(void, CTFBotMainAction_FireWeaponAtEnemy, CTFBot *actor) { DETOUR_MEMBER_CALL(CTFBotMainAction_FireWeaponAtEnemy)(actor); auto data = GetDataForBot(actor); if (data != nullptr && data->rocket_jump_type > 0) { auto weapon = actor->GetActiveTFWeapon(); const CKnownEntity *threat = actor->GetVisionInterface()->GetPrimaryKnownThreat(false); if (weapon != nullptr && (data->rocket_jump_type == 1 || weapon->m_iClip1 >= weapon->GetMaxClip1()) && threat != nullptr && threat->GetEntity() != nullptr && actor->IsLineOfFireClear( threat->GetEntity()->EyePosition() )/*&& ShouldRocketJump(actor, weapon, data, true)*//*weapon != nullptr*/) { if (actor->GetFlags() & FL_ONGROUND ) { actor->ReleaseFireButton(); actor->SetAttribute(CTFBot::ATTR_SUPPRESS_FIRE); } if (!actor->m_Shared->InCond( TF_COND_BLASTJUMPING )) { if (weapon->m_flNextPrimaryAttack < gpGlobals->curtime ) { Vector dir = actor->GetAbsOrigin() - threat->GetEntity()->GetAbsOrigin(); if (actor->GetItem() != nullptr) { dir = -actor->GetAbsVelocity(); } dir.z = 0; dir.NormalizeInPlace(); Vector actoreyes; AngleVectors(actor->EyeAngles(), &actoreyes, NULL, NULL); actoreyes.z = 0; actoreyes.NormalizeInPlace(); Vector aim = actor->GetAbsOrigin() + dir * 28; actor->GetBodyInterface()->AimHeadTowards(aim, IBody::LookAtPriorityType::OVERRIDE_ALL, 0.10f, NULL, "Aiming at target we need to destroy to progress"); if (DotProduct(dir,actoreyes) > 0.78) { actor->PressJumpButton(0.1f); if ((actor->GetFlags() & FL_ONGROUND) != 0) { actor->m_nBotAttrs = actor->m_nBotAttrs & ~(CTFBot::ATTR_SUPPRESS_FIRE); actor->PressFireButton(0.1f); } } if ((actor->GetFlags() & FL_ONGROUND) == 0) { actor->PressCrouchButton(0.1f); } //if (!actor->GetFlags() & FL_ONGROUND && DotProduct(dir,actoreyes) > 0.78/*DotProduct(dir,actoreyes) > 0.85*/) { // //} } } else { actor->m_nBotAttrs = actor->m_nBotAttrs & ~(CTFBot::ATTR_SUPPRESS_FIRE); } //if ((data->rocket_jump_type == 1 || (data->rocket_jump_type == 2 && weapon->GetMaxClip1() == weapon->m_iClip1)) && !actor->m_Shared->InCond( TF_COND_BLASTJUMPING )) { //} } } } /* DETOUR_DECL_STATIC(CBaseEntity *, Creat eEntityByName, const char *className, int iForceEdictIndex) { if (rc_CTFBot_AddItem > 0) { return DETOUR_STATIC_CALL(CreateEntityByName)(TranslateWeaponEntForClass_improved(className,bot_classnum), iForceEdictIndex); } return DETOUR_STATIC_CALL(CreateEntityByName)(className, iForceEdictIndex); }*/ DETOUR_DECL_MEMBER(void, CTFBot_EquipBestWeaponForThreat, const CKnownEntity * threat) { auto bot = reinterpret_cast<CTFBot *>(this); bool mannvsmachine = TFGameRules()->IsMannVsMachineMode(); bool use_best_weapon = false; auto data = GetDataForBot(bot); if (data != nullptr && data->use_best_weapon) { use_best_weapon = true; } if (use_best_weapon) TFGameRules()->Set_m_bPlayingMannVsMachine(false); DETOUR_MEMBER_CALL(CTFBot_EquipBestWeaponForThreat)(threat); if (use_best_weapon) TFGameRules()->Set_m_bPlayingMannVsMachine(mannvsmachine); } DETOUR_DECL_MEMBER(const CKnownEntity *, CTFBotMainAction_SelectMoreDangerousThreatInternal, const INextBot *nextbot, const CBaseCombatCharacter *them, const CKnownEntity *threat1, const CKnownEntity *threat2) { auto action = reinterpret_cast<const CTFBotMainAction *>(this); // TODO: make the perf impact of this less obnoxious if possible CTFBot *actor = ToTFBot(nextbot->GetEntity()); if (actor != nullptr) { auto data = GetDataForBot(actor); if (data != nullptr) { /* do the exact same thing as the game code does when the bot has WeaponRestrictions MeleeOnly */ if (data->use_melee_threat_prioritization) { return action->SelectCloserThreat(actor, threat1, threat2); } } } return DETOUR_MEMBER_CALL(CTFBotMainAction_SelectMoreDangerousThreatInternal)(nextbot, them, threat1, threat2); } DETOUR_DECL_MEMBER(bool,CTFBotDeliverFlag_UpgradeOverTime, CTFBot *bot) { auto data = GetDataForBot(bot); if (data != nullptr && data->no_bomb_upgrade) { return false; } return DETOUR_MEMBER_CALL(CTFBotDeliverFlag_UpgradeOverTime)(bot); } DETOUR_DECL_MEMBER(void, CTFPlayer_PainSound, const CTakeDamageInfo& info) { auto player = reinterpret_cast<CTFPlayer *>(this); if (TFGameRules()->IsMannVsMachineMode()) { auto data = GetDataForBot(player); if (data != nullptr) { if (data->pain_sound != "DEF") { player->EmitSound(STRING(AllocPooledString(data->pain_sound.c_str()))); return; } } } DETOUR_MEMBER_CALL(CTFPlayer_PainSound)(info); } DETOUR_DECL_MEMBER(void, CTFPlayer_DeathSound, const CTakeDamageInfo& info) { auto player = reinterpret_cast<CTFPlayer *>(this); if (TFGameRules()->IsMannVsMachineMode()) { auto data = GetDataForBot(player); if (data != nullptr) { if (data->death_sound != "DEF") { player->EmitSound(STRING(AllocPooledString(data->death_sound.c_str()))); return; } } } DETOUR_MEMBER_CALL(CTFPlayer_DeathSound)(info); } void UpdateAlwaysGlow() { if (gpGlobals->tickcount % 3 == 0) { ForEachTFBot([](CTFBot *bot){ if (!bot->IsAlive()) return; auto data = GetDataForBot(bot); if (data != nullptr && data->always_glow) { if (!bot->IsGlowEffectActive()){ bot->AddGlowEffect(); } } if (data != nullptr && data->no_glow) { if (bot->IsGlowEffectActive()){ bot->RemoveGlowEffect(); } } }); } } void UpdateRingOfFire() { static int ring_of_fire_tick_interval = (int)(0.500f / (float)gpGlobals->interval_per_tick); if (gpGlobals->tickcount % ring_of_fire_tick_interval == 0) { ForEachTFBot([](CTFBot *bot){ if (!bot->IsAlive()) return; auto data = GetDataForBot(bot); if (data != nullptr && data->ring_of_fire >= 0.0f) { ForEachEntityInSphere(bot->GetAbsOrigin(), 135.0f, [&](CBaseEntity *ent){ CTFPlayer *victim = ToTFPlayer(ent); if (victim == nullptr) return; if (victim->GetTeamNumber() == bot->GetTeamNumber()) return; if (victim->m_Shared->IsInvulnerable()) return; Vector victim_mins = victim->GetPlayerMins(); Vector victim_maxs = victim->GetPlayerMaxs(); if (bot->GetAbsOrigin().z >= victim->GetAbsOrigin().z + victim_maxs.z) return; Vector closest; victim->CollisionProp()->CalcNearestPoint(bot->GetAbsOrigin(), &closest); if (closest.DistToSqr(bot->GetAbsOrigin()) > Square(135.0f)) return; // trace start should be minigun WSC trace_t tr; UTIL_TraceLine(bot->WorldSpaceCenter(), victim->WorldSpaceCenter(), MASK_SOLID_BRUSHONLY, bot, COLLISION_GROUP_PROJECTILE, &tr); if (tr.fraction == 1.0f || tr.m_pEnt == victim) { Vector bot_origin = bot->GetAbsOrigin(); victim->TakeDamage(CTakeDamageInfo(bot, bot, bot->GetActiveTFWeapon(), vec3_origin, bot_origin, data->ring_of_fire, DMG_IGNITE, 0, &bot_origin)); victim->m_Shared->Burn(bot,nullptr,7.5f); } }); DispatchParticleEffect("heavy_ring_of_fire", bot->GetAbsOrigin(), vec3_angle); } }); } } DETOUR_DECL_MEMBER(int, CTFGameRules_ApplyOnDamageModifyRules, CTakeDamageInfo& info, CBaseEntity *pVictim, bool b1) { auto data = GetDataForBot(pVictim); if (data != nullptr) { auto pTFWeapon = static_cast<CTFWeaponBase *>(ToBaseCombatWeapon(info.GetWeapon())); if (pTFWeapon != nullptr) { int weapon_id = pTFWeapon->GetWeaponID(); auto it = data->weapon_resists.find(pTFWeapon->GetWeaponID()); if (it != data->weapon_resists.end()) { float resist = (*it).second; info.ScaleDamage(resist); DevMsg("Bot #%d taking damage from weapon_id 0x%02x; resist is %4.2f\n", ENTINDEX(pVictim), weapon_id, resist); } } } return DETOUR_MEMBER_CALL(CTFGameRules_ApplyOnDamageModifyRules)(info, pVictim, b1); } DETOUR_DECL_MEMBER(CTFProjectile_Rocket *, CTFWeaponBaseGun_FireRocket, CTFPlayer *player, int i1) { auto proj = DETOUR_MEMBER_CALL(CTFWeaponBaseGun_FireRocket)(player, i1); if (proj != nullptr) { auto data = GetDataForBot(proj->GetOwnerEntity()); if (data != nullptr) { if (!data->rocket_custom_model.empty()) { proj->SetModel(data->rocket_custom_model.c_str()); } if (!data->rocket_custom_particle.empty()) { if (data->rocket_custom_particle.front() == '~') { StopParticleEffects(proj); DispatchParticleEffect(data->rocket_custom_particle.c_str() + 1, PATTACH_ABSORIGIN_FOLLOW, proj, INVALID_PARTICLE_ATTACHMENT, false); } else { DispatchParticleEffect(data->rocket_custom_particle.c_str(), PATTACH_ABSORIGIN_FOLLOW, proj, INVALID_PARTICLE_ATTACHMENT, false); } } } } return proj; } DETOUR_DECL_MEMBER(void, CTFWeaponBase_ApplyOnHitAttributes, CBaseEntity *ent, CTFPlayer *player, const CTakeDamageInfo& info) { DETOUR_MEMBER_CALL(CTFWeaponBase_ApplyOnHitAttributes)(ent, player, info); CTFPlayer *victim = ToTFPlayer(ent); CTFBot *attacker = ToTFBot(player); if (victim != nullptr && attacker != nullptr) { auto data = GetDataForBot(attacker); if (data != nullptr) { for (const auto& addcond : data->dmgappliesconds) { if ((addcond.health_below == 0 || addcond.health_below >= attacker->GetHealth()) && (addcond.health_above == 0 || addcond.health_above < attacker->GetHealth())) victim->m_Shared->AddCond(addcond.cond, addcond.duration, attacker); } } } } DETOUR_DECL_MEMBER(void, CTFProjectile_Rocket_Spawn) { DETOUR_MEMBER_CALL(CTFProjectile_Rocket_Spawn)(); auto rocket = reinterpret_cast<CTFProjectile_Rocket *>(this); auto data = GetDataForBot(rocket->GetOwnerPlayer()); if (data != nullptr) { if (data->homing_rockets.enable) { rocket->SetMoveType(MOVETYPE_CUSTOM); } } } bool HasRobotHumanVoice(CTFPlayer *player) { static ConVarRef sig_mvm_human_bots_robot_voice("sig_mvm_human_bots_robot_voice"); static ConVarRef sig_mvm_bots_are_humans("sig_mvm_bots_are_humans"); if (sig_mvm_human_bots_robot_voice.GetBool()) return false; if (sig_mvm_bots_are_humans.GetBool()) return true; auto data = GetDataForBot(player); if (data != nullptr && data->use_human_model) { return true; } return false; } DETOUR_DECL_MEMBER(const char *, CTFPlayer_GetSceneSoundToken) { auto player = reinterpret_cast<CTFPlayer *>(this); if (player->IsBot() && HasRobotHumanVoice(player)) { return ""; } //const char *token=DETOUR_MEMBER_CALL( CTFPlayer_GetSceneSoundToken)(); //DevMsg("CTFPlayer::GetSceneSoundToken %s\n", token); return DETOUR_MEMBER_CALL( CTFPlayer_GetSceneSoundToken)(); } // std::string GetStrForEntity(CBaseEntity *ent) // { // if (ent == nullptr) { // return "nullptr"; // } // // CTFPlayer *player = ToTFPlayer(ent); // if (player == nullptr) { // return CFmtStr("[#%-4d] entity \"%s\" on teamnum %d", ENTINDEX(ent), ent->GetClassname(), ent->GetTeamNumber()).Get(); // } // // return CFmtStr("[#%-4d] player \"%s\" on teamnum %d", ENTINDEX(player), player->GetPlayerName(), player->GetTeamNumber()).Get(); // } // // void DeflectDebug(CBaseEntity *ent) // { // if (ent == nullptr) return; // // auto rocket = rtti_cast<CTFProjectile_Rocket *>(ent); // if (rocket == nullptr) return; // // DevMsg("\n" // "[#%-4d] tf_projectile_rocket on teamnum %d\n" // " rocket->GetOwnerEntity(): %s\n" // " rocket->GetOwnerPlayer(): %s\n" // " IScorer::GetScorer(): %s\n" // " IScorer::GetAssistant(): %s\n" // " CBaseProjectile::m_hOriginalLauncher: %s\n" // " CTFBaseRocket::m_hLauncher: %s\n" // " CTFBaseRocket::m_iDeflected: %d\n", // ENTINDEX(rocket), rocket->GetTeamNumber(), // GetStrForEntity(rocket->GetOwnerEntity()).c_str(), // GetStrForEntity(rocket->GetOwnerPlayer()).c_str(), // GetStrForEntity(rtti_cast<IScorer *>(rocket)->GetScorer()).c_str(), // GetStrForEntity(rtti_cast<IScorer *>(rocket)->GetAssistant()).c_str(), // GetStrForEntity(rocket->GetOriginalLauncher()).c_str(), // GetStrForEntity(rocket->GetLauncher()).c_str(), // (int)rocket->m_iDeflected); // // // ->GetOwner // // ->GetOwnerPlayer // // // IScorer::GetScorer // // IScorer::GetAssistant // // // CBaseProjectile::m_hOriginalLauncher // // // CTFBaseRocket::m_hLauncher // // CTFBaseRocket::m_iDeflected // // // CBaseGrenade::m_hThrower // // // CTFWeaponBaseGrenadeProj::m_hLauncher // // CTFWeaponBaseGrenadeProj::m_iDeflected // // CTFWeaponBaseGrenadeProj::m_hDeflectOwner // } // ========================================================================= // VALUE BEFORE DEFLECT --> AFTER DEFLECT // ========================================================================= // IScorer::GetScorer(): soldier --> soldier // IScorer::GetAssistant(): <nullptr> --> <nullptr> // CBaseEntity::GetOwnerEntity(): soldier --> pyro // CBaseProjectile::GetOriginalLauncher(): rocketlauncher --> rocketlauncher // CTFBaseRocket::GetOwnerPlayer(): soldier --> pyro // CTFBaseRocket::m_hLauncher: rocketlauncher --> flamethrower // CTFBaseRocket::m_iDeflected: 0 --> 1 DETOUR_DECL_MEMBER(void, CBaseEntity_PerformCustomPhysics, Vector *pNewPosition, Vector *pNewVelocity, QAngle *pNewAngles, QAngle *pNewAngVelocity) { CTFProjectile_Rocket *rocket = nullptr; const HomingRockets *hr = nullptr; auto ent = reinterpret_cast<CBaseEntity *>(this); const char *classname = ent->GetClassname(); if ((strcmp(classname, "tf_projectile_rocket") == 0 || strcmp(classname, "tf_projectile_sentryrocket") == 0)) { rocket = static_cast<CTFProjectile_Rocket *>(ent); auto data = GetDataForBot(rtti_scast<IScorer *>(rocket)->GetScorer()); if (data != nullptr) { hr = &data->homing_rockets; } } if (hr == nullptr || !hr->enable) { DETOUR_MEMBER_CALL(CBaseEntity_PerformCustomPhysics)(pNewPosition, pNewVelocity, pNewAngles, pNewAngVelocity); return; } constexpr float physics_interval = 0.25f; float time = (float)(ent->m_flSimulationTime) - (float)(ent->m_flAnimTime); if (time < hr->aim_time && gpGlobals->tickcount % (int)(physics_interval / gpGlobals->interval_per_tick) == 0) { Vector target_vec = vec3_origin; if (hr->follow_crosshair) { CBaseEntity *owner = rocket->GetOwnerEntity(); if (owner != nullptr) { Vector forward; AngleVectors(owner->EyeAngles(), &forward); trace_t result; UTIL_TraceLine(owner->EyePosition(), owner->EyePosition() + 4000.0f * forward, MASK_SHOT, owner, COLLISION_GROUP_NONE, &result); target_vec = result.endpos; } } else { CTFPlayer *target_player = nullptr; float target_distsqr = FLT_MAX; ForEachTFPlayer([&](CTFPlayer *player){ if (!player->IsAlive()) return; if (player->GetTeamNumber() == TEAM_SPECTATOR) return; if (player->GetTeamNumber() == rocket->GetTeamNumber()) return; if (hr->ignore_disguised_spies) { if (player->m_Shared->InCond(TF_COND_DISGUISED) && player->m_Shared->GetDisguiseTeam() == rocket->GetTeamNumber()) { return; } } if (hr->ignore_stealthed_spies) { if (player->m_Shared->IsStealthed() && player->m_Shared->GetPercentInvisible() >= 0.75f && !player->m_Shared->InCond(TF_COND_STEALTHED_BLINK) && !player->m_Shared->InCond(TF_COND_BURNING) && !player->m_Shared->InCond(TF_COND_URINE) && !player->m_Shared->InCond(TF_COND_BLEEDING)) { return; } } Vector delta = player->WorldSpaceCenter() - rocket->WorldSpaceCenter(); if (DotProduct(delta.Normalized(), pNewVelocity->Normalized()) < hr->min_dot_product) return; float distsqr = rocket->WorldSpaceCenter().DistToSqr(player->WorldSpaceCenter()); if (distsqr < target_distsqr) { trace_t tr; UTIL_TraceLine(player->WorldSpaceCenter(), rocket->WorldSpaceCenter(), MASK_SOLID_BRUSHONLY, player, COLLISION_GROUP_NONE, &tr); if (!tr.DidHit() || tr.m_pEnt == rocket) { target_player = player; target_distsqr = distsqr; } } }); if (target_player != nullptr) { target_vec = target_player->WorldSpaceCenter(); } } if (target_vec != vec3_origin) { QAngle angToTarget; VectorAngles(target_vec - rocket->WorldSpaceCenter(), angToTarget); pNewAngVelocity->x = Clamp(Approach(AngleDiff(angToTarget.x, pNewAngles->x) * 4.0f, pNewAngVelocity->x, hr->turn_power), -360.0f, 360.0f); pNewAngVelocity->y = Clamp(Approach(AngleDiff(angToTarget.y, pNewAngles->y) * 4.0f, pNewAngVelocity->y, hr->turn_power), -360.0f, 360.0f); pNewAngVelocity->z = Clamp(Approach(AngleDiff(angToTarget.z, pNewAngles->z) * 4.0f, pNewAngVelocity->z, hr->turn_power), -360.0f, 360.0f); } } if (time < hr->aim_time) *pNewAngles += (*pNewAngVelocity * gpGlobals->frametime); Vector vecOrientation; AngleVectors(*pNewAngles, &vecOrientation); *pNewVelocity = vecOrientation * (1100.0f * hr->speed + hr->acceleration * Clamp(time - hr->acceleration_start, 0.0f, hr->acceleration_time)) + Vector(0,0,-hr->gravity * gpGlobals->interval_per_tick); *pNewPosition += (*pNewVelocity * gpGlobals->frametime); // if (gpGlobals->tickcount % 2 == 0) { // NDebugOverlay::EntityText(ENTINDEX(rocket), -2, CFmtStr(" AngVel: % 6.1f % 6.1f % 6.1f", VectorExpand(*pNewAngVelocity)), 0.030f); // NDebugOverlay::EntityText(ENTINDEX(rocket), -1, CFmtStr(" Angles: % 6.1f % 6.1f % 6.1f", VectorExpand(*pNewAngles)), 0.030f); // NDebugOverlay::EntityText(ENTINDEX(rocket), 1, CFmtStr("Velocity: % 6.1f % 6.1f % 6.1f", VectorExpand(*pNewVelocity)), 0.030f); // NDebugOverlay::EntityText(ENTINDEX(rocket), 2, CFmtStr("Position: % 6.1f % 6.1f % 6.1f", VectorExpand(*pNewPosition)), 0.030f); // } // DevMsg("[%d] PerformCustomPhysics: #%d %s\n", gpGlobals->tickcount, ENTINDEX(ent), ent->GetClassname()); } DETOUR_DECL_MEMBER(CBaseAnimating *, CTFWeaponBaseGun_FireProjectile, CTFPlayer *player) { if (TFGameRules()->IsMannVsMachineMode()) { auto data = GetDataForBot(player); if (data != nullptr) { bool stopproj = false; auto weapon = reinterpret_cast<CTFWeaponBaseGun*>(this); for(auto it = data->shoot_templ.begin(); it != data->shoot_templ.end(); it++) { ShootTemplateData &temp_data = *it; if (temp_data.weapon != "" && !FStrEq(weapon->GetItem()->GetStaticData()->GetName(), temp_data.weapon.c_str())) continue; if (temp_data.parent_to_projectile) { CBaseAnimating *proj = DETOUR_MEMBER_CALL(CTFWeaponBaseGun_FireProjectile)(player); if (proj != nullptr) { Vector vec = temp_data.offset; QAngle ang = temp_data.angles; auto inst = temp_data.templ->SpawnTemplate(proj, vec, ang, true, nullptr); } return proj; } stopproj = temp_data.Shoot(player, weapon) | stopproj; } if (stopproj) { if (weapon->ShouldPlayFireAnim()) { player->DoAnimationEvent(PLAYERANIMEVENT_ATTACK_PRIMARY); } weapon->RemoveProjectileAmmo(player); weapon->m_flLastFireTime = gpGlobals->curtime; weapon->DoFireEffects(); weapon->UpdatePunchAngles(player); if (player->m_Shared->IsStealthed() && weapon->ShouldRemoveInvisibilityOnPrimaryAttack()) { player->RemoveInvisibility(); } return nullptr; } } } return DETOUR_MEMBER_CALL(CTFWeaponBaseGun_FireProjectile)(player); } DETOUR_DECL_MEMBER(void, CBaseCombatWeapon_WeaponSound, int index, float soundtime) { if ((index == 1 || index == 5) && TFGameRules()->IsMannVsMachineMode()) { auto weapon = reinterpret_cast<CTFWeaponBase *>(this); CTFBot *owner = ToTFBot(weapon->GetOwner()); if (owner != nullptr) { auto data = GetDataForBot(owner); if (data != nullptr && !data->fire_sound.empty()) { owner->EmitSound(data->fire_sound.c_str(), soundtime); return; } } } DETOUR_MEMBER_CALL(CBaseCombatWeapon_WeaponSound)(index, soundtime); } struct NextBotData { int vtable; INextBotComponent *m_ComponentList; // +0x04 PathFollower *m_CurrentPath; // +0x08 int m_iManagerIndex; // +0x0c bool m_bScheduledForNextTick; // +0x10 int m_iLastUpdateTick; // +0x14 }; DETOUR_DECL_MEMBER(ActionResult<CTFBot>, CTFBotMainAction_Update, CTFBot *actor, float dt) { auto data = GetDataForBot(actor); if (data != nullptr && data->fast_update) { reinterpret_cast<NextBotData *>(actor->MyNextBotPointer())->m_bScheduledForNextTick = true; } return DETOUR_MEMBER_CALL(CTFBotMainAction_Update)(actor, dt); } DETOUR_DECL_MEMBER(void, CTFBot_AvoidPlayers, void *cmd) { auto bot = reinterpret_cast<CTFBot *>(this); auto data = GetDataForBot(bot); if (data != nullptr && data->no_pushaway) { return; } DETOUR_MEMBER_CALL(CTFBot_AvoidPlayers)(cmd); } DETOUR_DECL_MEMBER(float, CTFPlayer_GetHandScaleSpeed) { auto data = GetDataForBot(reinterpret_cast<CTFPlayer *>(this)); if (data != nullptr) { return DETOUR_MEMBER_CALL(CTFPlayer_GetHandScaleSpeed)() * data->scale_speed; } return DETOUR_MEMBER_CALL(CTFPlayer_GetHandScaleSpeed)(); } DETOUR_DECL_MEMBER(float, CTFPlayer_GetHeadScaleSpeed) { auto data = GetDataForBot(reinterpret_cast<CTFPlayer *>(this)); if (data != nullptr) { return DETOUR_MEMBER_CALL(CTFPlayer_GetHeadScaleSpeed)() * data->scale_speed; } return DETOUR_MEMBER_CALL(CTFPlayer_GetHeadScaleSpeed)(); } DETOUR_DECL_MEMBER(float, CTFPlayer_GetTorsoScaleSpeed) { auto data = GetDataForBot(reinterpret_cast<CTFPlayer *>(this)); if (data != nullptr) { return DETOUR_MEMBER_CALL(CTFPlayer_GetTorsoScaleSpeed)() * data->scale_speed; } return DETOUR_MEMBER_CALL(CTFPlayer_GetTorsoScaleSpeed)(); } RefCount rc_CTFBotLocomotion_Update; DETOUR_DECL_MEMBER(void, CTFBotLocomotion_Update) { auto data = GetDataForBot(reinterpret_cast<ILocomotion *>(this)->GetBot()->GetEntity()); SCOPED_INCREMENT_IF(rc_CTFBotLocomotion_Update, data != nullptr && data->no_crouch_button_release); DETOUR_MEMBER_CALL(CTFBotLocomotion_Update)(); } DETOUR_DECL_MEMBER(void, NextBotPlayer_CTFPlayer_PressCrouchButton, float time) { if (rc_CTFBotLocomotion_Update) return; DETOUR_MEMBER_CALL(NextBotPlayer_CTFPlayer_PressCrouchButton)(time); } DETOUR_DECL_MEMBER(void, NextBotPlayer_CTFPlayer_ReleaseCrouchButton) { if (rc_CTFBotLocomotion_Update) return; DETOUR_MEMBER_CALL(NextBotPlayer_CTFPlayer_ReleaseCrouchButton)(); } RefCount rc_CTFGameRules_PlayerKilled; CBasePlayer *killed = nullptr; DETOUR_DECL_MEMBER(void, CTFGameRules_PlayerKilled, CBasePlayer *pVictim, const CTakeDamageInfo& info) { // DevMsg("CTFGameRules::PlayerKilled\n"); killed = pVictim; SCOPED_INCREMENT(rc_CTFGameRules_PlayerKilled); DETOUR_MEMBER_CALL(CTFGameRules_PlayerKilled)(pVictim, info); if (TFGameRules()->IsMannVsMachineMode()) { auto *data = GetDataForBot(killed); if (data != nullptr && (data->spell_drop)) { float rnd = RandomFloat(0.0f, 1.0f); float rate_rare = data->spell_drop_rate_rare; float rate_common = rate_rare + data->spell_drop_rate_common; if (rnd < rate_rare) { TFGameRules()->DropSpellPickup(pVictim->GetAbsOrigin(), 0); } else if (rnd < rate_common) { TFGameRules()->DropSpellPickup(pVictim->GetAbsOrigin(), 1); } } if (data != nullptr && data->custom_eye_particle != "") { StopParticleEffects(killed); } } } DETOUR_DECL_MEMBER(bool, CTFGameRules_ShouldDropSpellPickup) { // DevMsg("CTFGameRules::ShouldDropSpellPickup\n"); if (TFGameRules()->IsMannVsMachineMode() && rc_CTFGameRules_PlayerKilled > 0) { auto *data = GetDataForBot(killed); if (data != nullptr && (data->spell_drop)) { return false; } } return DETOUR_MEMBER_CALL(CTFGameRules_ShouldDropSpellPickup)(); } DETOUR_DECL_MEMBER(void, CBasePlayer_PlayStepSound, Vector& vecOrigin, surfacedata_t *psurface, float fvol, bool force) { auto player = reinterpret_cast<CTFPlayer *>(this); if (TFGameRules()->IsMannVsMachineMode()) { auto *data = GetDataForBot(player); if (data != nullptr && data->has_override_step_sound) { player->EmitSound(data->override_step_sound.c_str()); } } DETOUR_MEMBER_CALL(CBasePlayer_PlayStepSound)(vecOrigin, psurface, fvol, force); } RefCount rc_CTFPlayer_OnTakeDamage_Alive; bool was_bleed = false; DETOUR_DECL_MEMBER(int, CTFPlayer_OnTakeDamage_Alive, const CTakeDamageInfo &info) { CTFPlayer *player = reinterpret_cast<CTFPlayer *>(this); SCOPED_INCREMENT_IF(rc_CTFPlayer_OnTakeDamage_Alive, HasRobotBlood(player)); auto result = DETOUR_MEMBER_CALL(CTFPlayer_OnTakeDamage_Alive)(info); if (was_bleed) { Vector vDamagePos = info.GetDamagePosition(); if (vDamagePos == vec3_origin) { vDamagePos = player->WorldSpaceCenter(); } Vector vecDir = vec3_origin; if (info.GetInflictor()) { vecDir = info.GetInflictor()->WorldSpaceCenter() - Vector(0.0f, 0.0f, 10.0f) - player->WorldSpaceCenter(); VectorNormalize(vecDir); } CPVSFilter filter(vDamagePos); TE_TFBlood( filter, 0.0, vDamagePos, -vecDir, player->entindex() ); } was_bleed = false; return result; } RefCount rc_CTFPlayer_Event_Killed; DETOUR_DECL_MEMBER(void, CTFPlayer_Event_Killed, const CTakeDamageInfo& info) { auto player = reinterpret_cast<CTFPlayer *>(this); SCOPED_INCREMENT_IF(rc_CTFPlayer_Event_Killed, HasRobotBlood(player)); DETOUR_MEMBER_CALL(CTFPlayer_Event_Killed)(info); } DETOUR_DECL_STATIC(void, DispatchParticleEffect, char const *name, Vector vec, QAngle ang, CBaseEntity *entity) { if (rc_CTFPlayer_OnTakeDamage_Alive && (strcmp(name, "bot_impact_light") == 0 || strcmp(name, "bot_impact_heavy") == 0)) { was_bleed = true; return; } DETOUR_STATIC_CALL(DispatchParticleEffect)(name, vec, ang, entity); } DETOUR_DECL_STATIC(void, TE_TFParticleEffect, IRecipientFilter& recipement, float value, char const* name, Vector vector, QAngle angles, CBaseEntity* entity, ParticleAttachment_t attach) { if (rc_CTFPlayer_Event_Killed && strcmp(name, "bot_death") == 0) { return; } DETOUR_STATIC_CALL(TE_TFParticleEffect)(recipement, value, name, vector, angles, entity, attach); } class CMod : public IMod, public IModCallbackListener, public IFrameUpdatePostEntityThinkListener { public: CMod() : IMod("Pop:ECAttr_Extensions") { MOD_ADD_DETOUR_MEMBER(CTFBot_dtor0, "CTFBot::~CTFBot [D0]"); MOD_ADD_DETOUR_MEMBER(CTFBot_dtor2, "CTFBot::~CTFBot [D2]"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_StateEnter, "CTFPlayer::StateEnter"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_StateLeave, "CTFPlayer::StateLeave"); MOD_ADD_DETOUR_MEMBER(CTFBotSpawner_Parse, "CTFBotSpawner::Parse"); MOD_ADD_DETOUR_MEMBER(CTFBotSpawner_Spawn, "CTFBotSpawner::Spawn"); MOD_ADD_DETOUR_MEMBER(CTFBot_OnEventChangeAttributes, "CTFBot::OnEventChangeAttributes"); MOD_ADD_DETOUR_MEMBER(CTFBotSpawner_ParseEventChangeAttributes, "CTFBotSpawner::ParseEventChangeAttributes"); MOD_ADD_DETOUR_MEMBER(CPopulationManager_Parse, "CPopulationManager::Parse"); MOD_ADD_DETOUR_MEMBER(CTFBot_AddItem, "CTFBot::AddItem"); MOD_ADD_DETOUR_MEMBER(CTFItemDefinition_GetLoadoutSlot, "CTFItemDefinition::GetLoadoutSlot"); //MOD_ADD_DETOUR_STATIC(CreateEntityByName, "CreateEntityByName"); MOD_ADD_DETOUR_MEMBER(CItemGeneration_GenerateRandomItem, "CItemGeneration::GenerateRandomItem"); MOD_ADD_DETOUR_STATIC(ParseDynamicAttributes, "ParseDynamicAttributes"); MOD_ADD_DETOUR_MEMBER(CEconItemSchema_GetItemDefinitionByName, "CEconItemSchema::GetItemDefinitionByName"); MOD_ADD_DETOUR_MEMBER(CTFBot_EquipRequiredWeapon, "CTFBot::EquipRequiredWeapon"); MOD_ADD_DETOUR_MEMBER(CTFBotMainAction_FireWeaponAtEnemy, "CTFBotMainAction::FireWeaponAtEnemy"); MOD_ADD_DETOUR_MEMBER(CTFBotMainAction_SelectTargetPoint, "CTFBotMainAction::SelectTargetPoint"); MOD_ADD_DETOUR_MEMBER(CTFBotBody_GetHeadAimTrackingInterval, "CTFBotBody::GetHeadAimTrackingInterval"); MOD_ADD_DETOUR_MEMBER(PlayerBody_GetMaxHeadAngularVelocity, "PlayerBody::GetMaxHeadAngularVelocity"); MOD_ADD_DETOUR_MEMBER(CTFBot_EquipBestWeaponForThreat, "CTFBot::EquipBestWeaponForThreat"); MOD_ADD_DETOUR_MEMBER(CTFBotDeliverFlag_UpgradeOverTime, "CTFBotDeliverFlag::UpgradeOverTime"); MOD_ADD_DETOUR_MEMBER(CTFBotMainAction_SelectMoreDangerousThreatInternal, "CTFBotMainAction::SelectMoreDangerousThreatInternal"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_DeathSound, "CTFPlayer::DeathSound"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_PainSound, "CTFPlayer::PainSound"); MOD_ADD_DETOUR_MEMBER(CBaseCombatWeapon_WeaponSound, "CBaseCombatWeapon::WeaponSound"); MOD_ADD_DETOUR_MEMBER(CTFWeaponBaseGun_FireProjectile, "CTFWeaponBaseGun::FireProjectile"); MOD_ADD_DETOUR_MEMBER(CTFProjectile_Rocket_Spawn, "CTFProjectile_Rocket::Spawn"); MOD_ADD_DETOUR_MEMBER(CBaseEntity_PerformCustomPhysics, "CBaseEntity::PerformCustomPhysics"); MOD_ADD_DETOUR_MEMBER(CTFGameRules_ApplyOnDamageModifyRules, "CTFGameRules::ApplyOnDamageModifyRules"); MOD_ADD_DETOUR_MEMBER(CTFWeaponBaseGun_FireRocket, "CTFWeaponBaseGun::FireRocket"); MOD_ADD_DETOUR_MEMBER(CTFWeaponBase_ApplyOnHitAttributes, "CTFWeaponBase::ApplyOnHitAttributes"); MOD_ADD_DETOUR_MEMBER(CTFBotMainAction_Update, "CTFBotMainAction::Update"); MOD_ADD_DETOUR_MEMBER(CTFBot_AvoidPlayers, "CTFBot::AvoidPlayers"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_GetHandScaleSpeed, "CTFPlayer::GetHandScaleSpeed"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_GetHeadScaleSpeed, "CTFPlayer::GetHeadScaleSpeed"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_GetTorsoScaleSpeed, "CTFPlayer::GetTorsoScaleSpeed"); MOD_ADD_DETOUR_MEMBER(CTFBotLocomotion_Update, "CTFBotLocomotion::Update"); MOD_ADD_DETOUR_MEMBER(NextBotPlayer_CTFPlayer_PressCrouchButton, "NextBotPlayer<CTFPlayer>::PressCrouchButton"); MOD_ADD_DETOUR_MEMBER(NextBotPlayer_CTFPlayer_ReleaseCrouchButton, "NextBotPlayer<CTFPlayer>::ReleaseCrouchButton"); MOD_ADD_DETOUR_MEMBER(CTFGameRules_PlayerKilled, "CTFGameRules::PlayerKilled"); MOD_ADD_DETOUR_MEMBER_PRIORITY(CTFGameRules_ShouldDropSpellPickup, "CTFGameRules::ShouldDropSpellPickup", HIGH); MOD_ADD_DETOUR_MEMBER_PRIORITY(CBasePlayer_PlayStepSound, "CBasePlayer::PlayStepSound", HIGH); MOD_ADD_DETOUR_MEMBER(CTFPlayer_OnTakeDamage_Alive, "CTFPlayer::OnTakeDamage_Alive"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_Event_Killed, "CTFPlayer::Event_Killed"); MOD_ADD_DETOUR_STATIC(DispatchParticleEffect, "DispatchParticleEffect [overload 3]"); MOD_ADD_DETOUR_STATIC(TE_TFParticleEffect, "TE_TFParticleEffect"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_GetSceneSoundToken, "CTFPlayer::GetSceneSoundToken"); } virtual bool OnLoad() override { custom_item_equip_itemname = forwards->CreateForward("SIG_OnGiveCustomItem", ET_Hook, 2, NULL, Param_Cell, Param_String); custom_item_get_def_id = forwards->CreateForward("SIG_GetCustomItemID", ET_Hook, 3, NULL, Param_String, Param_Cell, Param_CellByRef); custom_item_set_attribute = forwards->CreateForward("SIG_SetCustomAttribute", ET_Hook, 3, NULL, Param_Cell, Param_String, Param_String); return true; } virtual void OnUnload() override { forwards->ReleaseForward(custom_item_equip_itemname); forwards->ReleaseForward(custom_item_get_def_id); forwards->ReleaseForward(custom_item_set_attribute); ClearAllData(); } virtual void OnDisable() override { ClearAllData(); } virtual bool ShouldReceiveCallbacks() const override { return this->IsEnabled(); } virtual void FrameUpdatePostEntityThink() override { UpdateDelayedAddConds(delayed_addconds); UpdatePeriodicTasks(pending_periodic_tasks); UpdateRingOfFire(); UpdateAlwaysGlow(); } }; CMod s_Mod; ConVar cvar_enable("sig_pop_ecattr_extensions", "0", FCVAR_NOTIFY, "Mod: enable extended KV in EventChangeAttributes", [](IConVar *pConVar, const char *pOldValue, float flOldValue){ s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool()); }); class CKVCond_ECAttr : public IKVCond { public: virtual bool operator()() override { return s_Mod.IsEnabled(); } }; CKVCond_ECAttr cond; } #endif
34.70357
298
0.664629
[ "vector", "model" ]
dbbb88e0299e33ec075648c49d81d77be15c46a2
11,947
cpp
C++
aws-cpp-sdk-ec2/source/model/IpamResourceCidr.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-ec2/source/model/IpamResourceCidr.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ec2/source/model/IpamResourceCidr.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ec2/model/IpamResourceCidr.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace EC2 { namespace Model { IpamResourceCidr::IpamResourceCidr() : m_ipamIdHasBeenSet(false), m_ipamScopeIdHasBeenSet(false), m_ipamPoolIdHasBeenSet(false), m_resourceRegionHasBeenSet(false), m_resourceOwnerIdHasBeenSet(false), m_resourceIdHasBeenSet(false), m_resourceNameHasBeenSet(false), m_resourceCidrHasBeenSet(false), m_resourceType(IpamResourceType::NOT_SET), m_resourceTypeHasBeenSet(false), m_resourceTagsHasBeenSet(false), m_ipUsage(0.0), m_ipUsageHasBeenSet(false), m_complianceStatus(IpamComplianceStatus::NOT_SET), m_complianceStatusHasBeenSet(false), m_managementState(IpamManagementState::NOT_SET), m_managementStateHasBeenSet(false), m_overlapStatus(IpamOverlapStatus::NOT_SET), m_overlapStatusHasBeenSet(false), m_vpcIdHasBeenSet(false) { } IpamResourceCidr::IpamResourceCidr(const XmlNode& xmlNode) : m_ipamIdHasBeenSet(false), m_ipamScopeIdHasBeenSet(false), m_ipamPoolIdHasBeenSet(false), m_resourceRegionHasBeenSet(false), m_resourceOwnerIdHasBeenSet(false), m_resourceIdHasBeenSet(false), m_resourceNameHasBeenSet(false), m_resourceCidrHasBeenSet(false), m_resourceType(IpamResourceType::NOT_SET), m_resourceTypeHasBeenSet(false), m_resourceTagsHasBeenSet(false), m_ipUsage(0.0), m_ipUsageHasBeenSet(false), m_complianceStatus(IpamComplianceStatus::NOT_SET), m_complianceStatusHasBeenSet(false), m_managementState(IpamManagementState::NOT_SET), m_managementStateHasBeenSet(false), m_overlapStatus(IpamOverlapStatus::NOT_SET), m_overlapStatusHasBeenSet(false), m_vpcIdHasBeenSet(false) { *this = xmlNode; } IpamResourceCidr& IpamResourceCidr::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode ipamIdNode = resultNode.FirstChild("ipamId"); if(!ipamIdNode.IsNull()) { m_ipamId = Aws::Utils::Xml::DecodeEscapedXmlText(ipamIdNode.GetText()); m_ipamIdHasBeenSet = true; } XmlNode ipamScopeIdNode = resultNode.FirstChild("ipamScopeId"); if(!ipamScopeIdNode.IsNull()) { m_ipamScopeId = Aws::Utils::Xml::DecodeEscapedXmlText(ipamScopeIdNode.GetText()); m_ipamScopeIdHasBeenSet = true; } XmlNode ipamPoolIdNode = resultNode.FirstChild("ipamPoolId"); if(!ipamPoolIdNode.IsNull()) { m_ipamPoolId = Aws::Utils::Xml::DecodeEscapedXmlText(ipamPoolIdNode.GetText()); m_ipamPoolIdHasBeenSet = true; } XmlNode resourceRegionNode = resultNode.FirstChild("resourceRegion"); if(!resourceRegionNode.IsNull()) { m_resourceRegion = Aws::Utils::Xml::DecodeEscapedXmlText(resourceRegionNode.GetText()); m_resourceRegionHasBeenSet = true; } XmlNode resourceOwnerIdNode = resultNode.FirstChild("resourceOwnerId"); if(!resourceOwnerIdNode.IsNull()) { m_resourceOwnerId = Aws::Utils::Xml::DecodeEscapedXmlText(resourceOwnerIdNode.GetText()); m_resourceOwnerIdHasBeenSet = true; } XmlNode resourceIdNode = resultNode.FirstChild("resourceId"); if(!resourceIdNode.IsNull()) { m_resourceId = Aws::Utils::Xml::DecodeEscapedXmlText(resourceIdNode.GetText()); m_resourceIdHasBeenSet = true; } XmlNode resourceNameNode = resultNode.FirstChild("resourceName"); if(!resourceNameNode.IsNull()) { m_resourceName = Aws::Utils::Xml::DecodeEscapedXmlText(resourceNameNode.GetText()); m_resourceNameHasBeenSet = true; } XmlNode resourceCidrNode = resultNode.FirstChild("resourceCidr"); if(!resourceCidrNode.IsNull()) { m_resourceCidr = Aws::Utils::Xml::DecodeEscapedXmlText(resourceCidrNode.GetText()); m_resourceCidrHasBeenSet = true; } XmlNode resourceTypeNode = resultNode.FirstChild("resourceType"); if(!resourceTypeNode.IsNull()) { m_resourceType = IpamResourceTypeMapper::GetIpamResourceTypeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(resourceTypeNode.GetText()).c_str()).c_str()); m_resourceTypeHasBeenSet = true; } XmlNode resourceTagsNode = resultNode.FirstChild("resourceTagSet"); if(!resourceTagsNode.IsNull()) { XmlNode resourceTagsMember = resourceTagsNode.FirstChild("item"); while(!resourceTagsMember.IsNull()) { m_resourceTags.push_back(resourceTagsMember); resourceTagsMember = resourceTagsMember.NextNode("item"); } m_resourceTagsHasBeenSet = true; } XmlNode ipUsageNode = resultNode.FirstChild("ipUsage"); if(!ipUsageNode.IsNull()) { m_ipUsage = StringUtils::ConvertToDouble(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(ipUsageNode.GetText()).c_str()).c_str()); m_ipUsageHasBeenSet = true; } XmlNode complianceStatusNode = resultNode.FirstChild("complianceStatus"); if(!complianceStatusNode.IsNull()) { m_complianceStatus = IpamComplianceStatusMapper::GetIpamComplianceStatusForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(complianceStatusNode.GetText()).c_str()).c_str()); m_complianceStatusHasBeenSet = true; } XmlNode managementStateNode = resultNode.FirstChild("managementState"); if(!managementStateNode.IsNull()) { m_managementState = IpamManagementStateMapper::GetIpamManagementStateForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(managementStateNode.GetText()).c_str()).c_str()); m_managementStateHasBeenSet = true; } XmlNode overlapStatusNode = resultNode.FirstChild("overlapStatus"); if(!overlapStatusNode.IsNull()) { m_overlapStatus = IpamOverlapStatusMapper::GetIpamOverlapStatusForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(overlapStatusNode.GetText()).c_str()).c_str()); m_overlapStatusHasBeenSet = true; } XmlNode vpcIdNode = resultNode.FirstChild("vpcId"); if(!vpcIdNode.IsNull()) { m_vpcId = Aws::Utils::Xml::DecodeEscapedXmlText(vpcIdNode.GetText()); m_vpcIdHasBeenSet = true; } } return *this; } void IpamResourceCidr::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_ipamIdHasBeenSet) { oStream << location << index << locationValue << ".IpamId=" << StringUtils::URLEncode(m_ipamId.c_str()) << "&"; } if(m_ipamScopeIdHasBeenSet) { oStream << location << index << locationValue << ".IpamScopeId=" << StringUtils::URLEncode(m_ipamScopeId.c_str()) << "&"; } if(m_ipamPoolIdHasBeenSet) { oStream << location << index << locationValue << ".IpamPoolId=" << StringUtils::URLEncode(m_ipamPoolId.c_str()) << "&"; } if(m_resourceRegionHasBeenSet) { oStream << location << index << locationValue << ".ResourceRegion=" << StringUtils::URLEncode(m_resourceRegion.c_str()) << "&"; } if(m_resourceOwnerIdHasBeenSet) { oStream << location << index << locationValue << ".ResourceOwnerId=" << StringUtils::URLEncode(m_resourceOwnerId.c_str()) << "&"; } if(m_resourceIdHasBeenSet) { oStream << location << index << locationValue << ".ResourceId=" << StringUtils::URLEncode(m_resourceId.c_str()) << "&"; } if(m_resourceNameHasBeenSet) { oStream << location << index << locationValue << ".ResourceName=" << StringUtils::URLEncode(m_resourceName.c_str()) << "&"; } if(m_resourceCidrHasBeenSet) { oStream << location << index << locationValue << ".ResourceCidr=" << StringUtils::URLEncode(m_resourceCidr.c_str()) << "&"; } if(m_resourceTypeHasBeenSet) { oStream << location << index << locationValue << ".ResourceType=" << IpamResourceTypeMapper::GetNameForIpamResourceType(m_resourceType) << "&"; } if(m_resourceTagsHasBeenSet) { unsigned resourceTagsIdx = 1; for(auto& item : m_resourceTags) { Aws::StringStream resourceTagsSs; resourceTagsSs << location << index << locationValue << ".ResourceTagSet." << resourceTagsIdx++; item.OutputToStream(oStream, resourceTagsSs.str().c_str()); } } if(m_ipUsageHasBeenSet) { oStream << location << index << locationValue << ".IpUsage=" << StringUtils::URLEncode(m_ipUsage) << "&"; } if(m_complianceStatusHasBeenSet) { oStream << location << index << locationValue << ".ComplianceStatus=" << IpamComplianceStatusMapper::GetNameForIpamComplianceStatus(m_complianceStatus) << "&"; } if(m_managementStateHasBeenSet) { oStream << location << index << locationValue << ".ManagementState=" << IpamManagementStateMapper::GetNameForIpamManagementState(m_managementState) << "&"; } if(m_overlapStatusHasBeenSet) { oStream << location << index << locationValue << ".OverlapStatus=" << IpamOverlapStatusMapper::GetNameForIpamOverlapStatus(m_overlapStatus) << "&"; } if(m_vpcIdHasBeenSet) { oStream << location << index << locationValue << ".VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&"; } } void IpamResourceCidr::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_ipamIdHasBeenSet) { oStream << location << ".IpamId=" << StringUtils::URLEncode(m_ipamId.c_str()) << "&"; } if(m_ipamScopeIdHasBeenSet) { oStream << location << ".IpamScopeId=" << StringUtils::URLEncode(m_ipamScopeId.c_str()) << "&"; } if(m_ipamPoolIdHasBeenSet) { oStream << location << ".IpamPoolId=" << StringUtils::URLEncode(m_ipamPoolId.c_str()) << "&"; } if(m_resourceRegionHasBeenSet) { oStream << location << ".ResourceRegion=" << StringUtils::URLEncode(m_resourceRegion.c_str()) << "&"; } if(m_resourceOwnerIdHasBeenSet) { oStream << location << ".ResourceOwnerId=" << StringUtils::URLEncode(m_resourceOwnerId.c_str()) << "&"; } if(m_resourceIdHasBeenSet) { oStream << location << ".ResourceId=" << StringUtils::URLEncode(m_resourceId.c_str()) << "&"; } if(m_resourceNameHasBeenSet) { oStream << location << ".ResourceName=" << StringUtils::URLEncode(m_resourceName.c_str()) << "&"; } if(m_resourceCidrHasBeenSet) { oStream << location << ".ResourceCidr=" << StringUtils::URLEncode(m_resourceCidr.c_str()) << "&"; } if(m_resourceTypeHasBeenSet) { oStream << location << ".ResourceType=" << IpamResourceTypeMapper::GetNameForIpamResourceType(m_resourceType) << "&"; } if(m_resourceTagsHasBeenSet) { unsigned resourceTagsIdx = 1; for(auto& item : m_resourceTags) { Aws::StringStream resourceTagsSs; resourceTagsSs << location << ".ResourceTagSet." << resourceTagsIdx++; item.OutputToStream(oStream, resourceTagsSs.str().c_str()); } } if(m_ipUsageHasBeenSet) { oStream << location << ".IpUsage=" << StringUtils::URLEncode(m_ipUsage) << "&"; } if(m_complianceStatusHasBeenSet) { oStream << location << ".ComplianceStatus=" << IpamComplianceStatusMapper::GetNameForIpamComplianceStatus(m_complianceStatus) << "&"; } if(m_managementStateHasBeenSet) { oStream << location << ".ManagementState=" << IpamManagementStateMapper::GetNameForIpamManagementState(m_managementState) << "&"; } if(m_overlapStatusHasBeenSet) { oStream << location << ".OverlapStatus=" << IpamOverlapStatusMapper::GetNameForIpamOverlapStatus(m_overlapStatus) << "&"; } if(m_vpcIdHasBeenSet) { oStream << location << ".VpcId=" << StringUtils::URLEncode(m_vpcId.c_str()) << "&"; } } } // namespace Model } // namespace EC2 } // namespace Aws
35.451039
192
0.701264
[ "model" ]
dbbba5f7efc2598016252aad5323a9c622fcc454
6,464
cpp
C++
Editor/AudioManager.cpp
ahwayakchih/Medo
acc34c189676544c092fbc6800c27a25d05de6dd
[ "MIT" ]
null
null
null
Editor/AudioManager.cpp
ahwayakchih/Medo
acc34c189676544c092fbc6800c27a25d05de6dd
[ "MIT" ]
null
null
null
Editor/AudioManager.cpp
ahwayakchih/Medo
acc34c189676544c092fbc6800c27a25d05de6dd
[ "MIT" ]
null
null
null
/* PROJECT: Medo * AUTHORS: Zenja Solaja, Melbourne Australia * COPYRIGHT: Zen Yes Pty Ltd, 2019-2021 * DESCRIPTION: Audio manager (accurate seeking + cache frames) */ #include <cassert> #include <vector> #include <MediaKit.h> #include <interface/Bitmap.h> #include <kernel/OS.h> extern "C" { #include <libswresample/swresample.h> } #include "MediaSource.h" #include "Project.h" #include "AudioCache.h" #include "AudioManager.h" #include "MedoWindow.h" #include "Actor/Actor.h" #if 0 #define DEBUG(...) do {printf(__VA_ARGS__);} while (0) #else #define DEBUG(fmt, ...) {} #endif AudioManager *gAudioManager = nullptr; /********************************** AudioThumbnailActor ***********************************/ class AudioThumbnailActor : public yarra::Actor { BMessage *fMessage; public: AudioThumbnailActor() { fMessage = new BMessage(MedoWindow::eMsgActionAsyncThumbnailReady); } ~AudioThumbnailActor() { delete fMessage; } /* FUNCTION: AudioThumbnailActor :: AsyncGenerateThumbnail ARGS: none RETURN: n/a DESCRIPTION: Async generate audio bitmap. */ void AsyncGenerateThumbnail(MediaSource *source, const int64 audio_start, const int64 audio_end, const float width, const float height) { BBitmap *bitmap = gAudioManager->GetBitmapAudioFrame(source, audio_start, audio_end, width, height); if (bitmap) MedoWindow::GetInstance()->PostMessage(fMessage); } /* FUNCTION: AudioThumbnailActor :: ClearPendingThumbnails ARGS: none RETURN: n/a DESCRIPTION: FrameResized() can cause an explosion of these messages, so discard older requests */ void ClearPendingThumbnails() { ClearAllMessages(); } }; /********************************** Audio Manager ***********************************/ /* FUNCTION: AudioManager :: AudioManager ARGS: none RETURN: n/a DESCRIPTION: Constructor */ AudioManager :: AudioManager() { fAudioCache = new AudioCache; for (int i=0; i < NUMBER_AUDIO_PROCESSING_BUFFERS; i++) fProcessingBuffers[i] = new uint8 [192*1024*sizeof(float)*2]; // 192k samples/second, sizeof(float), 2 channels fCacheSemaphore = create_sem(1, "AudioManager::fQueueSemaphore"); if (fCacheSemaphore < B_OK) { printf("AudioManager() - cannot create fQueueSemaphore\n"); exit(1); } fAudioThumbnailActor = new AudioThumbnailActor; fPreviewStartFrame = 0; fPreviewEndFrame = 0; #if 1 fSoundPlayer = new BSoundPlayer("Medo", SoundPlayerCallback, nullptr, this); if (fSoundPlayer->InitCheck() == B_OK) { fSoundPlayer->SetHasData(false); fSoundPlayer->Start(); } else { delete fSoundPlayer; fSoundPlayer = nullptr; } #else fSoundPlayer = nullptr; #endif } /* FUNCTION: AudioManager :: ~AudioManager ARGS: n/a RETURN: n/a DESCRIPTION: Destructor */ AudioManager :: ~AudioManager() { for (auto &i : fResamplerContext) swr_free(&i.context); delete fSoundPlayer; delete fAudioThumbnailActor; if (fCacheSemaphore >= B_OK) delete_sem(fCacheSemaphore); for (int i=0; i < NUMBER_AUDIO_PROCESSING_BUFFERS; i++) delete fProcessingBuffers[i]; delete fAudioCache; } /* FUNCTION: AudioManager :: GetBitmapAudioFrame ARGS: source audio_start, audio_end width,height RETURN: BBitmap DESCRIPTION: Get audio track bitmap (no source frame conversion) */ BBitmap * AudioManager :: GetBitmapAudioFrame(MediaSource *source, const int64 audio_start, const int64 audio_end, const float width, const float height) { DEBUG("AudioManager::GetBitmapAudioFrame() %fx%f\n", width, height); assert(source != nullptr); BMediaTrack *track = source->GetAudioTrack(); assert(track != nullptr); assert(audio_start <= audio_end); assert(audio_end <= source->GetAudioNumberSamples()); assert(audio_start >= 0); if ((audio_start == audio_end) || (width == 0.0f) || (height == 0.0f)) return nullptr; if ((width <= 0.0f) || (height < 0.0f)) return nullptr; BBitmap *bitmap = nullptr; status_t err; while ((err = acquire_sem(fCacheSemaphore)) == B_INTERRUPTED) ; if (err == B_OK) { bitmap = fAudioCache->FindBitmapLocked(source, audio_start, audio_end, width, height); release_sem_etc(fCacheSemaphore, 1, B_DO_NOT_RESCHEDULE); if (!bitmap) bitmap = fAudioCache->CreateBitmapUnlocked(fCacheSemaphore, source, audio_start, audio_end, width, height); } return bitmap; } /* FUNCTION: AudioManager :: GetBitmapAsync ARGS: source source_start, source_end width,height callback RETURN: BBitmap DESCRIPTION: Get audio track bitmap (async) */ BBitmap * AudioManager :: GetBitmapAsync(MediaSource *source, const int64 start_frame, const int64 end_frame, const float width, const float height) { DEBUG("AudioManager::GetBitmapAsync() %fx%f\n", width, height); assert(source != nullptr); assert(source->GetAudioTrack() != nullptr); assert(start_frame <= end_frame); assert(start_frame >= 0); if ((start_frame >= end_frame) || (width == 0.0f) || (height == 0.0f)) return nullptr; // convert to source frame rate const float kConversionFactor = float(kFramesSecond) / source->GetAudioFrameRate(); int64 audio_start = start_frame / kConversionFactor; int64 audio_end = end_frame / kConversionFactor; // BMediaTrack::Duration() may incorrectly report more than available samples (https://dev.haiku-os.org/ticket/16581) const int64 audio_samples = source->GetAudioNumberSamples(); if (audio_end >= audio_samples) audio_end = audio_samples; if (audio_start > audio_samples) return nullptr; // Check if frame in cache, otherwise schedule work status_t err; while ((err = acquire_sem(fCacheSemaphore)) == B_INTERRUPTED) ; if (err != B_OK) return nullptr; bool generate_thumbnail = false; BBitmap *bitmap = fAudioCache->FindBitmapLocked(source, audio_start, audio_end, width, height); if (!bitmap) { // See if we can find temporary bitmap with different size bitmap = fAudioCache->FindSimilarBitmapLocked(source, audio_start, audio_end, width, height); generate_thumbnail = true; } release_sem_etc(fCacheSemaphore, 1, B_DO_NOT_RESCHEDULE); if (generate_thumbnail) { fAudioThumbnailActor->Async(&AudioThumbnailActor::AsyncGenerateThumbnail, fAudioThumbnailActor, source, audio_start, audio_end, width, height); } return bitmap; } /* FUNCTION: AudioManager :: ClearPendingThumbnails ARGS: none RETURN: n/a DESCRIPTION: Clear pending thumbnail generation */ void AudioManager :: ClearPendingThumbnails() { fAudioThumbnailActor->ClearPendingThumbnails(); }
27.159664
153
0.715811
[ "vector" ]
dbbbabd92df39565e41cbcb90bc90aa01e8f47d5
1,351
cpp
C++
src/main_auxiliary.cpp
meteoritenhagel/conways_game_of_life
5a15cc008b9e7b700cd1c900bcc2509a3a22f233
[ "MIT" ]
null
null
null
src/main_auxiliary.cpp
meteoritenhagel/conways_game_of_life
5a15cc008b9e7b700cd1c900bcc2509a3a22f233
[ "MIT" ]
null
null
null
src/main_auxiliary.cpp
meteoritenhagel/conways_game_of_life
5a15cc008b9e7b700cd1c900bcc2509a3a22f233
[ "MIT" ]
null
null
null
#include "main_auxiliary.h" bool events() { bool quit = false; SDL_Event event; while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) // window is closed { quit = true; } } return quit; } void loop(GameOfLife &gameOfLife) { gameOfLife.nextGeneration(); // lets the game develop by one time step SDL_Delay(16); return; } void render(const GameOfLife &gameOfLife, RenderingEngine &renderingEngine, SDL_Texture *texture) { uint32_t *pixelData; int pitch; // length of the surface scanline in bytes SDL_LockTexture(texture, NULL, reinterpret_cast<void**>(&pixelData), &pitch); int offset = pitch/sizeof(*pixelData); // length of the surface scanline in pixels for (int i = 0; i < gameOfLife.getHeight(); ++i) for (int j = 0; j < gameOfLife.getWidth(); ++j) // go through all cells. if(gameOfLife.isCellAlive(i, j)) { pixelData[i + offset*j] = 0xFFFFFFFF; //if alive, draw as white. } else pixelData[i + offset*j] = 0xFF000000; //if dead, draw as black. SDL_UnlockTexture(texture); SDL_RenderCopy(renderingEngine.get_renderer(), texture, NULL, NULL); // copy texture to renderer SDL_RenderPresent(renderingEngine.get_renderer()); // render return; }
30.022222
100
0.626203
[ "render" ]
dbc61e7ae41f6a2d9cb7e77775897121759ed239
9,867
cpp
C++
traced_inference_example.cpp
steczol/cpp-pytorch-ssd
c0852ab02c16def1191dc5a991b2da055349518e
[ "MIT" ]
null
null
null
traced_inference_example.cpp
steczol/cpp-pytorch-ssd
c0852ab02c16def1191dc5a991b2da055349518e
[ "MIT" ]
null
null
null
traced_inference_example.cpp
steczol/cpp-pytorch-ssd
c0852ab02c16def1191dc5a991b2da055349518e
[ "MIT" ]
null
null
null
#include <ATen/Functions.h> #include <ATen/core/TensorBody.h> #include <ATen/core/grad_mode.h> #include <chrono> #include <functional> #include <opencv2/core.hpp> #include <opencv2/core/matx.hpp> #include <opencv2/imgproc.hpp> #include <torch/script.h> #include <torchvision/vision.h> #include <opencv2/core/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <chrono> #include <iostream> #include <memory> #include <vector> // using namespace torch::indexing; using namespace std::chrono; using clk = std::chrono::high_resolution_clock; const float EPS = 1e-5; struct Box { Box(float left, float top, float right, float bottom, float score) : left(left), top(top), right(right), bottom(bottom), score(score) {} float left, top, right, bottom, score; float area() const { auto w = right - left; auto h = bottom - top; return std::max(0.F, w * h); } }; std::ostream &operator<<(std::ostream &out, const Box &b) { out << "(" << b.left << ", " << b.top << ") -- (" << b.right << ", " << b.bottom << ") : " << b.score; return out; } using Boxes = std::vector<Box>; Box overlap(const Box &lhs, const Box &rhs) { return {std::max(lhs.left, rhs.left), std::max(lhs.top, rhs.top), std::min(lhs.right, rhs.right), std::min(lhs.bottom, rhs.bottom), 0.F}; } float iou_of(const Box &box0, const Box &box1, float eps = EPS) { auto intersection_area = overlap(box0, box1).area(); return intersection_area / (box0.area() + box1.area() - intersection_area + eps); } std::vector<float> iou_of(const Boxes &boxes0, const Box &box, float eps = EPS) { std::vector<float> ret; std::transform( boxes0.cbegin(), boxes0.cend(), std::back_inserter(ret), [&box](const Box &box0) -> float { return iou_of(box0, box); }); return ret; } template <class BoxesIt> std::vector<float> iou_of(BoxesIt first, BoxesIt last, const Box &box, float eps = EPS) { std::vector<float> ret; std::transform( first, last, std::back_inserter(ret), [&box](const Box &box0) -> float { return iou_of(box0, box); }); return ret; } std::vector<float> iou_of(const Boxes &boxes0, const Boxes &boxes1, float eps = EPS) { std::vector<float> ret; std::transform( boxes0.cbegin(), boxes0.cend(), boxes1.cbegin(), std::back_inserter(ret), [](const Box &box0, const Box &box1) { return iou_of(box0, box1); }); return ret; } template <class BoxesIt, class IousIt> BoxesIt removeGivenIous(BoxesIt boxes_first, BoxesIt boxes_last, IousIt ious_first, IousIt ious_last, float iou_threshold) { assert(std::distance(boxes_first, boxes_last) == std::distance(ious_first, ious_last)); auto ious_it = ious_first; auto boxes_it = boxes_first; while ((ious_it != ious_last) && (boxes_it != boxes_last)) { if (*ious_it <= iou_threshold) { *boxes_first++ = std::move(*boxes_it); } ++ious_it; ++boxes_it; }; return boxes_first; } Boxes hard_nms(Boxes &boxes, int top_k, int candidate_size) { Boxes ret; std::sort(boxes.begin(), boxes.end(), [](const Box &box0, const Box &box1) { return box0.score > box1.score; }); const float iou_threshold = 0.45F; while (!boxes.empty()) { auto box = boxes.at(0); ret.push_back(box); // pop_front boxes.erase(boxes.begin()); if (top_k > 0 && top_k == ret.size()) { break; } auto ious = iou_of(boxes.begin(), boxes.end(), box); boxes.erase(removeGivenIous(boxes.begin(), boxes.end(), ious.begin(), ious.end(), iou_threshold), boxes.end()); } return ret; } template <typename T> std::string rounded(T number) { std::stringstream ss; ss << std::fixed << std::setprecision(2) << number; return ss.str(); } cv::Mat draw_boxes(const cv::Mat &orig_image, const Boxes &boxes, const std::vector<std::string> &labels_str) { assert(boxes.size() == labels_str.size()); cv::Mat ret = orig_image; for (int i = 0; i < boxes.size(); i++) { const auto &box = boxes.at(i); cv::rectangle(ret, cv::Point2f{box.left, box.top}, cv::Point2f{box.right, box.bottom}, {255, 255, 0}, 4); // std::string label = labels_str.at(i) + ": " + std::to_string(box.score); const std::string label = labels_str.at(i) + ": " + rounded(box.score); cv::putText(ret, label, cv::Point2f{box.left + 20, box.top + 40}, cv::FONT_HERSHEY_SIMPLEX, 1, {255, 0, 255}, 2); } return ret; } const auto CLASS_NAMES = std::vector<std::string>{ "BACKGROUND", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"}; int main(int argc, char **argv) { auto model_path = std::string(); auto image_path = std::string(); auto labels_path = std::string(); std::vector<std::string> class_names; if (argc < 3) { std::cerr << "usage: sysiko_infer_example <path-to-exported-module> " "<path_to_image> [path_to_labels]\n"; std::cerr << "example: sysiko_infer_example models/model.pt\n"; return -1; } if (argc >= 3) { model_path = std::string(argv[1]); image_path = std::string(argv[2]); if (argc == 3) { class_names = CLASS_NAMES; } else { // read class names from file put as third argument } } torch::jit::script::Module module; try { module = torch::jit::load(model_path); } catch (const c10::Error &e) { std::cerr << "error loading the model | \n" << e.what() << "\n"; return -1; } std::cout << "info: module loaded\n"; // Read image input auto orig_image = cv::imread(image_path); std::cout << "info: image read\n"; cv::Mat image; cv::cvtColor(orig_image, image, cv::COLOR_BGR2RGB); auto height = image.rows; auto width = image.cols; // Infer const auto size = 300; const auto mean = 127; const auto stddev = 128.0; // Transforms // Resize cv::Mat img_resized; cv::resize(image, img_resized, {size, size}); // Subtract Means // cv::Mat img_subtracted; // img_resized.convertTo(img_subtracted, CV_32FC3, 1, -127); // // Normalize // cv::Mat img_normalized; // img_subtracted.convertTo(img_normalized, CV_32FC3, 1.0 / stddev); cv::Mat img_normalized; img_resized.convertTo(img_normalized, CV_32FC3, 1.0 / stddev, -mean / stddev); // Create input at::Tensor input_tensor = torch::from_blob( img_normalized.data, {1, img_normalized.rows, img_normalized.cols, img_normalized.channels()}); input_tensor = input_tensor.permute({0, 3, 1, 2}); input_tensor = input_tensor.cuda(); std::vector<torch::jit::IValue> inputs; inputs.push_back(input_tensor); // Infer c10::IValue output; { at::NoGradGuard no_grad; auto start = clk::now(); output = module.forward(inputs); auto stop = clk::now(); std::cout << "Inference time: " << duration_cast<microseconds>(stop - start).count() / 1000000.F << " s" << std::endl; } // output is a tuple of tensors: [scores, boxes] auto scores = output.toTuple()->elements().at(0).toTensor(); auto boxes = output.toTuple()->elements().at(1).toTensor(); scores = scores.cpu(); boxes = boxes.cpu(); // since there is just one image on input: scores = scores[0]; // scores has now size [3000, 21] boxes = boxes[0]; // boxes has now size [3000, 4] // Postprocessing: const float prob_threshold = 0.4; const int top_k = 10; const int candidate_size = 200; auto scores_transp = scores.permute({1, 0}); Boxes picked_boxes; std::vector<int> picked_labels; for (int class_index = 1; class_index < scores.size(1); class_index++) { auto probs = scores_transp[class_index]; Boxes subset_boxes; for (int i = 0; i < scores.size(0); i++) { auto prob = probs[i].item<float>(); if (prob > prob_threshold) { std::vector<float> prob_box(static_cast<float *>(boxes[i].data_ptr()), static_cast<float *>(boxes[i].data_ptr()) + boxes[i].numel()); Box v_probable_bbox(prob_box[0], prob_box[1], prob_box[2], prob_box[3], prob); subset_boxes.push_back(v_probable_bbox); } } if (subset_boxes.empty()) { continue; } subset_boxes = hard_nms(subset_boxes, top_k, candidate_size); picked_boxes.insert(picked_boxes.end(), subset_boxes.begin(), subset_boxes.end()); picked_labels.insert(picked_labels.end(), subset_boxes.size(), class_index); } std::for_each(picked_boxes.begin(), picked_boxes.end(), [&width, &height](Box &box) -> void { box.left *= static_cast<float>(width); box.top *= static_cast<float>(height); box.right *= static_cast<float>(width); box.bottom *= static_cast<float>(height); }); std::vector<std::string> picked_labels_str; std::transform(picked_labels.begin(), picked_labels.end(), std::back_inserter(picked_labels_str), [](int idx) -> std::string { return CLASS_NAMES[idx]; }); cv::Mat traced_out_img = draw_boxes(orig_image, picked_boxes, picked_labels_str); std::string out_img_path = "out/detected_traced_cpp.jpg"; cv::imwrite(out_img_path, traced_out_img); std::cout << "info: found " << picked_boxes.size() << " objects. The output image is " << out_img_path << std::endl; std::cout << "info: ok\n"; return 0; }
30.266871
80
0.606973
[ "vector", "model", "transform" ]
dbc65183b81ea3b16e9663221ba39e4965520175
151,599
cpp
C++
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_0Table.cpp
angelicabr97/Emergency-Broadcast-
edafae6b21db0026a9502dbc7ba63b815bd06dbd
[ "MIT" ]
1
2019-04-02T19:43:55.000Z
2019-04-02T19:43:55.000Z
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_0Table.cpp
angelicabr97/Emergency-Broadcast-
edafae6b21db0026a9502dbc7ba63b815bd06dbd
[ "MIT" ]
null
null
null
Temp/il2cppOutput/il2cppOutput/Il2CppCompilerCalculateTypeValues_0Table.cpp
angelicabr97/Emergency-Broadcast-
edafae6b21db0026a9502dbc7ba63b815bd06dbd
[ "MIT" ]
null
null
null
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "il2cpp-class-internals.h" #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // Mono.Globalization.Unicode.CodePointIndexer/TableRange[] struct TableRangeU5BU5D_t4FC778065AD83ABC25432F9CC16725D7044A8D2E; // System.AsyncCallback struct AsyncCallback_t74ABD1277F711E7FBDCB00E169A63DEFD39E86A2; // System.Byte struct Byte_t4C3393E6E7EAD06B53234C05564190D9A2D7B149; // System.Byte[] struct ByteU5BU5D_t8E14BD25C7BEB727CB1849CF449DE26B113309E8; // System.Char[] struct CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744; // System.Collections.IDictionary struct IDictionary_tD35B9437F08BE98D1E0B295CC73C48E168CAB316; // System.DelegateData struct DelegateData_tF588FE8D395F9A38FC7D222940F9B218441D21A9; // System.Double struct Double_t2011D65DAF7D1FCBE71DD4CBDFA69A8F24643159; // System.IAsyncResult struct IAsyncResult_tDA33C24465239FB383C4C2CDAAC43B9AD3CB7F05; // System.IntPtr[] struct IntPtrU5BU5D_tB866BA24C91559CF299618E230043451CC7CF659; // System.Reflection.MemberFilter struct MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE; // System.Reflection.MethodInfo struct MethodInfo_t; // System.Runtime.Remoting.ServerIdentity struct ServerIdentity_t3C5F8BAEFAC94CF69694273ACCB6CB41355E0B5C; // System.String struct String_t; // System.Type struct Type_t; // System.Type[] struct TypeU5BU5D_tEF927658123F6CD4274B971442504A42AB6DE532; // System.UInt16 struct UInt16_t1FF1E02102FB09D5656DF30E5299DD359E497E9B; // System.Void struct Void_tDB81A15FA2AB53E2401A76B745D215397B29F783; #ifndef U3CMODULEU3E_TD1EF7EA122A0D4C77CC334676127E2D8CF50824D_H #define U3CMODULEU3E_TD1EF7EA122A0D4C77CC334676127E2D8CF50824D_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_tD1EF7EA122A0D4C77CC334676127E2D8CF50824D { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_TD1EF7EA122A0D4C77CC334676127E2D8CF50824D_H #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H #ifndef LOCALE_T12F756ABDAE9CA1C3A9518C0EF782FD1A54D2FEE_H #define LOCALE_T12F756ABDAE9CA1C3A9518C0EF782FD1A54D2FEE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Locale struct Locale_t12F756ABDAE9CA1C3A9518C0EF782FD1A54D2FEE : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LOCALE_T12F756ABDAE9CA1C3A9518C0EF782FD1A54D2FEE_H #ifndef CODEPOINTINDEXER_TBEAB082D551EAD545D7B14B25BF02150303A3C2A_H #define CODEPOINTINDEXER_TBEAB082D551EAD545D7B14B25BF02150303A3C2A_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Globalization.Unicode.CodePointIndexer struct CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A : public RuntimeObject { public: // Mono.Globalization.Unicode.CodePointIndexer_TableRange[] Mono.Globalization.Unicode.CodePointIndexer::ranges TableRangeU5BU5D_t4FC778065AD83ABC25432F9CC16725D7044A8D2E* ___ranges_0; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer::TotalCount int32_t ___TotalCount_1; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer::defaultIndex int32_t ___defaultIndex_2; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer::defaultCP int32_t ___defaultCP_3; public: inline static int32_t get_offset_of_ranges_0() { return static_cast<int32_t>(offsetof(CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A, ___ranges_0)); } inline TableRangeU5BU5D_t4FC778065AD83ABC25432F9CC16725D7044A8D2E* get_ranges_0() const { return ___ranges_0; } inline TableRangeU5BU5D_t4FC778065AD83ABC25432F9CC16725D7044A8D2E** get_address_of_ranges_0() { return &___ranges_0; } inline void set_ranges_0(TableRangeU5BU5D_t4FC778065AD83ABC25432F9CC16725D7044A8D2E* value) { ___ranges_0 = value; Il2CppCodeGenWriteBarrier((&___ranges_0), value); } inline static int32_t get_offset_of_TotalCount_1() { return static_cast<int32_t>(offsetof(CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A, ___TotalCount_1)); } inline int32_t get_TotalCount_1() const { return ___TotalCount_1; } inline int32_t* get_address_of_TotalCount_1() { return &___TotalCount_1; } inline void set_TotalCount_1(int32_t value) { ___TotalCount_1 = value; } inline static int32_t get_offset_of_defaultIndex_2() { return static_cast<int32_t>(offsetof(CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A, ___defaultIndex_2)); } inline int32_t get_defaultIndex_2() const { return ___defaultIndex_2; } inline int32_t* get_address_of_defaultIndex_2() { return &___defaultIndex_2; } inline void set_defaultIndex_2(int32_t value) { ___defaultIndex_2 = value; } inline static int32_t get_offset_of_defaultCP_3() { return static_cast<int32_t>(offsetof(CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A, ___defaultCP_3)); } inline int32_t get_defaultCP_3() const { return ___defaultCP_3; } inline int32_t* get_address_of_defaultCP_3() { return &___defaultCP_3; } inline void set_defaultCP_3(int32_t value) { ___defaultCP_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CODEPOINTINDEXER_TBEAB082D551EAD545D7B14B25BF02150303A3C2A_H #ifndef CONTRACTION_T431612397072C270EAFC2580AC4F0BBC94632A7A_H #define CONTRACTION_T431612397072C270EAFC2580AC4F0BBC94632A7A_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Globalization.Unicode.Contraction struct Contraction_t431612397072C270EAFC2580AC4F0BBC94632A7A : public RuntimeObject { public: // System.Char[] Mono.Globalization.Unicode.Contraction::Source CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* ___Source_0; // System.String Mono.Globalization.Unicode.Contraction::Replacement String_t* ___Replacement_1; // System.Byte[] Mono.Globalization.Unicode.Contraction::SortKey ByteU5BU5D_t8E14BD25C7BEB727CB1849CF449DE26B113309E8* ___SortKey_2; public: inline static int32_t get_offset_of_Source_0() { return static_cast<int32_t>(offsetof(Contraction_t431612397072C270EAFC2580AC4F0BBC94632A7A, ___Source_0)); } inline CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* get_Source_0() const { return ___Source_0; } inline CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744** get_address_of_Source_0() { return &___Source_0; } inline void set_Source_0(CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* value) { ___Source_0 = value; Il2CppCodeGenWriteBarrier((&___Source_0), value); } inline static int32_t get_offset_of_Replacement_1() { return static_cast<int32_t>(offsetof(Contraction_t431612397072C270EAFC2580AC4F0BBC94632A7A, ___Replacement_1)); } inline String_t* get_Replacement_1() const { return ___Replacement_1; } inline String_t** get_address_of_Replacement_1() { return &___Replacement_1; } inline void set_Replacement_1(String_t* value) { ___Replacement_1 = value; Il2CppCodeGenWriteBarrier((&___Replacement_1), value); } inline static int32_t get_offset_of_SortKey_2() { return static_cast<int32_t>(offsetof(Contraction_t431612397072C270EAFC2580AC4F0BBC94632A7A, ___SortKey_2)); } inline ByteU5BU5D_t8E14BD25C7BEB727CB1849CF449DE26B113309E8* get_SortKey_2() const { return ___SortKey_2; } inline ByteU5BU5D_t8E14BD25C7BEB727CB1849CF449DE26B113309E8** get_address_of_SortKey_2() { return &___SortKey_2; } inline void set_SortKey_2(ByteU5BU5D_t8E14BD25C7BEB727CB1849CF449DE26B113309E8* value) { ___SortKey_2 = value; Il2CppCodeGenWriteBarrier((&___SortKey_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONTRACTION_T431612397072C270EAFC2580AC4F0BBC94632A7A_H #ifndef CONTRACTIONCOMPARER_TE5C323345B887CA47B1B139D43C0CC053F89FFE0_H #define CONTRACTIONCOMPARER_TE5C323345B887CA47B1B139D43C0CC053F89FFE0_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Globalization.Unicode.ContractionComparer struct ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0 : public RuntimeObject { public: public: }; struct ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0_StaticFields { public: // Mono.Globalization.Unicode.ContractionComparer Mono.Globalization.Unicode.ContractionComparer::Instance ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0 * ___Instance_0; public: inline static int32_t get_offset_of_Instance_0() { return static_cast<int32_t>(offsetof(ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0_StaticFields, ___Instance_0)); } inline ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0 * get_Instance_0() const { return ___Instance_0; } inline ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0 ** get_address_of_Instance_0() { return &___Instance_0; } inline void set_Instance_0(ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0 * value) { ___Instance_0 = value; Il2CppCodeGenWriteBarrier((&___Instance_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONTRACTIONCOMPARER_TE5C323345B887CA47B1B139D43C0CC053F89FFE0_H #ifndef LEVEL2MAP_T066C49DE57EDACBB77D6F873C258FC48BF409A58_H #define LEVEL2MAP_T066C49DE57EDACBB77D6F873C258FC48BF409A58_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Globalization.Unicode.Level2Map struct Level2Map_t066C49DE57EDACBB77D6F873C258FC48BF409A58 : public RuntimeObject { public: // System.Byte Mono.Globalization.Unicode.Level2Map::Source uint8_t ___Source_0; // System.Byte Mono.Globalization.Unicode.Level2Map::Replace uint8_t ___Replace_1; public: inline static int32_t get_offset_of_Source_0() { return static_cast<int32_t>(offsetof(Level2Map_t066C49DE57EDACBB77D6F873C258FC48BF409A58, ___Source_0)); } inline uint8_t get_Source_0() const { return ___Source_0; } inline uint8_t* get_address_of_Source_0() { return &___Source_0; } inline void set_Source_0(uint8_t value) { ___Source_0 = value; } inline static int32_t get_offset_of_Replace_1() { return static_cast<int32_t>(offsetof(Level2Map_t066C49DE57EDACBB77D6F873C258FC48BF409A58, ___Replace_1)); } inline uint8_t get_Replace_1() const { return ___Replace_1; } inline uint8_t* get_address_of_Replace_1() { return &___Replace_1; } inline void set_Replace_1(uint8_t value) { ___Replace_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LEVEL2MAP_T066C49DE57EDACBB77D6F873C258FC48BF409A58_H #ifndef TAILORINGINFO_T0D99C80D20D2733A229F5AD2A49B954381A8D536_H #define TAILORINGINFO_T0D99C80D20D2733A229F5AD2A49B954381A8D536_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Globalization.Unicode.TailoringInfo struct TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536 : public RuntimeObject { public: // System.Int32 Mono.Globalization.Unicode.TailoringInfo::LCID int32_t ___LCID_0; // System.Int32 Mono.Globalization.Unicode.TailoringInfo::TailoringIndex int32_t ___TailoringIndex_1; // System.Int32 Mono.Globalization.Unicode.TailoringInfo::TailoringCount int32_t ___TailoringCount_2; // System.Boolean Mono.Globalization.Unicode.TailoringInfo::FrenchSort bool ___FrenchSort_3; public: inline static int32_t get_offset_of_LCID_0() { return static_cast<int32_t>(offsetof(TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536, ___LCID_0)); } inline int32_t get_LCID_0() const { return ___LCID_0; } inline int32_t* get_address_of_LCID_0() { return &___LCID_0; } inline void set_LCID_0(int32_t value) { ___LCID_0 = value; } inline static int32_t get_offset_of_TailoringIndex_1() { return static_cast<int32_t>(offsetof(TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536, ___TailoringIndex_1)); } inline int32_t get_TailoringIndex_1() const { return ___TailoringIndex_1; } inline int32_t* get_address_of_TailoringIndex_1() { return &___TailoringIndex_1; } inline void set_TailoringIndex_1(int32_t value) { ___TailoringIndex_1 = value; } inline static int32_t get_offset_of_TailoringCount_2() { return static_cast<int32_t>(offsetof(TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536, ___TailoringCount_2)); } inline int32_t get_TailoringCount_2() const { return ___TailoringCount_2; } inline int32_t* get_address_of_TailoringCount_2() { return &___TailoringCount_2; } inline void set_TailoringCount_2(int32_t value) { ___TailoringCount_2 = value; } inline static int32_t get_offset_of_FrenchSort_3() { return static_cast<int32_t>(offsetof(TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536, ___FrenchSort_3)); } inline bool get_FrenchSort_3() const { return ___FrenchSort_3; } inline bool* get_address_of_FrenchSort_3() { return &___FrenchSort_3; } inline void set_FrenchSort_3(bool value) { ___FrenchSort_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TAILORINGINFO_T0D99C80D20D2733A229F5AD2A49B954381A8D536_H struct Il2CppArrayBounds; #ifndef RUNTIMEARRAY_H #define RUNTIMEARRAY_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEARRAY_H #ifndef SIMPLEENUMERATOR_TF4FC79ABC6002436095E7D58D522B97A54E60590_H #define SIMPLEENUMERATOR_TF4FC79ABC6002436095E7D58D522B97A54E60590_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array_SimpleEnumerator struct SimpleEnumerator_tF4FC79ABC6002436095E7D58D522B97A54E60590 : public RuntimeObject { public: // System.Array System.Array_SimpleEnumerator::enumeratee RuntimeArray * ___enumeratee_0; // System.Int32 System.Array_SimpleEnumerator::currentpos int32_t ___currentpos_1; // System.Int32 System.Array_SimpleEnumerator::length int32_t ___length_2; public: inline static int32_t get_offset_of_enumeratee_0() { return static_cast<int32_t>(offsetof(SimpleEnumerator_tF4FC79ABC6002436095E7D58D522B97A54E60590, ___enumeratee_0)); } inline RuntimeArray * get_enumeratee_0() const { return ___enumeratee_0; } inline RuntimeArray ** get_address_of_enumeratee_0() { return &___enumeratee_0; } inline void set_enumeratee_0(RuntimeArray * value) { ___enumeratee_0 = value; Il2CppCodeGenWriteBarrier((&___enumeratee_0), value); } inline static int32_t get_offset_of_currentpos_1() { return static_cast<int32_t>(offsetof(SimpleEnumerator_tF4FC79ABC6002436095E7D58D522B97A54E60590, ___currentpos_1)); } inline int32_t get_currentpos_1() const { return ___currentpos_1; } inline int32_t* get_address_of_currentpos_1() { return &___currentpos_1; } inline void set_currentpos_1(int32_t value) { ___currentpos_1 = value; } inline static int32_t get_offset_of_length_2() { return static_cast<int32_t>(offsetof(SimpleEnumerator_tF4FC79ABC6002436095E7D58D522B97A54E60590, ___length_2)); } inline int32_t get_length_2() const { return ___length_2; } inline int32_t* get_address_of_length_2() { return &___length_2; } inline void set_length_2(int32_t value) { ___length_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SIMPLEENUMERATOR_TF4FC79ABC6002436095E7D58D522B97A54E60590_H #ifndef ATTRIBUTE_T60F25EB48D5935E4C6C2BAF7F90F57A43528E469_H #define ATTRIBUTE_T60F25EB48D5935E4C6C2BAF7F90F57A43528E469_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Attribute struct Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTE_T60F25EB48D5935E4C6C2BAF7F90F57A43528E469_H #ifndef EXCEPTION_T_H #define EXCEPTION_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Exception struct Exception_t : public RuntimeObject { public: // System.IntPtr[] System.Exception::trace_ips IntPtrU5BU5D_tB866BA24C91559CF299618E230043451CC7CF659* ___trace_ips_0; // System.Exception System.Exception::inner_exception Exception_t * ___inner_exception_1; // System.String System.Exception::message String_t* ___message_2; // System.String System.Exception::help_link String_t* ___help_link_3; // System.String System.Exception::class_name String_t* ___class_name_4; // System.String System.Exception::stack_trace String_t* ___stack_trace_5; // System.String System.Exception::_remoteStackTraceString String_t* ____remoteStackTraceString_6; // System.Int32 System.Exception::remote_stack_index int32_t ___remote_stack_index_7; // System.Int32 System.Exception::hresult int32_t ___hresult_8; // System.String System.Exception::source String_t* ___source_9; // System.Collections.IDictionary System.Exception::_data RuntimeObject* ____data_10; public: inline static int32_t get_offset_of_trace_ips_0() { return static_cast<int32_t>(offsetof(Exception_t, ___trace_ips_0)); } inline IntPtrU5BU5D_tB866BA24C91559CF299618E230043451CC7CF659* get_trace_ips_0() const { return ___trace_ips_0; } inline IntPtrU5BU5D_tB866BA24C91559CF299618E230043451CC7CF659** get_address_of_trace_ips_0() { return &___trace_ips_0; } inline void set_trace_ips_0(IntPtrU5BU5D_tB866BA24C91559CF299618E230043451CC7CF659* value) { ___trace_ips_0 = value; Il2CppCodeGenWriteBarrier((&___trace_ips_0), value); } inline static int32_t get_offset_of_inner_exception_1() { return static_cast<int32_t>(offsetof(Exception_t, ___inner_exception_1)); } inline Exception_t * get_inner_exception_1() const { return ___inner_exception_1; } inline Exception_t ** get_address_of_inner_exception_1() { return &___inner_exception_1; } inline void set_inner_exception_1(Exception_t * value) { ___inner_exception_1 = value; Il2CppCodeGenWriteBarrier((&___inner_exception_1), value); } inline static int32_t get_offset_of_message_2() { return static_cast<int32_t>(offsetof(Exception_t, ___message_2)); } inline String_t* get_message_2() const { return ___message_2; } inline String_t** get_address_of_message_2() { return &___message_2; } inline void set_message_2(String_t* value) { ___message_2 = value; Il2CppCodeGenWriteBarrier((&___message_2), value); } inline static int32_t get_offset_of_help_link_3() { return static_cast<int32_t>(offsetof(Exception_t, ___help_link_3)); } inline String_t* get_help_link_3() const { return ___help_link_3; } inline String_t** get_address_of_help_link_3() { return &___help_link_3; } inline void set_help_link_3(String_t* value) { ___help_link_3 = value; Il2CppCodeGenWriteBarrier((&___help_link_3), value); } inline static int32_t get_offset_of_class_name_4() { return static_cast<int32_t>(offsetof(Exception_t, ___class_name_4)); } inline String_t* get_class_name_4() const { return ___class_name_4; } inline String_t** get_address_of_class_name_4() { return &___class_name_4; } inline void set_class_name_4(String_t* value) { ___class_name_4 = value; Il2CppCodeGenWriteBarrier((&___class_name_4), value); } inline static int32_t get_offset_of_stack_trace_5() { return static_cast<int32_t>(offsetof(Exception_t, ___stack_trace_5)); } inline String_t* get_stack_trace_5() const { return ___stack_trace_5; } inline String_t** get_address_of_stack_trace_5() { return &___stack_trace_5; } inline void set_stack_trace_5(String_t* value) { ___stack_trace_5 = value; Il2CppCodeGenWriteBarrier((&___stack_trace_5), value); } inline static int32_t get_offset_of__remoteStackTraceString_6() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_6)); } inline String_t* get__remoteStackTraceString_6() const { return ____remoteStackTraceString_6; } inline String_t** get_address_of__remoteStackTraceString_6() { return &____remoteStackTraceString_6; } inline void set__remoteStackTraceString_6(String_t* value) { ____remoteStackTraceString_6 = value; Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_6), value); } inline static int32_t get_offset_of_remote_stack_index_7() { return static_cast<int32_t>(offsetof(Exception_t, ___remote_stack_index_7)); } inline int32_t get_remote_stack_index_7() const { return ___remote_stack_index_7; } inline int32_t* get_address_of_remote_stack_index_7() { return &___remote_stack_index_7; } inline void set_remote_stack_index_7(int32_t value) { ___remote_stack_index_7 = value; } inline static int32_t get_offset_of_hresult_8() { return static_cast<int32_t>(offsetof(Exception_t, ___hresult_8)); } inline int32_t get_hresult_8() const { return ___hresult_8; } inline int32_t* get_address_of_hresult_8() { return &___hresult_8; } inline void set_hresult_8(int32_t value) { ___hresult_8 = value; } inline static int32_t get_offset_of_source_9() { return static_cast<int32_t>(offsetof(Exception_t, ___source_9)); } inline String_t* get_source_9() const { return ___source_9; } inline String_t** get_address_of_source_9() { return &___source_9; } inline void set_source_9(String_t* value) { ___source_9 = value; Il2CppCodeGenWriteBarrier((&___source_9), value); } inline static int32_t get_offset_of__data_10() { return static_cast<int32_t>(offsetof(Exception_t, ____data_10)); } inline RuntimeObject* get__data_10() const { return ____data_10; } inline RuntimeObject** get_address_of__data_10() { return &____data_10; } inline void set__data_10(RuntimeObject* value) { ____data_10 = value; Il2CppCodeGenWriteBarrier((&____data_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EXCEPTION_T_H #ifndef MARSHALBYREFOBJECT_T05F62A8AC86E36BAE3063CA28097945DE9E179C4_H #define MARSHALBYREFOBJECT_T05F62A8AC86E36BAE3063CA28097945DE9E179C4_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MarshalByRefObject struct MarshalByRefObject_t05F62A8AC86E36BAE3063CA28097945DE9E179C4 : public RuntimeObject { public: // System.Runtime.Remoting.ServerIdentity System.MarshalByRefObject::_identity ServerIdentity_t3C5F8BAEFAC94CF69694273ACCB6CB41355E0B5C * ____identity_0; public: inline static int32_t get_offset_of__identity_0() { return static_cast<int32_t>(offsetof(MarshalByRefObject_t05F62A8AC86E36BAE3063CA28097945DE9E179C4, ____identity_0)); } inline ServerIdentity_t3C5F8BAEFAC94CF69694273ACCB6CB41355E0B5C * get__identity_0() const { return ____identity_0; } inline ServerIdentity_t3C5F8BAEFAC94CF69694273ACCB6CB41355E0B5C ** get_address_of__identity_0() { return &____identity_0; } inline void set__identity_0(ServerIdentity_t3C5F8BAEFAC94CF69694273ACCB6CB41355E0B5C * value) { ____identity_0 = value; Il2CppCodeGenWriteBarrier((&____identity_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MARSHALBYREFOBJECT_T05F62A8AC86E36BAE3063CA28097945DE9E179C4_H #ifndef MEMBERINFO_T_H #define MEMBERINFO_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.MemberInfo struct MemberInfo_t : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MEMBERINFO_T_H #ifndef RUNTIMEHELPERS_T58E3CCC7308DD00F68A88BF555A80FF0FBABE8D3_H #define RUNTIMEHELPERS_T58E3CCC7308DD00F68A88BF555A80FF0FBABE8D3_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.CompilerServices.RuntimeHelpers struct RuntimeHelpers_t58E3CCC7308DD00F68A88BF555A80FF0FBABE8D3 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEHELPERS_T58E3CCC7308DD00F68A88BF555A80FF0FBABE8D3_H #ifndef CRITICALFINALIZEROBJECT_TEF12E2D0ADC15894681402455E99775943930F94_H #define CRITICALFINALIZEROBJECT_TEF12E2D0ADC15894681402455E99775943930F94_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.ConstrainedExecution.CriticalFinalizerObject struct CriticalFinalizerObject_tEF12E2D0ADC15894681402455E99775943930F94 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CRITICALFINALIZEROBJECT_TEF12E2D0ADC15894681402455E99775943930F94_H #ifndef STRING_T_H #define STRING_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::length int32_t ___length_0; // System.Char System.String::start_char Il2CppChar ___start_char_1; public: inline static int32_t get_offset_of_length_0() { return static_cast<int32_t>(offsetof(String_t, ___length_0)); } inline int32_t get_length_0() const { return ___length_0; } inline int32_t* get_address_of_length_0() { return &___length_0; } inline void set_length_0(int32_t value) { ___length_0 = value; } inline static int32_t get_offset_of_start_char_1() { return static_cast<int32_t>(offsetof(String_t, ___start_char_1)); } inline Il2CppChar get_start_char_1() const { return ___start_char_1; } inline Il2CppChar* get_address_of_start_char_1() { return &___start_char_1; } inline void set_start_char_1(Il2CppChar value) { ___start_char_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_2; // System.Char[] System.String::WhiteChars CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* ___WhiteChars_3; public: inline static int32_t get_offset_of_Empty_2() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_2)); } inline String_t* get_Empty_2() const { return ___Empty_2; } inline String_t** get_address_of_Empty_2() { return &___Empty_2; } inline void set_Empty_2(String_t* value) { ___Empty_2 = value; Il2CppCodeGenWriteBarrier((&___Empty_2), value); } inline static int32_t get_offset_of_WhiteChars_3() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___WhiteChars_3)); } inline CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* get_WhiteChars_3() const { return ___WhiteChars_3; } inline CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744** get_address_of_WhiteChars_3() { return &___WhiteChars_3; } inline void set_WhiteChars_3(CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* value) { ___WhiteChars_3 = value; Il2CppCodeGenWriteBarrier((&___WhiteChars_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRING_T_H #ifndef VALUETYPE_T1810BD84E0FDB5D3A7CD34286A5B22F343995C9C_H #define VALUETYPE_T1810BD84E0FDB5D3A7CD34286A5B22F343995C9C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t1810BD84E0FDB5D3A7CD34286A5B22F343995C9C : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t1810BD84E0FDB5D3A7CD34286A5B22F343995C9C_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t1810BD84E0FDB5D3A7CD34286A5B22F343995C9C_marshaled_com { }; #endif // VALUETYPE_T1810BD84E0FDB5D3A7CD34286A5B22F343995C9C_H #ifndef TABLERANGE_T7412995BCD43AB0D42039C6DF1413777053C8C52_H #define TABLERANGE_T7412995BCD43AB0D42039C6DF1413777053C8C52_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Globalization.Unicode.CodePointIndexer_TableRange struct TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52 { public: // System.Int32 Mono.Globalization.Unicode.CodePointIndexer_TableRange::Start int32_t ___Start_0; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer_TableRange::End int32_t ___End_1; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer_TableRange::Count int32_t ___Count_2; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer_TableRange::IndexStart int32_t ___IndexStart_3; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer_TableRange::IndexEnd int32_t ___IndexEnd_4; public: inline static int32_t get_offset_of_Start_0() { return static_cast<int32_t>(offsetof(TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52, ___Start_0)); } inline int32_t get_Start_0() const { return ___Start_0; } inline int32_t* get_address_of_Start_0() { return &___Start_0; } inline void set_Start_0(int32_t value) { ___Start_0 = value; } inline static int32_t get_offset_of_End_1() { return static_cast<int32_t>(offsetof(TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52, ___End_1)); } inline int32_t get_End_1() const { return ___End_1; } inline int32_t* get_address_of_End_1() { return &___End_1; } inline void set_End_1(int32_t value) { ___End_1 = value; } inline static int32_t get_offset_of_Count_2() { return static_cast<int32_t>(offsetof(TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52, ___Count_2)); } inline int32_t get_Count_2() const { return ___Count_2; } inline int32_t* get_address_of_Count_2() { return &___Count_2; } inline void set_Count_2(int32_t value) { ___Count_2 = value; } inline static int32_t get_offset_of_IndexStart_3() { return static_cast<int32_t>(offsetof(TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52, ___IndexStart_3)); } inline int32_t get_IndexStart_3() const { return ___IndexStart_3; } inline int32_t* get_address_of_IndexStart_3() { return &___IndexStart_3; } inline void set_IndexStart_3(int32_t value) { ___IndexStart_3 = value; } inline static int32_t get_offset_of_IndexEnd_4() { return static_cast<int32_t>(offsetof(TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52, ___IndexEnd_4)); } inline int32_t get_IndexEnd_4() const { return ___IndexEnd_4; } inline int32_t* get_address_of_IndexEnd_4() { return &___IndexEnd_4; } inline void set_IndexEnd_4(int32_t value) { ___IndexEnd_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TABLERANGE_T7412995BCD43AB0D42039C6DF1413777053C8C52_H #ifndef BOOLEAN_T92E4792324DA9B716F339A3B965A14965E99A4EF_H #define BOOLEAN_T92E4792324DA9B716F339A3B965A14965E99A4EF_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Boolean struct Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF { public: // System.Boolean System.Boolean::m_value bool ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF, ___m_value_2)); } inline bool get_m_value_2() const { return ___m_value_2; } inline bool* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(bool value) { ___m_value_2 = value; } }; struct Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF_StaticFields { public: // System.String System.Boolean::FalseString String_t* ___FalseString_0; // System.String System.Boolean::TrueString String_t* ___TrueString_1; public: inline static int32_t get_offset_of_FalseString_0() { return static_cast<int32_t>(offsetof(Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF_StaticFields, ___FalseString_0)); } inline String_t* get_FalseString_0() const { return ___FalseString_0; } inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; } inline void set_FalseString_0(String_t* value) { ___FalseString_0 = value; Il2CppCodeGenWriteBarrier((&___FalseString_0), value); } inline static int32_t get_offset_of_TrueString_1() { return static_cast<int32_t>(offsetof(Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF_StaticFields, ___TrueString_1)); } inline String_t* get_TrueString_1() const { return ___TrueString_1; } inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; } inline void set_TrueString_1(String_t* value) { ___TrueString_1 = value; Il2CppCodeGenWriteBarrier((&___TrueString_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEAN_T92E4792324DA9B716F339A3B965A14965E99A4EF_H #ifndef BYTE_T4C3393E6E7EAD06B53234C05564190D9A2D7B149_H #define BYTE_T4C3393E6E7EAD06B53234C05564190D9A2D7B149_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Byte struct Byte_t4C3393E6E7EAD06B53234C05564190D9A2D7B149 { public: // System.Byte System.Byte::m_value uint8_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Byte_t4C3393E6E7EAD06B53234C05564190D9A2D7B149, ___m_value_2)); } inline uint8_t get_m_value_2() const { return ___m_value_2; } inline uint8_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(uint8_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BYTE_T4C3393E6E7EAD06B53234C05564190D9A2D7B149_H #ifndef CLSCOMPLIANTATTRIBUTE_T161163A690EF51165D83B0C3F0FE5E69662722C3_H #define CLSCOMPLIANTATTRIBUTE_T161163A690EF51165D83B0C3F0FE5E69662722C3_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.CLSCompliantAttribute struct CLSCompliantAttribute_t161163A690EF51165D83B0C3F0FE5E69662722C3 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.Boolean System.CLSCompliantAttribute::is_compliant bool ___is_compliant_0; public: inline static int32_t get_offset_of_is_compliant_0() { return static_cast<int32_t>(offsetof(CLSCompliantAttribute_t161163A690EF51165D83B0C3F0FE5E69662722C3, ___is_compliant_0)); } inline bool get_is_compliant_0() const { return ___is_compliant_0; } inline bool* get_address_of_is_compliant_0() { return &___is_compliant_0; } inline void set_is_compliant_0(bool value) { ___is_compliant_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CLSCOMPLIANTATTRIBUTE_T161163A690EF51165D83B0C3F0FE5E69662722C3_H #ifndef CHAR_T2AF4E0DF8B57497BF49A6A8822F574113ADA8432_H #define CHAR_T2AF4E0DF8B57497BF49A6A8822F574113ADA8432_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Char struct Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432 { public: // System.Char System.Char::m_value Il2CppChar ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432, ___m_value_2)); } inline Il2CppChar get_m_value_2() const { return ___m_value_2; } inline Il2CppChar* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(Il2CppChar value) { ___m_value_2 = value; } }; struct Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields { public: // System.Byte* System.Char::category_data uint8_t* ___category_data_3; // System.Byte* System.Char::numeric_data uint8_t* ___numeric_data_4; // System.Double* System.Char::numeric_data_values double* ___numeric_data_values_5; // System.UInt16* System.Char::to_lower_data_low uint16_t* ___to_lower_data_low_6; // System.UInt16* System.Char::to_lower_data_high uint16_t* ___to_lower_data_high_7; // System.UInt16* System.Char::to_upper_data_low uint16_t* ___to_upper_data_low_8; // System.UInt16* System.Char::to_upper_data_high uint16_t* ___to_upper_data_high_9; public: inline static int32_t get_offset_of_category_data_3() { return static_cast<int32_t>(offsetof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields, ___category_data_3)); } inline uint8_t* get_category_data_3() const { return ___category_data_3; } inline uint8_t** get_address_of_category_data_3() { return &___category_data_3; } inline void set_category_data_3(uint8_t* value) { ___category_data_3 = value; } inline static int32_t get_offset_of_numeric_data_4() { return static_cast<int32_t>(offsetof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields, ___numeric_data_4)); } inline uint8_t* get_numeric_data_4() const { return ___numeric_data_4; } inline uint8_t** get_address_of_numeric_data_4() { return &___numeric_data_4; } inline void set_numeric_data_4(uint8_t* value) { ___numeric_data_4 = value; } inline static int32_t get_offset_of_numeric_data_values_5() { return static_cast<int32_t>(offsetof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields, ___numeric_data_values_5)); } inline double* get_numeric_data_values_5() const { return ___numeric_data_values_5; } inline double** get_address_of_numeric_data_values_5() { return &___numeric_data_values_5; } inline void set_numeric_data_values_5(double* value) { ___numeric_data_values_5 = value; } inline static int32_t get_offset_of_to_lower_data_low_6() { return static_cast<int32_t>(offsetof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields, ___to_lower_data_low_6)); } inline uint16_t* get_to_lower_data_low_6() const { return ___to_lower_data_low_6; } inline uint16_t** get_address_of_to_lower_data_low_6() { return &___to_lower_data_low_6; } inline void set_to_lower_data_low_6(uint16_t* value) { ___to_lower_data_low_6 = value; } inline static int32_t get_offset_of_to_lower_data_high_7() { return static_cast<int32_t>(offsetof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields, ___to_lower_data_high_7)); } inline uint16_t* get_to_lower_data_high_7() const { return ___to_lower_data_high_7; } inline uint16_t** get_address_of_to_lower_data_high_7() { return &___to_lower_data_high_7; } inline void set_to_lower_data_high_7(uint16_t* value) { ___to_lower_data_high_7 = value; } inline static int32_t get_offset_of_to_upper_data_low_8() { return static_cast<int32_t>(offsetof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields, ___to_upper_data_low_8)); } inline uint16_t* get_to_upper_data_low_8() const { return ___to_upper_data_low_8; } inline uint16_t** get_address_of_to_upper_data_low_8() { return &___to_upper_data_low_8; } inline void set_to_upper_data_low_8(uint16_t* value) { ___to_upper_data_low_8 = value; } inline static int32_t get_offset_of_to_upper_data_high_9() { return static_cast<int32_t>(offsetof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields, ___to_upper_data_high_9)); } inline uint16_t* get_to_upper_data_high_9() const { return ___to_upper_data_high_9; } inline uint16_t** get_address_of_to_upper_data_high_9() { return &___to_upper_data_high_9; } inline void set_to_upper_data_high_9(uint16_t* value) { ___to_upper_data_high_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CHAR_T2AF4E0DF8B57497BF49A6A8822F574113ADA8432_H #ifndef DECIMAL_T46BBDD161320E361BC57E00CD6C1F87256CA27F3_H #define DECIMAL_T46BBDD161320E361BC57E00CD6C1F87256CA27F3_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Decimal struct Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 { public: // System.UInt32 System.Decimal::flags uint32_t ___flags_5; // System.UInt32 System.Decimal::hi uint32_t ___hi_6; // System.UInt32 System.Decimal::lo uint32_t ___lo_7; // System.UInt32 System.Decimal::mid uint32_t ___mid_8; public: inline static int32_t get_offset_of_flags_5() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3, ___flags_5)); } inline uint32_t get_flags_5() const { return ___flags_5; } inline uint32_t* get_address_of_flags_5() { return &___flags_5; } inline void set_flags_5(uint32_t value) { ___flags_5 = value; } inline static int32_t get_offset_of_hi_6() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3, ___hi_6)); } inline uint32_t get_hi_6() const { return ___hi_6; } inline uint32_t* get_address_of_hi_6() { return &___hi_6; } inline void set_hi_6(uint32_t value) { ___hi_6 = value; } inline static int32_t get_offset_of_lo_7() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3, ___lo_7)); } inline uint32_t get_lo_7() const { return ___lo_7; } inline uint32_t* get_address_of_lo_7() { return &___lo_7; } inline void set_lo_7(uint32_t value) { ___lo_7 = value; } inline static int32_t get_offset_of_mid_8() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3, ___mid_8)); } inline uint32_t get_mid_8() const { return ___mid_8; } inline uint32_t* get_address_of_mid_8() { return &___mid_8; } inline void set_mid_8(uint32_t value) { ___mid_8 = value; } }; struct Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields { public: // System.Decimal System.Decimal::MinValue Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 ___MinValue_0; // System.Decimal System.Decimal::MaxValue Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 ___MaxValue_1; // System.Decimal System.Decimal::MinusOne Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 ___MinusOne_2; // System.Decimal System.Decimal::One Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 ___One_3; // System.Decimal System.Decimal::MaxValueDiv10 Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 ___MaxValueDiv10_4; public: inline static int32_t get_offset_of_MinValue_0() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields, ___MinValue_0)); } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 get_MinValue_0() const { return ___MinValue_0; } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 * get_address_of_MinValue_0() { return &___MinValue_0; } inline void set_MinValue_0(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 value) { ___MinValue_0 = value; } inline static int32_t get_offset_of_MaxValue_1() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields, ___MaxValue_1)); } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 get_MaxValue_1() const { return ___MaxValue_1; } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 * get_address_of_MaxValue_1() { return &___MaxValue_1; } inline void set_MaxValue_1(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 value) { ___MaxValue_1 = value; } inline static int32_t get_offset_of_MinusOne_2() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields, ___MinusOne_2)); } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 get_MinusOne_2() const { return ___MinusOne_2; } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 * get_address_of_MinusOne_2() { return &___MinusOne_2; } inline void set_MinusOne_2(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 value) { ___MinusOne_2 = value; } inline static int32_t get_offset_of_One_3() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields, ___One_3)); } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 get_One_3() const { return ___One_3; } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 * get_address_of_One_3() { return &___One_3; } inline void set_One_3(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 value) { ___One_3 = value; } inline static int32_t get_offset_of_MaxValueDiv10_4() { return static_cast<int32_t>(offsetof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields, ___MaxValueDiv10_4)); } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 get_MaxValueDiv10_4() const { return ___MaxValueDiv10_4; } inline Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 * get_address_of_MaxValueDiv10_4() { return &___MaxValueDiv10_4; } inline void set_MaxValueDiv10_4(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 value) { ___MaxValueDiv10_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DECIMAL_T46BBDD161320E361BC57E00CD6C1F87256CA27F3_H #ifndef CONDITIONALATTRIBUTE_T65D186CC2DEFD4F839DDCFB180B8AEE8293779AA_H #define CONDITIONALATTRIBUTE_T65D186CC2DEFD4F839DDCFB180B8AEE8293779AA_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Diagnostics.ConditionalAttribute struct ConditionalAttribute_t65D186CC2DEFD4F839DDCFB180B8AEE8293779AA : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.String System.Diagnostics.ConditionalAttribute::myCondition String_t* ___myCondition_0; public: inline static int32_t get_offset_of_myCondition_0() { return static_cast<int32_t>(offsetof(ConditionalAttribute_t65D186CC2DEFD4F839DDCFB180B8AEE8293779AA, ___myCondition_0)); } inline String_t* get_myCondition_0() const { return ___myCondition_0; } inline String_t** get_address_of_myCondition_0() { return &___myCondition_0; } inline void set_myCondition_0(String_t* value) { ___myCondition_0 = value; Il2CppCodeGenWriteBarrier((&___myCondition_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONDITIONALATTRIBUTE_T65D186CC2DEFD4F839DDCFB180B8AEE8293779AA_H #ifndef DEBUGGERHIDDENATTRIBUTE_TC1385C90899898587339A9A236F8ED9800400417_H #define DEBUGGERHIDDENATTRIBUTE_TC1385C90899898587339A9A236F8ED9800400417_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Diagnostics.DebuggerHiddenAttribute struct DebuggerHiddenAttribute_tC1385C90899898587339A9A236F8ED9800400417 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DEBUGGERHIDDENATTRIBUTE_TC1385C90899898587339A9A236F8ED9800400417_H #ifndef DOUBLE_T2011D65DAF7D1FCBE71DD4CBDFA69A8F24643159_H #define DOUBLE_T2011D65DAF7D1FCBE71DD4CBDFA69A8F24643159_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Double struct Double_t2011D65DAF7D1FCBE71DD4CBDFA69A8F24643159 { public: // System.Double System.Double::m_value double ___m_value_13; public: inline static int32_t get_offset_of_m_value_13() { return static_cast<int32_t>(offsetof(Double_t2011D65DAF7D1FCBE71DD4CBDFA69A8F24643159, ___m_value_13)); } inline double get_m_value_13() const { return ___m_value_13; } inline double* get_address_of_m_value_13() { return &___m_value_13; } inline void set_m_value_13(double value) { ___m_value_13 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DOUBLE_T2011D65DAF7D1FCBE71DD4CBDFA69A8F24643159_H #ifndef ENUM_T5AAC444DFCAA78411386665A25FE3CD3169879EF_H #define ENUM_T5AAC444DFCAA78411386665A25FE3CD3169879EF_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF : public ValueType_t1810BD84E0FDB5D3A7CD34286A5B22F343995C9C { public: public: }; struct Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF_StaticFields { public: // System.Char[] System.Enum::split_char CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* ___split_char_0; public: inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF_StaticFields, ___split_char_0)); } inline CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* get_split_char_0() const { return ___split_char_0; } inline CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744** get_address_of_split_char_0() { return &___split_char_0; } inline void set_split_char_0(CharU5BU5D_t79D85CE93255C78D04436552445C364ED409B744* value) { ___split_char_0 = value; Il2CppCodeGenWriteBarrier((&___split_char_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF_marshaled_com { }; #endif // ENUM_T5AAC444DFCAA78411386665A25FE3CD3169879EF_H #ifndef INT16_TBFC41132AB8E6B4E1F9D4A1E3CC46422BF453F3C_H #define INT16_TBFC41132AB8E6B4E1F9D4A1E3CC46422BF453F3C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int16 struct Int16_tBFC41132AB8E6B4E1F9D4A1E3CC46422BF453F3C { public: // System.Int16 System.Int16::m_value int16_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int16_tBFC41132AB8E6B4E1F9D4A1E3CC46422BF453F3C, ___m_value_2)); } inline int16_t get_m_value_2() const { return ___m_value_2; } inline int16_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int16_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT16_TBFC41132AB8E6B4E1F9D4A1E3CC46422BF453F3C_H #ifndef INT32_TC16F64335CE8B56D99229DE94BB3A876ED55FE87_H #define INT32_TC16F64335CE8B56D99229DE94BB3A876ED55FE87_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 struct Int32_tC16F64335CE8B56D99229DE94BB3A876ED55FE87 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int32_tC16F64335CE8B56D99229DE94BB3A876ED55FE87, ___m_value_2)); } inline int32_t get_m_value_2() const { return ___m_value_2; } inline int32_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int32_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32_TC16F64335CE8B56D99229DE94BB3A876ED55FE87_H #ifndef INT64_TF61270729FC90F8A705A5FA6FE222C9644374ADF_H #define INT64_TF61270729FC90F8A705A5FA6FE222C9644374ADF_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int64 struct Int64_tF61270729FC90F8A705A5FA6FE222C9644374ADF { public: // System.Int64 System.Int64::m_value int64_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int64_tF61270729FC90F8A705A5FA6FE222C9644374ADF, ___m_value_2)); } inline int64_t get_m_value_2() const { return ___m_value_2; } inline int64_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int64_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT64_TF61270729FC90F8A705A5FA6FE222C9644374ADF_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef MONOTODOATTRIBUTE_TC3BFF62878CE5A141978F4C91C28CFE340F3BB45_H #define MONOTODOATTRIBUTE_TC3BFF62878CE5A141978F4C91C28CFE340F3BB45_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MonoTODOAttribute struct MonoTODOAttribute_tC3BFF62878CE5A141978F4C91C28CFE340F3BB45 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.String System.MonoTODOAttribute::comment String_t* ___comment_0; public: inline static int32_t get_offset_of_comment_0() { return static_cast<int32_t>(offsetof(MonoTODOAttribute_tC3BFF62878CE5A141978F4C91C28CFE340F3BB45, ___comment_0)); } inline String_t* get_comment_0() const { return ___comment_0; } inline String_t** get_address_of_comment_0() { return &___comment_0; } inline void set_comment_0(String_t* value) { ___comment_0 = value; Il2CppCodeGenWriteBarrier((&___comment_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MONOTODOATTRIBUTE_TC3BFF62878CE5A141978F4C91C28CFE340F3BB45_H #ifndef OBSOLETEATTRIBUTE_TF664926888D92615CB9A166412D1E197874E2C94_H #define OBSOLETEATTRIBUTE_TF664926888D92615CB9A166412D1E197874E2C94_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ObsoleteAttribute struct ObsoleteAttribute_tF664926888D92615CB9A166412D1E197874E2C94 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.String System.ObsoleteAttribute::_message String_t* ____message_0; // System.Boolean System.ObsoleteAttribute::_error bool ____error_1; public: inline static int32_t get_offset_of__message_0() { return static_cast<int32_t>(offsetof(ObsoleteAttribute_tF664926888D92615CB9A166412D1E197874E2C94, ____message_0)); } inline String_t* get__message_0() const { return ____message_0; } inline String_t** get_address_of__message_0() { return &____message_0; } inline void set__message_0(String_t* value) { ____message_0 = value; Il2CppCodeGenWriteBarrier((&____message_0), value); } inline static int32_t get_offset_of__error_1() { return static_cast<int32_t>(offsetof(ObsoleteAttribute_tF664926888D92615CB9A166412D1E197874E2C94, ____error_1)); } inline bool get__error_1() const { return ____error_1; } inline bool* get_address_of__error_1() { return &____error_1; } inline void set__error_1(bool value) { ____error_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OBSOLETEATTRIBUTE_TF664926888D92615CB9A166412D1E197874E2C94_H #ifndef PARAMARRAYATTRIBUTE_T2108C09F62ACD30BCEB0D170A0DE5D779783EC22_H #define PARAMARRAYATTRIBUTE_T2108C09F62ACD30BCEB0D170A0DE5D779783EC22_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ParamArrayAttribute struct ParamArrayAttribute_t2108C09F62ACD30BCEB0D170A0DE5D779783EC22 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PARAMARRAYATTRIBUTE_T2108C09F62ACD30BCEB0D170A0DE5D779783EC22_H #ifndef DEFAULTMEMBERATTRIBUTE_TA6BDB6141F5EE774BC59AA22BFFBE34A41C944C8_H #define DEFAULTMEMBERATTRIBUTE_TA6BDB6141F5EE774BC59AA22BFFBE34A41C944C8_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.DefaultMemberAttribute struct DefaultMemberAttribute_tA6BDB6141F5EE774BC59AA22BFFBE34A41C944C8 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.String System.Reflection.DefaultMemberAttribute::member_name String_t* ___member_name_0; public: inline static int32_t get_offset_of_member_name_0() { return static_cast<int32_t>(offsetof(DefaultMemberAttribute_tA6BDB6141F5EE774BC59AA22BFFBE34A41C944C8, ___member_name_0)); } inline String_t* get_member_name_0() const { return ___member_name_0; } inline String_t** get_address_of_member_name_0() { return &___member_name_0; } inline void set_member_name_0(String_t* value) { ___member_name_0 = value; Il2CppCodeGenWriteBarrier((&___member_name_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DEFAULTMEMBERATTRIBUTE_TA6BDB6141F5EE774BC59AA22BFFBE34A41C944C8_H #ifndef COMPILERGENERATEDATTRIBUTE_T98B4A7C00E6A42E9E9D561FB9C8FC96304E069C5_H #define COMPILERGENERATEDATTRIBUTE_T98B4A7C00E6A42E9E9D561FB9C8FC96304E069C5_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.CompilerServices.CompilerGeneratedAttribute struct CompilerGeneratedAttribute_t98B4A7C00E6A42E9E9D561FB9C8FC96304E069C5 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMPILERGENERATEDATTRIBUTE_T98B4A7C00E6A42E9E9D561FB9C8FC96304E069C5_H #ifndef DECIMALCONSTANTATTRIBUTE_T5A37F426D60FE70806686E34D623A296AFB90821_H #define DECIMALCONSTANTATTRIBUTE_T5A37F426D60FE70806686E34D623A296AFB90821_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.CompilerServices.DecimalConstantAttribute struct DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.Byte System.Runtime.CompilerServices.DecimalConstantAttribute::scale uint8_t ___scale_0; // System.Boolean System.Runtime.CompilerServices.DecimalConstantAttribute::sign bool ___sign_1; // System.Int32 System.Runtime.CompilerServices.DecimalConstantAttribute::hi int32_t ___hi_2; // System.Int32 System.Runtime.CompilerServices.DecimalConstantAttribute::mid int32_t ___mid_3; // System.Int32 System.Runtime.CompilerServices.DecimalConstantAttribute::low int32_t ___low_4; public: inline static int32_t get_offset_of_scale_0() { return static_cast<int32_t>(offsetof(DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821, ___scale_0)); } inline uint8_t get_scale_0() const { return ___scale_0; } inline uint8_t* get_address_of_scale_0() { return &___scale_0; } inline void set_scale_0(uint8_t value) { ___scale_0 = value; } inline static int32_t get_offset_of_sign_1() { return static_cast<int32_t>(offsetof(DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821, ___sign_1)); } inline bool get_sign_1() const { return ___sign_1; } inline bool* get_address_of_sign_1() { return &___sign_1; } inline void set_sign_1(bool value) { ___sign_1 = value; } inline static int32_t get_offset_of_hi_2() { return static_cast<int32_t>(offsetof(DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821, ___hi_2)); } inline int32_t get_hi_2() const { return ___hi_2; } inline int32_t* get_address_of_hi_2() { return &___hi_2; } inline void set_hi_2(int32_t value) { ___hi_2 = value; } inline static int32_t get_offset_of_mid_3() { return static_cast<int32_t>(offsetof(DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821, ___mid_3)); } inline int32_t get_mid_3() const { return ___mid_3; } inline int32_t* get_address_of_mid_3() { return &___mid_3; } inline void set_mid_3(int32_t value) { ___mid_3 = value; } inline static int32_t get_offset_of_low_4() { return static_cast<int32_t>(offsetof(DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821, ___low_4)); } inline int32_t get_low_4() const { return ___low_4; } inline int32_t* get_address_of_low_4() { return &___low_4; } inline void set_low_4(int32_t value) { ___low_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DECIMALCONSTANTATTRIBUTE_T5A37F426D60FE70806686E34D623A296AFB90821_H #ifndef FIXEDBUFFERATTRIBUTE_T9367EDE2ADFA15474F1A91C8387D022B4728B064_H #define FIXEDBUFFERATTRIBUTE_T9367EDE2ADFA15474F1A91C8387D022B4728B064_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.CompilerServices.FixedBufferAttribute struct FixedBufferAttribute_t9367EDE2ADFA15474F1A91C8387D022B4728B064 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.Type System.Runtime.CompilerServices.FixedBufferAttribute::elementType Type_t * ___elementType_0; // System.Int32 System.Runtime.CompilerServices.FixedBufferAttribute::length int32_t ___length_1; public: inline static int32_t get_offset_of_elementType_0() { return static_cast<int32_t>(offsetof(FixedBufferAttribute_t9367EDE2ADFA15474F1A91C8387D022B4728B064, ___elementType_0)); } inline Type_t * get_elementType_0() const { return ___elementType_0; } inline Type_t ** get_address_of_elementType_0() { return &___elementType_0; } inline void set_elementType_0(Type_t * value) { ___elementType_0 = value; Il2CppCodeGenWriteBarrier((&___elementType_0), value); } inline static int32_t get_offset_of_length_1() { return static_cast<int32_t>(offsetof(FixedBufferAttribute_t9367EDE2ADFA15474F1A91C8387D022B4728B064, ___length_1)); } inline int32_t get_length_1() const { return ___length_1; } inline int32_t* get_address_of_length_1() { return &___length_1; } inline void set_length_1(int32_t value) { ___length_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FIXEDBUFFERATTRIBUTE_T9367EDE2ADFA15474F1A91C8387D022B4728B064_H #ifndef INTERNALSVISIBLETOATTRIBUTE_T63DF8EC119150BF501084AF970829C6AEFA2B0F4_H #define INTERNALSVISIBLETOATTRIBUTE_T63DF8EC119150BF501084AF970829C6AEFA2B0F4_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.CompilerServices.InternalsVisibleToAttribute struct InternalsVisibleToAttribute_t63DF8EC119150BF501084AF970829C6AEFA2B0F4 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.String System.Runtime.CompilerServices.InternalsVisibleToAttribute::assemblyName String_t* ___assemblyName_0; // System.Boolean System.Runtime.CompilerServices.InternalsVisibleToAttribute::all_visible bool ___all_visible_1; public: inline static int32_t get_offset_of_assemblyName_0() { return static_cast<int32_t>(offsetof(InternalsVisibleToAttribute_t63DF8EC119150BF501084AF970829C6AEFA2B0F4, ___assemblyName_0)); } inline String_t* get_assemblyName_0() const { return ___assemblyName_0; } inline String_t** get_address_of_assemblyName_0() { return &___assemblyName_0; } inline void set_assemblyName_0(String_t* value) { ___assemblyName_0 = value; Il2CppCodeGenWriteBarrier((&___assemblyName_0), value); } inline static int32_t get_offset_of_all_visible_1() { return static_cast<int32_t>(offsetof(InternalsVisibleToAttribute_t63DF8EC119150BF501084AF970829C6AEFA2B0F4, ___all_visible_1)); } inline bool get_all_visible_1() const { return ___all_visible_1; } inline bool* get_address_of_all_visible_1() { return &___all_visible_1; } inline void set_all_visible_1(bool value) { ___all_visible_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERNALSVISIBLETOATTRIBUTE_T63DF8EC119150BF501084AF970829C6AEFA2B0F4_H #ifndef RUNTIMECOMPATIBILITYATTRIBUTE_TCB1191BA01F9F4A9B02DE1F89A021DC4E9BAA23A_H #define RUNTIMECOMPATIBILITYATTRIBUTE_TCB1191BA01F9F4A9B02DE1F89A021DC4E9BAA23A_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.CompilerServices.RuntimeCompatibilityAttribute struct RuntimeCompatibilityAttribute_tCB1191BA01F9F4A9B02DE1F89A021DC4E9BAA23A : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::wrap_non_exception_throws bool ___wrap_non_exception_throws_0; public: inline static int32_t get_offset_of_wrap_non_exception_throws_0() { return static_cast<int32_t>(offsetof(RuntimeCompatibilityAttribute_tCB1191BA01F9F4A9B02DE1F89A021DC4E9BAA23A, ___wrap_non_exception_throws_0)); } inline bool get_wrap_non_exception_throws_0() const { return ___wrap_non_exception_throws_0; } inline bool* get_address_of_wrap_non_exception_throws_0() { return &___wrap_non_exception_throws_0; } inline void set_wrap_non_exception_throws_0(bool value) { ___wrap_non_exception_throws_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMECOMPATIBILITYATTRIBUTE_TCB1191BA01F9F4A9B02DE1F89A021DC4E9BAA23A_H #ifndef COMIMPORTATTRIBUTE_TAFEEBF41C09108C78BE098E6951686BDA2F92EEE_H #define COMIMPORTATTRIBUTE_TAFEEBF41C09108C78BE098E6951686BDA2F92EEE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.ComImportAttribute struct ComImportAttribute_tAFEEBF41C09108C78BE098E6951686BDA2F92EEE : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMIMPORTATTRIBUTE_TAFEEBF41C09108C78BE098E6951686BDA2F92EEE_H #ifndef COMVISIBLEATTRIBUTE_T0B3C80B1CF94B29B53B75A802635D11303B1EFE5_H #define COMVISIBLEATTRIBUTE_T0B3C80B1CF94B29B53B75A802635D11303B1EFE5_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.ComVisibleAttribute struct ComVisibleAttribute_t0B3C80B1CF94B29B53B75A802635D11303B1EFE5 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.Boolean System.Runtime.InteropServices.ComVisibleAttribute::Visible bool ___Visible_0; public: inline static int32_t get_offset_of_Visible_0() { return static_cast<int32_t>(offsetof(ComVisibleAttribute_t0B3C80B1CF94B29B53B75A802635D11303B1EFE5, ___Visible_0)); } inline bool get_Visible_0() const { return ___Visible_0; } inline bool* get_address_of_Visible_0() { return &___Visible_0; } inline void set_Visible_0(bool value) { ___Visible_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMVISIBLEATTRIBUTE_T0B3C80B1CF94B29B53B75A802635D11303B1EFE5_H #ifndef FIELDOFFSETATTRIBUTE_T6903AC169DD803EBEB6DD0FFE54D1568CA186DAC_H #define FIELDOFFSETATTRIBUTE_T6903AC169DD803EBEB6DD0FFE54D1568CA186DAC_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.FieldOffsetAttribute struct FieldOffsetAttribute_t6903AC169DD803EBEB6DD0FFE54D1568CA186DAC : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.Int32 System.Runtime.InteropServices.FieldOffsetAttribute::val int32_t ___val_0; public: inline static int32_t get_offset_of_val_0() { return static_cast<int32_t>(offsetof(FieldOffsetAttribute_t6903AC169DD803EBEB6DD0FFE54D1568CA186DAC, ___val_0)); } inline int32_t get_val_0() const { return ___val_0; } inline int32_t* get_address_of_val_0() { return &___val_0; } inline void set_val_0(int32_t value) { ___val_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FIELDOFFSETATTRIBUTE_T6903AC169DD803EBEB6DD0FFE54D1568CA186DAC_H #ifndef GUIDATTRIBUTE_TFADD188D2E2B2BF32624D558D1E7D2A6086E35DB_H #define GUIDATTRIBUTE_TFADD188D2E2B2BF32624D558D1E7D2A6086E35DB_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.GuidAttribute struct GuidAttribute_tFADD188D2E2B2BF32624D558D1E7D2A6086E35DB : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.String System.Runtime.InteropServices.GuidAttribute::guidValue String_t* ___guidValue_0; public: inline static int32_t get_offset_of_guidValue_0() { return static_cast<int32_t>(offsetof(GuidAttribute_tFADD188D2E2B2BF32624D558D1E7D2A6086E35DB, ___guidValue_0)); } inline String_t* get_guidValue_0() const { return ___guidValue_0; } inline String_t** get_address_of_guidValue_0() { return &___guidValue_0; } inline void set_guidValue_0(String_t* value) { ___guidValue_0 = value; Il2CppCodeGenWriteBarrier((&___guidValue_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GUIDATTRIBUTE_TFADD188D2E2B2BF32624D558D1E7D2A6086E35DB_H #ifndef INATTRIBUTE_T795BB5EC6BD74D2CF13BA1EAB6C112C98EB00E4D_H #define INATTRIBUTE_T795BB5EC6BD74D2CF13BA1EAB6C112C98EB00E4D_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.InAttribute struct InAttribute_t795BB5EC6BD74D2CF13BA1EAB6C112C98EB00E4D : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INATTRIBUTE_T795BB5EC6BD74D2CF13BA1EAB6C112C98EB00E4D_H #ifndef OPTIONALATTRIBUTE_T850203AA3F7B1FF849C1FA61A09BC84E448F800B_H #define OPTIONALATTRIBUTE_T850203AA3F7B1FF849C1FA61A09BC84E448F800B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.OptionalAttribute struct OptionalAttribute_t850203AA3F7B1FF849C1FA61A09BC84E448F800B : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OPTIONALATTRIBUTE_T850203AA3F7B1FF849C1FA61A09BC84E448F800B_H #ifndef OUTATTRIBUTE_T0ED5A1CE96E11A5BDBFC614869FFD423495F43EB_H #define OUTATTRIBUTE_T0ED5A1CE96E11A5BDBFC614869FFD423495F43EB_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.OutAttribute struct OutAttribute_t0ED5A1CE96E11A5BDBFC614869FFD423495F43EB : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OUTATTRIBUTE_T0ED5A1CE96E11A5BDBFC614869FFD423495F43EB_H #ifndef SBYTE_T50B643C59EE66E3364AED19D82E06B27BDE75268_H #define SBYTE_T50B643C59EE66E3364AED19D82E06B27BDE75268_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.SByte struct SByte_t50B643C59EE66E3364AED19D82E06B27BDE75268 { public: // System.SByte System.SByte::m_value int8_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(SByte_t50B643C59EE66E3364AED19D82E06B27BDE75268, ___m_value_0)); } inline int8_t get_m_value_0() const { return ___m_value_0; } inline int8_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int8_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SBYTE_T50B643C59EE66E3364AED19D82E06B27BDE75268_H #ifndef SECURITYATTRIBUTE_T532FD6D44D5E61D437F97ECCF7FD7DEFE265F0C5_H #define SECURITYATTRIBUTE_T532FD6D44D5E61D437F97ECCF7FD7DEFE265F0C5_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Permissions.SecurityAttribute struct SecurityAttribute_t532FD6D44D5E61D437F97ECCF7FD7DEFE265F0C5 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SECURITYATTRIBUTE_T532FD6D44D5E61D437F97ECCF7FD7DEFE265F0C5_H #ifndef SERIALIZABLEATTRIBUTE_T13B46ED74807ECB3679E003E93AF3A5559A8495C_H #define SERIALIZABLEATTRIBUTE_T13B46ED74807ECB3679E003E93AF3A5559A8495C_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.SerializableAttribute struct SerializableAttribute_t13B46ED74807ECB3679E003E93AF3A5559A8495C : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SERIALIZABLEATTRIBUTE_T13B46ED74807ECB3679E003E93AF3A5559A8495C_H #ifndef SINGLE_TF2613CF3F3AF0E8BEBC3CE8AD41479C44E6075DB_H #define SINGLE_TF2613CF3F3AF0E8BEBC3CE8AD41479C44E6075DB_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Single struct Single_tF2613CF3F3AF0E8BEBC3CE8AD41479C44E6075DB { public: // System.Single System.Single::m_value float ___m_value_7; public: inline static int32_t get_offset_of_m_value_7() { return static_cast<int32_t>(offsetof(Single_tF2613CF3F3AF0E8BEBC3CE8AD41479C44E6075DB, ___m_value_7)); } inline float get_m_value_7() const { return ___m_value_7; } inline float* get_address_of_m_value_7() { return &___m_value_7; } inline void set_m_value_7(float value) { ___m_value_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SINGLE_TF2613CF3F3AF0E8BEBC3CE8AD41479C44E6075DB_H #ifndef UINT16_T1FF1E02102FB09D5656DF30E5299DD359E497E9B_H #define UINT16_T1FF1E02102FB09D5656DF30E5299DD359E497E9B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UInt16 struct UInt16_t1FF1E02102FB09D5656DF30E5299DD359E497E9B { public: // System.UInt16 System.UInt16::m_value uint16_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(UInt16_t1FF1E02102FB09D5656DF30E5299DD359E497E9B, ___m_value_2)); } inline uint16_t get_m_value_2() const { return ___m_value_2; } inline uint16_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(uint16_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINT16_T1FF1E02102FB09D5656DF30E5299DD359E497E9B_H #ifndef UINT32_T69F92C53356907895162C7F31D87C59F9141D3B8_H #define UINT32_T69F92C53356907895162C7F31D87C59F9141D3B8_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UInt32 struct UInt32_t69F92C53356907895162C7F31D87C59F9141D3B8 { public: // System.UInt32 System.UInt32::m_value uint32_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(UInt32_t69F92C53356907895162C7F31D87C59F9141D3B8, ___m_value_2)); } inline uint32_t get_m_value_2() const { return ___m_value_2; } inline uint32_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(uint32_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINT32_T69F92C53356907895162C7F31D87C59F9141D3B8_H #ifndef UINT64_T9739CEA7F47A9C2DB5DDEAE34A1CE4B78AF8B29F_H #define UINT64_T9739CEA7F47A9C2DB5DDEAE34A1CE4B78AF8B29F_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UInt64 struct UInt64_t9739CEA7F47A9C2DB5DDEAE34A1CE4B78AF8B29F { public: // System.UInt64 System.UInt64::m_value uint64_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(UInt64_t9739CEA7F47A9C2DB5DDEAE34A1CE4B78AF8B29F, ___m_value_2)); } inline uint64_t get_m_value_2() const { return ___m_value_2; } inline uint64_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(uint64_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINT64_T9739CEA7F47A9C2DB5DDEAE34A1CE4B78AF8B29F_H #ifndef UINTPTR_T_H #define UINTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UIntPtr struct UIntPtr_t { public: // System.Void* System.UIntPtr::_pointer void* ____pointer_1; public: inline static int32_t get_offset_of__pointer_1() { return static_cast<int32_t>(offsetof(UIntPtr_t, ____pointer_1)); } inline void* get__pointer_1() const { return ____pointer_1; } inline void** get_address_of__pointer_1() { return &____pointer_1; } inline void set__pointer_1(void* value) { ____pointer_1 = value; } }; struct UIntPtr_t_StaticFields { public: // System.UIntPtr System.UIntPtr::Zero uintptr_t ___Zero_0; public: inline static int32_t get_offset_of_Zero_0() { return static_cast<int32_t>(offsetof(UIntPtr_t_StaticFields, ___Zero_0)); } inline uintptr_t get_Zero_0() const { return ___Zero_0; } inline uintptr_t* get_address_of_Zero_0() { return &___Zero_0; } inline void set_Zero_0(uintptr_t value) { ___Zero_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINTPTR_T_H #ifndef VOID_TDB81A15FA2AB53E2401A76B745D215397B29F783_H #define VOID_TDB81A15FA2AB53E2401A76B745D215397B29F783_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_tDB81A15FA2AB53E2401A76B745D215397B29F783 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_TDB81A15FA2AB53E2401A76B745D215397B29F783_H #ifndef ARGITERATOR_T91764B0E783C8EB1E5FCCA14A5116FE666DB0212_H #define ARGITERATOR_T91764B0E783C8EB1E5FCCA14A5116FE666DB0212_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ArgIterator struct ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212 { public: // System.IntPtr System.ArgIterator::sig intptr_t ___sig_0; // System.IntPtr System.ArgIterator::args intptr_t ___args_1; // System.Int32 System.ArgIterator::next_arg int32_t ___next_arg_2; // System.Int32 System.ArgIterator::num_args int32_t ___num_args_3; public: inline static int32_t get_offset_of_sig_0() { return static_cast<int32_t>(offsetof(ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212, ___sig_0)); } inline intptr_t get_sig_0() const { return ___sig_0; } inline intptr_t* get_address_of_sig_0() { return &___sig_0; } inline void set_sig_0(intptr_t value) { ___sig_0 = value; } inline static int32_t get_offset_of_args_1() { return static_cast<int32_t>(offsetof(ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212, ___args_1)); } inline intptr_t get_args_1() const { return ___args_1; } inline intptr_t* get_address_of_args_1() { return &___args_1; } inline void set_args_1(intptr_t value) { ___args_1 = value; } inline static int32_t get_offset_of_next_arg_2() { return static_cast<int32_t>(offsetof(ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212, ___next_arg_2)); } inline int32_t get_next_arg_2() const { return ___next_arg_2; } inline int32_t* get_address_of_next_arg_2() { return &___next_arg_2; } inline void set_next_arg_2(int32_t value) { ___next_arg_2 = value; } inline static int32_t get_offset_of_num_args_3() { return static_cast<int32_t>(offsetof(ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212, ___num_args_3)); } inline int32_t get_num_args_3() const { return ___num_args_3; } inline int32_t* get_address_of_num_args_3() { return &___num_args_3; } inline void set_num_args_3(int32_t value) { ___num_args_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARGITERATOR_T91764B0E783C8EB1E5FCCA14A5116FE666DB0212_H #ifndef ATTRIBUTETARGETS_T7D0C54BAF3C3182EC98698785E243961F7E4F51B_H #define ATTRIBUTETARGETS_T7D0C54BAF3C3182EC98698785E243961F7E4F51B_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.AttributeTargets struct AttributeTargets_t7D0C54BAF3C3182EC98698785E243961F7E4F51B { public: // System.Int32 System.AttributeTargets::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(AttributeTargets_t7D0C54BAF3C3182EC98698785E243961F7E4F51B, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTETARGETS_T7D0C54BAF3C3182EC98698785E243961F7E4F51B_H #ifndef DELEGATE_T_H #define DELEGATE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Delegate struct Delegate_t : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_5; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_6; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_7; // System.DelegateData System.Delegate::data DelegateData_tF588FE8D395F9A38FC7D222940F9B218441D21A9 * ___data_8; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((&___m_target_2), value); } inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_method_code_5() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_code_5)); } inline intptr_t get_method_code_5() const { return ___method_code_5; } inline intptr_t* get_address_of_method_code_5() { return &___method_code_5; } inline void set_method_code_5(intptr_t value) { ___method_code_5 = value; } inline static int32_t get_offset_of_method_info_6() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_info_6)); } inline MethodInfo_t * get_method_info_6() const { return ___method_info_6; } inline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; } inline void set_method_info_6(MethodInfo_t * value) { ___method_info_6 = value; Il2CppCodeGenWriteBarrier((&___method_info_6), value); } inline static int32_t get_offset_of_original_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t, ___original_method_info_7)); } inline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; } inline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; } inline void set_original_method_info_7(MethodInfo_t * value) { ___original_method_info_7 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_7), value); } inline static int32_t get_offset_of_data_8() { return static_cast<int32_t>(offsetof(Delegate_t, ___data_8)); } inline DelegateData_tF588FE8D395F9A38FC7D222940F9B218441D21A9 * get_data_8() const { return ___data_8; } inline DelegateData_tF588FE8D395F9A38FC7D222940F9B218441D21A9 ** get_address_of_data_8() { return &___data_8; } inline void set_data_8(DelegateData_tF588FE8D395F9A38FC7D222940F9B218441D21A9 * value) { ___data_8 = value; Il2CppCodeGenWriteBarrier((&___data_8), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DELEGATE_T_H #ifndef MONODOCUMENTATIONNOTEATTRIBUTE_T3A046DD4447EB8D0E57187CBF5DEE1D02F1A24CF_H #define MONODOCUMENTATIONNOTEATTRIBUTE_T3A046DD4447EB8D0E57187CBF5DEE1D02F1A24CF_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MonoDocumentationNoteAttribute struct MonoDocumentationNoteAttribute_t3A046DD4447EB8D0E57187CBF5DEE1D02F1A24CF : public MonoTODOAttribute_tC3BFF62878CE5A141978F4C91C28CFE340F3BB45 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MONODOCUMENTATIONNOTEATTRIBUTE_T3A046DD4447EB8D0E57187CBF5DEE1D02F1A24CF_H #ifndef MONOLIMITATIONATTRIBUTE_TD26F08333B27ADCAA36FD8328FFFF04FE9C103B2_H #define MONOLIMITATIONATTRIBUTE_TD26F08333B27ADCAA36FD8328FFFF04FE9C103B2_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MonoLimitationAttribute struct MonoLimitationAttribute_tD26F08333B27ADCAA36FD8328FFFF04FE9C103B2 : public MonoTODOAttribute_tC3BFF62878CE5A141978F4C91C28CFE340F3BB45 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MONOLIMITATIONATTRIBUTE_TD26F08333B27ADCAA36FD8328FFFF04FE9C103B2_H #ifndef BINDINGFLAGS_T7FD4941D9115FF77D5F573F63A93BFBC5D1F63B2_H #define BINDINGFLAGS_T7FD4941D9115FF77D5F573F63A93BFBC5D1F63B2_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.BindingFlags struct BindingFlags_t7FD4941D9115FF77D5F573F63A93BFBC5D1F63B2 { public: // System.Int32 System.Reflection.BindingFlags::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(BindingFlags_t7FD4941D9115FF77D5F573F63A93BFBC5D1F63B2, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BINDINGFLAGS_T7FD4941D9115FF77D5F573F63A93BFBC5D1F63B2_H #ifndef CALLINGCONVENTION_T3A3DF68FFC5A99C4FCC454929C971ECCE54F308F_H #define CALLINGCONVENTION_T3A3DF68FFC5A99C4FCC454929C971ECCE54F308F_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.CallingConvention struct CallingConvention_t3A3DF68FFC5A99C4FCC454929C971ECCE54F308F { public: // System.Int32 System.Runtime.InteropServices.CallingConvention::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(CallingConvention_t3A3DF68FFC5A99C4FCC454929C971ECCE54F308F, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CALLINGCONVENTION_T3A3DF68FFC5A99C4FCC454929C971ECCE54F308F_H #ifndef CHARSET_T556634D7FC86416457716D4CE636577024DF3C05_H #define CHARSET_T556634D7FC86416457716D4CE636577024DF3C05_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.CharSet struct CharSet_t556634D7FC86416457716D4CE636577024DF3C05 { public: // System.Int32 System.Runtime.InteropServices.CharSet::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(CharSet_t556634D7FC86416457716D4CE636577024DF3C05, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CHARSET_T556634D7FC86416457716D4CE636577024DF3C05_H #ifndef SAFEHANDLE_TF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80_H #define SAFEHANDLE_TF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.SafeHandle struct SafeHandle_tF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80 : public CriticalFinalizerObject_tEF12E2D0ADC15894681402455E99775943930F94 { public: // System.IntPtr System.Runtime.InteropServices.SafeHandle::handle intptr_t ___handle_0; // System.IntPtr System.Runtime.InteropServices.SafeHandle::invalid_handle_value intptr_t ___invalid_handle_value_1; // System.Int32 System.Runtime.InteropServices.SafeHandle::refcount int32_t ___refcount_2; // System.Boolean System.Runtime.InteropServices.SafeHandle::owns_handle bool ___owns_handle_3; public: inline static int32_t get_offset_of_handle_0() { return static_cast<int32_t>(offsetof(SafeHandle_tF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80, ___handle_0)); } inline intptr_t get_handle_0() const { return ___handle_0; } inline intptr_t* get_address_of_handle_0() { return &___handle_0; } inline void set_handle_0(intptr_t value) { ___handle_0 = value; } inline static int32_t get_offset_of_invalid_handle_value_1() { return static_cast<int32_t>(offsetof(SafeHandle_tF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80, ___invalid_handle_value_1)); } inline intptr_t get_invalid_handle_value_1() const { return ___invalid_handle_value_1; } inline intptr_t* get_address_of_invalid_handle_value_1() { return &___invalid_handle_value_1; } inline void set_invalid_handle_value_1(intptr_t value) { ___invalid_handle_value_1 = value; } inline static int32_t get_offset_of_refcount_2() { return static_cast<int32_t>(offsetof(SafeHandle_tF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80, ___refcount_2)); } inline int32_t get_refcount_2() const { return ___refcount_2; } inline int32_t* get_address_of_refcount_2() { return &___refcount_2; } inline void set_refcount_2(int32_t value) { ___refcount_2 = value; } inline static int32_t get_offset_of_owns_handle_3() { return static_cast<int32_t>(offsetof(SafeHandle_tF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80, ___owns_handle_3)); } inline bool get_owns_handle_3() const { return ___owns_handle_3; } inline bool* get_address_of_owns_handle_3() { return &___owns_handle_3; } inline void set_owns_handle_3(bool value) { ___owns_handle_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SAFEHANDLE_TF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80_H #ifndef UNMANAGEDTYPE_TC31C30B1390F19DEE2F6923A2480968D7B2B8193_H #define UNMANAGEDTYPE_TC31C30B1390F19DEE2F6923A2480968D7B2B8193_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.UnmanagedType struct UnmanagedType_tC31C30B1390F19DEE2F6923A2480968D7B2B8193 { public: // System.Int32 System.Runtime.InteropServices.UnmanagedType::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(UnmanagedType_tC31C30B1390F19DEE2F6923A2480968D7B2B8193, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNMANAGEDTYPE_TC31C30B1390F19DEE2F6923A2480968D7B2B8193_H #ifndef RUNTIMEARGUMENTHANDLE_TB0C3CDFC95F9CF95BE76B9B155D2AE12EA4ACF49_H #define RUNTIMEARGUMENTHANDLE_TB0C3CDFC95F9CF95BE76B9B155D2AE12EA4ACF49_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.RuntimeArgumentHandle struct RuntimeArgumentHandle_tB0C3CDFC95F9CF95BE76B9B155D2AE12EA4ACF49 { public: // System.IntPtr System.RuntimeArgumentHandle::args intptr_t ___args_0; public: inline static int32_t get_offset_of_args_0() { return static_cast<int32_t>(offsetof(RuntimeArgumentHandle_tB0C3CDFC95F9CF95BE76B9B155D2AE12EA4ACF49, ___args_0)); } inline intptr_t get_args_0() const { return ___args_0; } inline intptr_t* get_address_of_args_0() { return &___args_0; } inline void set_args_0(intptr_t value) { ___args_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEARGUMENTHANDLE_TB0C3CDFC95F9CF95BE76B9B155D2AE12EA4ACF49_H #ifndef RUNTIMEFIELDHANDLE_TDDEB9F6EC2C3875C313750A5C3C33488A2F7A703_H #define RUNTIMEFIELDHANDLE_TDDEB9F6EC2C3875C313750A5C3C33488A2F7A703_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.RuntimeFieldHandle struct RuntimeFieldHandle_tDDEB9F6EC2C3875C313750A5C3C33488A2F7A703 { public: // System.IntPtr System.RuntimeFieldHandle::value intptr_t ___value_0; public: inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(RuntimeFieldHandle_tDDEB9F6EC2C3875C313750A5C3C33488A2F7A703, ___value_0)); } inline intptr_t get_value_0() const { return ___value_0; } inline intptr_t* get_address_of_value_0() { return &___value_0; } inline void set_value_0(intptr_t value) { ___value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEFIELDHANDLE_TDDEB9F6EC2C3875C313750A5C3C33488A2F7A703_H #ifndef RUNTIMETYPEHANDLE_T58BB862EF56F46A9518F8ACA413EF7D70238F1AD_H #define RUNTIMETYPEHANDLE_T58BB862EF56F46A9518F8ACA413EF7D70238F1AD_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.RuntimeTypeHandle struct RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD { public: // System.IntPtr System.RuntimeTypeHandle::value intptr_t ___value_0; public: inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD, ___value_0)); } inline intptr_t get_value_0() const { return ___value_0; } inline intptr_t* get_address_of_value_0() { return &___value_0; } inline void set_value_0(intptr_t value) { ___value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMETYPEHANDLE_T58BB862EF56F46A9518F8ACA413EF7D70238F1AD_H #ifndef SAFEHANDLEZEROORMINUSONEISINVALID_TFB69962935CA6B88F4DB0AC72A19642AE5A01C1F_H #define SAFEHANDLEZEROORMINUSONEISINVALID_TFB69962935CA6B88F4DB0AC72A19642AE5A01C1F_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid struct SafeHandleZeroOrMinusOneIsInvalid_tFB69962935CA6B88F4DB0AC72A19642AE5A01C1F : public SafeHandle_tF51E0A75D122DB2E4FE6C839CC575ACBE3FCFB80 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SAFEHANDLEZEROORMINUSONEISINVALID_TFB69962935CA6B88F4DB0AC72A19642AE5A01C1F_H #ifndef ATTRIBUTEUSAGEATTRIBUTE_TDF795451BD27F671AEEC8DFD772C3344DC1149F2_H #define ATTRIBUTEUSAGEATTRIBUTE_TDF795451BD27F671AEEC8DFD772C3344DC1149F2_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.AttributeUsageAttribute struct AttributeUsageAttribute_tDF795451BD27F671AEEC8DFD772C3344DC1149F2 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.AttributeTargets System.AttributeUsageAttribute::valid_on int32_t ___valid_on_0; // System.Boolean System.AttributeUsageAttribute::allow_multiple bool ___allow_multiple_1; // System.Boolean System.AttributeUsageAttribute::inherited bool ___inherited_2; public: inline static int32_t get_offset_of_valid_on_0() { return static_cast<int32_t>(offsetof(AttributeUsageAttribute_tDF795451BD27F671AEEC8DFD772C3344DC1149F2, ___valid_on_0)); } inline int32_t get_valid_on_0() const { return ___valid_on_0; } inline int32_t* get_address_of_valid_on_0() { return &___valid_on_0; } inline void set_valid_on_0(int32_t value) { ___valid_on_0 = value; } inline static int32_t get_offset_of_allow_multiple_1() { return static_cast<int32_t>(offsetof(AttributeUsageAttribute_tDF795451BD27F671AEEC8DFD772C3344DC1149F2, ___allow_multiple_1)); } inline bool get_allow_multiple_1() const { return ___allow_multiple_1; } inline bool* get_address_of_allow_multiple_1() { return &___allow_multiple_1; } inline void set_allow_multiple_1(bool value) { ___allow_multiple_1 = value; } inline static int32_t get_offset_of_inherited_2() { return static_cast<int32_t>(offsetof(AttributeUsageAttribute_tDF795451BD27F671AEEC8DFD772C3344DC1149F2, ___inherited_2)); } inline bool get_inherited_2() const { return ___inherited_2; } inline bool* get_address_of_inherited_2() { return &___inherited_2; } inline void set_inherited_2(bool value) { ___inherited_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTEUSAGEATTRIBUTE_TDF795451BD27F671AEEC8DFD772C3344DC1149F2_H #ifndef MULTICASTDELEGATE_T_H #define MULTICASTDELEGATE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MulticastDelegate struct MulticastDelegate_t : public Delegate_t { public: // System.MulticastDelegate System.MulticastDelegate::prev MulticastDelegate_t * ___prev_9; // System.MulticastDelegate System.MulticastDelegate::kpm_next MulticastDelegate_t * ___kpm_next_10; public: inline static int32_t get_offset_of_prev_9() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___prev_9)); } inline MulticastDelegate_t * get_prev_9() const { return ___prev_9; } inline MulticastDelegate_t ** get_address_of_prev_9() { return &___prev_9; } inline void set_prev_9(MulticastDelegate_t * value) { ___prev_9 = value; Il2CppCodeGenWriteBarrier((&___prev_9), value); } inline static int32_t get_offset_of_kpm_next_10() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___kpm_next_10)); } inline MulticastDelegate_t * get_kpm_next_10() const { return ___kpm_next_10; } inline MulticastDelegate_t ** get_address_of_kpm_next_10() { return &___kpm_next_10; } inline void set_kpm_next_10(MulticastDelegate_t * value) { ___kpm_next_10 = value; Il2CppCodeGenWriteBarrier((&___kpm_next_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MULTICASTDELEGATE_T_H #ifndef DLLIMPORTATTRIBUTE_T213D4F3B8CF912A021E83C034835112608EAC265_H #define DLLIMPORTATTRIBUTE_T213D4F3B8CF912A021E83C034835112608EAC265_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.DllImportAttribute struct DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265 : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.Runtime.InteropServices.CallingConvention System.Runtime.InteropServices.DllImportAttribute::CallingConvention int32_t ___CallingConvention_0; // System.Runtime.InteropServices.CharSet System.Runtime.InteropServices.DllImportAttribute::CharSet int32_t ___CharSet_1; // System.String System.Runtime.InteropServices.DllImportAttribute::Dll String_t* ___Dll_2; // System.String System.Runtime.InteropServices.DllImportAttribute::EntryPoint String_t* ___EntryPoint_3; // System.Boolean System.Runtime.InteropServices.DllImportAttribute::ExactSpelling bool ___ExactSpelling_4; // System.Boolean System.Runtime.InteropServices.DllImportAttribute::PreserveSig bool ___PreserveSig_5; // System.Boolean System.Runtime.InteropServices.DllImportAttribute::SetLastError bool ___SetLastError_6; // System.Boolean System.Runtime.InteropServices.DllImportAttribute::BestFitMapping bool ___BestFitMapping_7; // System.Boolean System.Runtime.InteropServices.DllImportAttribute::ThrowOnUnmappableChar bool ___ThrowOnUnmappableChar_8; public: inline static int32_t get_offset_of_CallingConvention_0() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___CallingConvention_0)); } inline int32_t get_CallingConvention_0() const { return ___CallingConvention_0; } inline int32_t* get_address_of_CallingConvention_0() { return &___CallingConvention_0; } inline void set_CallingConvention_0(int32_t value) { ___CallingConvention_0 = value; } inline static int32_t get_offset_of_CharSet_1() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___CharSet_1)); } inline int32_t get_CharSet_1() const { return ___CharSet_1; } inline int32_t* get_address_of_CharSet_1() { return &___CharSet_1; } inline void set_CharSet_1(int32_t value) { ___CharSet_1 = value; } inline static int32_t get_offset_of_Dll_2() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___Dll_2)); } inline String_t* get_Dll_2() const { return ___Dll_2; } inline String_t** get_address_of_Dll_2() { return &___Dll_2; } inline void set_Dll_2(String_t* value) { ___Dll_2 = value; Il2CppCodeGenWriteBarrier((&___Dll_2), value); } inline static int32_t get_offset_of_EntryPoint_3() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___EntryPoint_3)); } inline String_t* get_EntryPoint_3() const { return ___EntryPoint_3; } inline String_t** get_address_of_EntryPoint_3() { return &___EntryPoint_3; } inline void set_EntryPoint_3(String_t* value) { ___EntryPoint_3 = value; Il2CppCodeGenWriteBarrier((&___EntryPoint_3), value); } inline static int32_t get_offset_of_ExactSpelling_4() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___ExactSpelling_4)); } inline bool get_ExactSpelling_4() const { return ___ExactSpelling_4; } inline bool* get_address_of_ExactSpelling_4() { return &___ExactSpelling_4; } inline void set_ExactSpelling_4(bool value) { ___ExactSpelling_4 = value; } inline static int32_t get_offset_of_PreserveSig_5() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___PreserveSig_5)); } inline bool get_PreserveSig_5() const { return ___PreserveSig_5; } inline bool* get_address_of_PreserveSig_5() { return &___PreserveSig_5; } inline void set_PreserveSig_5(bool value) { ___PreserveSig_5 = value; } inline static int32_t get_offset_of_SetLastError_6() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___SetLastError_6)); } inline bool get_SetLastError_6() const { return ___SetLastError_6; } inline bool* get_address_of_SetLastError_6() { return &___SetLastError_6; } inline void set_SetLastError_6(bool value) { ___SetLastError_6 = value; } inline static int32_t get_offset_of_BestFitMapping_7() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___BestFitMapping_7)); } inline bool get_BestFitMapping_7() const { return ___BestFitMapping_7; } inline bool* get_address_of_BestFitMapping_7() { return &___BestFitMapping_7; } inline void set_BestFitMapping_7(bool value) { ___BestFitMapping_7 = value; } inline static int32_t get_offset_of_ThrowOnUnmappableChar_8() { return static_cast<int32_t>(offsetof(DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265, ___ThrowOnUnmappableChar_8)); } inline bool get_ThrowOnUnmappableChar_8() const { return ___ThrowOnUnmappableChar_8; } inline bool* get_address_of_ThrowOnUnmappableChar_8() { return &___ThrowOnUnmappableChar_8; } inline void set_ThrowOnUnmappableChar_8(bool value) { ___ThrowOnUnmappableChar_8 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DLLIMPORTATTRIBUTE_T213D4F3B8CF912A021E83C034835112608EAC265_H #ifndef MARSHALASATTRIBUTE_TFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE_H #define MARSHALASATTRIBUTE_TFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.MarshalAsAttribute struct MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE : public Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469 { public: // System.Runtime.InteropServices.UnmanagedType System.Runtime.InteropServices.MarshalAsAttribute::utype int32_t ___utype_0; // System.Runtime.InteropServices.UnmanagedType System.Runtime.InteropServices.MarshalAsAttribute::ArraySubType int32_t ___ArraySubType_1; // System.String System.Runtime.InteropServices.MarshalAsAttribute::MarshalCookie String_t* ___MarshalCookie_2; // System.String System.Runtime.InteropServices.MarshalAsAttribute::MarshalType String_t* ___MarshalType_3; // System.Type System.Runtime.InteropServices.MarshalAsAttribute::MarshalTypeRef Type_t * ___MarshalTypeRef_4; // System.Int32 System.Runtime.InteropServices.MarshalAsAttribute::SizeConst int32_t ___SizeConst_5; // System.Int16 System.Runtime.InteropServices.MarshalAsAttribute::SizeParamIndex int16_t ___SizeParamIndex_6; public: inline static int32_t get_offset_of_utype_0() { return static_cast<int32_t>(offsetof(MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE, ___utype_0)); } inline int32_t get_utype_0() const { return ___utype_0; } inline int32_t* get_address_of_utype_0() { return &___utype_0; } inline void set_utype_0(int32_t value) { ___utype_0 = value; } inline static int32_t get_offset_of_ArraySubType_1() { return static_cast<int32_t>(offsetof(MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE, ___ArraySubType_1)); } inline int32_t get_ArraySubType_1() const { return ___ArraySubType_1; } inline int32_t* get_address_of_ArraySubType_1() { return &___ArraySubType_1; } inline void set_ArraySubType_1(int32_t value) { ___ArraySubType_1 = value; } inline static int32_t get_offset_of_MarshalCookie_2() { return static_cast<int32_t>(offsetof(MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE, ___MarshalCookie_2)); } inline String_t* get_MarshalCookie_2() const { return ___MarshalCookie_2; } inline String_t** get_address_of_MarshalCookie_2() { return &___MarshalCookie_2; } inline void set_MarshalCookie_2(String_t* value) { ___MarshalCookie_2 = value; Il2CppCodeGenWriteBarrier((&___MarshalCookie_2), value); } inline static int32_t get_offset_of_MarshalType_3() { return static_cast<int32_t>(offsetof(MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE, ___MarshalType_3)); } inline String_t* get_MarshalType_3() const { return ___MarshalType_3; } inline String_t** get_address_of_MarshalType_3() { return &___MarshalType_3; } inline void set_MarshalType_3(String_t* value) { ___MarshalType_3 = value; Il2CppCodeGenWriteBarrier((&___MarshalType_3), value); } inline static int32_t get_offset_of_MarshalTypeRef_4() { return static_cast<int32_t>(offsetof(MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE, ___MarshalTypeRef_4)); } inline Type_t * get_MarshalTypeRef_4() const { return ___MarshalTypeRef_4; } inline Type_t ** get_address_of_MarshalTypeRef_4() { return &___MarshalTypeRef_4; } inline void set_MarshalTypeRef_4(Type_t * value) { ___MarshalTypeRef_4 = value; Il2CppCodeGenWriteBarrier((&___MarshalTypeRef_4), value); } inline static int32_t get_offset_of_SizeConst_5() { return static_cast<int32_t>(offsetof(MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE, ___SizeConst_5)); } inline int32_t get_SizeConst_5() const { return ___SizeConst_5; } inline int32_t* get_address_of_SizeConst_5() { return &___SizeConst_5; } inline void set_SizeConst_5(int32_t value) { ___SizeConst_5 = value; } inline static int32_t get_offset_of_SizeParamIndex_6() { return static_cast<int32_t>(offsetof(MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE, ___SizeParamIndex_6)); } inline int16_t get_SizeParamIndex_6() const { return ___SizeParamIndex_6; } inline int16_t* get_address_of_SizeParamIndex_6() { return &___SizeParamIndex_6; } inline void set_SizeParamIndex_6(int16_t value) { ___SizeParamIndex_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MARSHALASATTRIBUTE_TFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE_H #ifndef TYPE_T_H #define TYPE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Type struct Type_t : public MemberInfo_t { public: // System.RuntimeTypeHandle System.Type::_impl RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD ____impl_1; public: inline static int32_t get_offset_of__impl_1() { return static_cast<int32_t>(offsetof(Type_t, ____impl_1)); } inline RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD get__impl_1() const { return ____impl_1; } inline RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD * get_address_of__impl_1() { return &____impl_1; } inline void set__impl_1(RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD value) { ____impl_1 = value; } }; struct Type_t_StaticFields { public: // System.Char System.Type::Delimiter Il2CppChar ___Delimiter_2; // System.Type[] System.Type::EmptyTypes TypeU5BU5D_tEF927658123F6CD4274B971442504A42AB6DE532* ___EmptyTypes_3; // System.Reflection.MemberFilter System.Type::FilterAttribute MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * ___FilterAttribute_4; // System.Reflection.MemberFilter System.Type::FilterName MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * ___FilterName_5; // System.Reflection.MemberFilter System.Type::FilterNameIgnoreCase MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * ___FilterNameIgnoreCase_6; // System.Object System.Type::Missing RuntimeObject * ___Missing_7; public: inline static int32_t get_offset_of_Delimiter_2() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Delimiter_2)); } inline Il2CppChar get_Delimiter_2() const { return ___Delimiter_2; } inline Il2CppChar* get_address_of_Delimiter_2() { return &___Delimiter_2; } inline void set_Delimiter_2(Il2CppChar value) { ___Delimiter_2 = value; } inline static int32_t get_offset_of_EmptyTypes_3() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___EmptyTypes_3)); } inline TypeU5BU5D_tEF927658123F6CD4274B971442504A42AB6DE532* get_EmptyTypes_3() const { return ___EmptyTypes_3; } inline TypeU5BU5D_tEF927658123F6CD4274B971442504A42AB6DE532** get_address_of_EmptyTypes_3() { return &___EmptyTypes_3; } inline void set_EmptyTypes_3(TypeU5BU5D_tEF927658123F6CD4274B971442504A42AB6DE532* value) { ___EmptyTypes_3 = value; Il2CppCodeGenWriteBarrier((&___EmptyTypes_3), value); } inline static int32_t get_offset_of_FilterAttribute_4() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterAttribute_4)); } inline MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * get_FilterAttribute_4() const { return ___FilterAttribute_4; } inline MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE ** get_address_of_FilterAttribute_4() { return &___FilterAttribute_4; } inline void set_FilterAttribute_4(MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * value) { ___FilterAttribute_4 = value; Il2CppCodeGenWriteBarrier((&___FilterAttribute_4), value); } inline static int32_t get_offset_of_FilterName_5() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterName_5)); } inline MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * get_FilterName_5() const { return ___FilterName_5; } inline MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE ** get_address_of_FilterName_5() { return &___FilterName_5; } inline void set_FilterName_5(MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * value) { ___FilterName_5 = value; Il2CppCodeGenWriteBarrier((&___FilterName_5), value); } inline static int32_t get_offset_of_FilterNameIgnoreCase_6() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterNameIgnoreCase_6)); } inline MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * get_FilterNameIgnoreCase_6() const { return ___FilterNameIgnoreCase_6; } inline MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE ** get_address_of_FilterNameIgnoreCase_6() { return &___FilterNameIgnoreCase_6; } inline void set_FilterNameIgnoreCase_6(MemberFilter_t0471813A7FF5255D21A8EA144C5CCF3325274CDE * value) { ___FilterNameIgnoreCase_6 = value; Il2CppCodeGenWriteBarrier((&___FilterNameIgnoreCase_6), value); } inline static int32_t get_offset_of_Missing_7() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Missing_7)); } inline RuntimeObject * get_Missing_7() const { return ___Missing_7; } inline RuntimeObject ** get_address_of_Missing_7() { return &___Missing_7; } inline void set_Missing_7(RuntimeObject * value) { ___Missing_7 = value; Il2CppCodeGenWriteBarrier((&___Missing_7), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TYPE_T_H #ifndef TYPEDREFERENCE_T6C50501B536C0B63B481CF84F67719D9B94D3593_H #define TYPEDREFERENCE_T6C50501B536C0B63B481CF84F67719D9B94D3593_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.TypedReference struct TypedReference_t6C50501B536C0B63B481CF84F67719D9B94D3593 { public: // System.RuntimeTypeHandle System.TypedReference::type RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD ___type_0; // System.IntPtr System.TypedReference::value intptr_t ___value_1; // System.IntPtr System.TypedReference::klass intptr_t ___klass_2; public: inline static int32_t get_offset_of_type_0() { return static_cast<int32_t>(offsetof(TypedReference_t6C50501B536C0B63B481CF84F67719D9B94D3593, ___type_0)); } inline RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD get_type_0() const { return ___type_0; } inline RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD * get_address_of_type_0() { return &___type_0; } inline void set_type_0(RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD value) { ___type_0 = value; } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(TypedReference_t6C50501B536C0B63B481CF84F67719D9B94D3593, ___value_1)); } inline intptr_t get_value_1() const { return ___value_1; } inline intptr_t* get_address_of_value_1() { return &___value_1; } inline void set_value_1(intptr_t value) { ___value_1 = value; } inline static int32_t get_offset_of_klass_2() { return static_cast<int32_t>(offsetof(TypedReference_t6C50501B536C0B63B481CF84F67719D9B94D3593, ___klass_2)); } inline intptr_t get_klass_2() const { return ___klass_2; } inline intptr_t* get_address_of_klass_2() { return &___klass_2; } inline void set_klass_2(intptr_t value) { ___klass_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TYPEDREFERENCE_T6C50501B536C0B63B481CF84F67719D9B94D3593_H #ifndef SAFEWAITHANDLE_T40C8EF13EE28AED31D814C26B860551E8962BEBE_H #define SAFEWAITHANDLE_T40C8EF13EE28AED31D814C26B860551E8962BEBE_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Microsoft.Win32.SafeHandles.SafeWaitHandle struct SafeWaitHandle_t40C8EF13EE28AED31D814C26B860551E8962BEBE : public SafeHandleZeroOrMinusOneIsInvalid_tFB69962935CA6B88F4DB0AC72A19642AE5A01C1F { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SAFEWAITHANDLE_T40C8EF13EE28AED31D814C26B860551E8962BEBE_H #ifndef SWAPPER_T9F2C0D39670373AAE7E9AE52A834E0ED2D92C23F_H #define SWAPPER_T9F2C0D39670373AAE7E9AE52A834E0ED2D92C23F_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array_Swapper struct Swapper_t9F2C0D39670373AAE7E9AE52A834E0ED2D92C23F : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SWAPPER_T9F2C0D39670373AAE7E9AE52A834E0ED2D92C23F_H #ifndef ASYNCCALLBACK_T74ABD1277F711E7FBDCB00E169A63DEFD39E86A2_H #define ASYNCCALLBACK_T74ABD1277F711E7FBDCB00E169A63DEFD39E86A2_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.AsyncCallback struct AsyncCallback_t74ABD1277F711E7FBDCB00E169A63DEFD39E86A2 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASYNCCALLBACK_T74ABD1277F711E7FBDCB00E169A63DEFD39E86A2_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize0 = { sizeof (U3CModuleU3E_tD1EF7EA122A0D4C77CC334676127E2D8CF50824D), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize1 = { sizeof (RuntimeObject), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2 = { sizeof (ValueType_t1810BD84E0FDB5D3A7CD34286A5B22F343995C9C), sizeof(ValueType_t1810BD84E0FDB5D3A7CD34286A5B22F343995C9C_marshaled_pinvoke), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3 = { sizeof (Attribute_t60F25EB48D5935E4C6C2BAF7F90F57A43528E469), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize4 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize5 = { sizeof (Int32_tC16F64335CE8B56D99229DE94BB3A876ED55FE87)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable5[3] = { 0, 0, Int32_tC16F64335CE8B56D99229DE94BB3A876ED55FE87::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize6 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize7 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize8 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize9 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize10 = { sizeof (SerializableAttribute_t13B46ED74807ECB3679E003E93AF3A5559A8495C), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize11 = { sizeof (AttributeUsageAttribute_tDF795451BD27F671AEEC8DFD772C3344DC1149F2), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable11[3] = { AttributeUsageAttribute_tDF795451BD27F671AEEC8DFD772C3344DC1149F2::get_offset_of_valid_on_0(), AttributeUsageAttribute_tDF795451BD27F671AEEC8DFD772C3344DC1149F2::get_offset_of_allow_multiple_1(), AttributeUsageAttribute_tDF795451BD27F671AEEC8DFD772C3344DC1149F2::get_offset_of_inherited_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize12 = { sizeof (ComVisibleAttribute_t0B3C80B1CF94B29B53B75A802635D11303B1EFE5), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable12[1] = { ComVisibleAttribute_t0B3C80B1CF94B29B53B75A802635D11303B1EFE5::get_offset_of_Visible_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize13 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize14 = { sizeof (Int64_tF61270729FC90F8A705A5FA6FE222C9644374ADF)+ sizeof (RuntimeObject), sizeof(int64_t), 0, 0 }; extern const int32_t g_FieldOffsetTable14[3] = { 0, 0, Int64_tF61270729FC90F8A705A5FA6FE222C9644374ADF::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize15 = { sizeof (UInt32_t69F92C53356907895162C7F31D87C59F9141D3B8)+ sizeof (RuntimeObject), sizeof(uint32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable15[3] = { 0, 0, UInt32_t69F92C53356907895162C7F31D87C59F9141D3B8::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize16 = { sizeof (CLSCompliantAttribute_t161163A690EF51165D83B0C3F0FE5E69662722C3), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable16[1] = { CLSCompliantAttribute_t161163A690EF51165D83B0C3F0FE5E69662722C3::get_offset_of_is_compliant_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize17 = { sizeof (UInt64_t9739CEA7F47A9C2DB5DDEAE34A1CE4B78AF8B29F)+ sizeof (RuntimeObject), sizeof(uint64_t), 0, 0 }; extern const int32_t g_FieldOffsetTable17[3] = { 0, 0, UInt64_t9739CEA7F47A9C2DB5DDEAE34A1CE4B78AF8B29F::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize18 = { sizeof (Byte_t4C3393E6E7EAD06B53234C05564190D9A2D7B149)+ sizeof (RuntimeObject), sizeof(uint8_t), 0, 0 }; extern const int32_t g_FieldOffsetTable18[3] = { 0, 0, Byte_t4C3393E6E7EAD06B53234C05564190D9A2D7B149::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize19 = { sizeof (SByte_t50B643C59EE66E3364AED19D82E06B27BDE75268)+ sizeof (RuntimeObject), sizeof(int8_t), 0, 0 }; extern const int32_t g_FieldOffsetTable19[1] = { SByte_t50B643C59EE66E3364AED19D82E06B27BDE75268::get_offset_of_m_value_0() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize20 = { sizeof (Int16_tBFC41132AB8E6B4E1F9D4A1E3CC46422BF453F3C)+ sizeof (RuntimeObject), sizeof(int16_t), 0, 0 }; extern const int32_t g_FieldOffsetTable20[3] = { 0, 0, Int16_tBFC41132AB8E6B4E1F9D4A1E3CC46422BF453F3C::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize21 = { sizeof (UInt16_t1FF1E02102FB09D5656DF30E5299DD359E497E9B)+ sizeof (RuntimeObject), sizeof(uint16_t), 0, 0 }; extern const int32_t g_FieldOffsetTable21[3] = { 0, 0, UInt16_t1FF1E02102FB09D5656DF30E5299DD359E497E9B::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize22 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize23 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize24 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize25 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize26 = { sizeof (Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432)+ sizeof (RuntimeObject), 1, sizeof(Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable26[10] = { 0, 0, Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields::get_offset_of_category_data_3(), Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields::get_offset_of_numeric_data_4(), Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields::get_offset_of_numeric_data_values_5(), Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields::get_offset_of_to_lower_data_low_6(), Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields::get_offset_of_to_lower_data_high_7(), Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields::get_offset_of_to_upper_data_low_8(), Char_t2AF4E0DF8B57497BF49A6A8822F574113ADA8432_StaticFields::get_offset_of_to_upper_data_high_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize27 = { sizeof (String_t), sizeof(char*), sizeof(String_t_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable27[4] = { String_t::get_offset_of_length_0(), String_t::get_offset_of_start_char_1(), String_t_StaticFields::get_offset_of_Empty_2(), String_t_StaticFields::get_offset_of_WhiteChars_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize28 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize29 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize30 = { sizeof (Single_tF2613CF3F3AF0E8BEBC3CE8AD41479C44E6075DB)+ sizeof (RuntimeObject), sizeof(float), 0, 0 }; extern const int32_t g_FieldOffsetTable30[8] = { 0, 0, 0, 0, 0, 0, 0, Single_tF2613CF3F3AF0E8BEBC3CE8AD41479C44E6075DB::get_offset_of_m_value_7() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize31 = { sizeof (Double_t2011D65DAF7D1FCBE71DD4CBDFA69A8F24643159)+ sizeof (RuntimeObject), sizeof(double), 0, 0 }; extern const int32_t g_FieldOffsetTable31[14] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Double_t2011D65DAF7D1FCBE71DD4CBDFA69A8F24643159::get_offset_of_m_value_13() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize32 = { sizeof (Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3)+ sizeof (RuntimeObject), sizeof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3 ), sizeof(Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable32[9] = { Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields::get_offset_of_MinValue_0(), Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields::get_offset_of_MaxValue_1(), Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields::get_offset_of_MinusOne_2(), Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields::get_offset_of_One_3(), Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3_StaticFields::get_offset_of_MaxValueDiv10_4(), Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3::get_offset_of_flags_5() + static_cast<int32_t>(sizeof(RuntimeObject)), Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3::get_offset_of_hi_6() + static_cast<int32_t>(sizeof(RuntimeObject)), Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3::get_offset_of_lo_7() + static_cast<int32_t>(sizeof(RuntimeObject)), Decimal_t46BBDD161320E361BC57E00CD6C1F87256CA27F3::get_offset_of_mid_8() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize33 = { sizeof (Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF)+ sizeof (RuntimeObject), 4, sizeof(Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable33[3] = { Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF_StaticFields::get_offset_of_FalseString_0(), Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF_StaticFields::get_offset_of_TrueString_1(), Boolean_t92E4792324DA9B716F339A3B965A14965E99A4EF::get_offset_of_m_value_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize34 = { sizeof (IntPtr_t)+ sizeof (RuntimeObject), sizeof(intptr_t), sizeof(IntPtr_t_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable34[2] = { IntPtr_t::get_offset_of_m_value_0() + static_cast<int32_t>(sizeof(RuntimeObject)), IntPtr_t_StaticFields::get_offset_of_Zero_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize35 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize36 = { sizeof (UIntPtr_t)+ sizeof (RuntimeObject), sizeof(uintptr_t), sizeof(UIntPtr_t_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable36[2] = { UIntPtr_t_StaticFields::get_offset_of_Zero_0(), UIntPtr_t::get_offset_of__pointer_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize37 = { sizeof (MulticastDelegate_t), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable37[2] = { MulticastDelegate_t::get_offset_of_prev_9(), MulticastDelegate_t::get_offset_of_kpm_next_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize38 = { sizeof (Delegate_t), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable38[9] = { Delegate_t::get_offset_of_method_ptr_0(), Delegate_t::get_offset_of_invoke_impl_1(), Delegate_t::get_offset_of_m_target_2(), Delegate_t::get_offset_of_method_3(), Delegate_t::get_offset_of_delegate_trampoline_4(), Delegate_t::get_offset_of_method_code_5(), Delegate_t::get_offset_of_method_info_6(), Delegate_t::get_offset_of_original_method_info_7(), Delegate_t::get_offset_of_data_8(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize39 = { sizeof (Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF), sizeof(Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF_marshaled_pinvoke), sizeof(Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable39[1] = { Enum_t5AAC444DFCAA78411386665A25FE3CD3169879EF_StaticFields::get_offset_of_split_char_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize40 = { sizeof (RuntimeArray), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize41 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable41[2] = { 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize42 = { sizeof (SimpleEnumerator_tF4FC79ABC6002436095E7D58D522B97A54E60590), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable42[3] = { SimpleEnumerator_tF4FC79ABC6002436095E7D58D522B97A54E60590::get_offset_of_enumeratee_0(), SimpleEnumerator_tF4FC79ABC6002436095E7D58D522B97A54E60590::get_offset_of_currentpos_1(), SimpleEnumerator_tF4FC79ABC6002436095E7D58D522B97A54E60590::get_offset_of_length_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize43 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable43[1] = { 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize44 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable44[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize45 = { sizeof (Swapper_t9F2C0D39670373AAE7E9AE52A834E0ED2D92C23F), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize46 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize47 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize48 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize49 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize50 = { sizeof (Void_tDB81A15FA2AB53E2401A76B745D215397B29F783)+ sizeof (RuntimeObject), 1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize51 = { sizeof (Type_t), -1, sizeof(Type_t_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable51[8] = { 0, Type_t::get_offset_of__impl_1(), Type_t_StaticFields::get_offset_of_Delimiter_2(), Type_t_StaticFields::get_offset_of_EmptyTypes_3(), Type_t_StaticFields::get_offset_of_FilterAttribute_4(), Type_t_StaticFields::get_offset_of_FilterName_5(), Type_t_StaticFields::get_offset_of_FilterNameIgnoreCase_6(), Type_t_StaticFields::get_offset_of_Missing_7(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize52 = { sizeof (MemberInfo_t), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize53 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize54 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize55 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize56 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize57 = { sizeof (Exception_t), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable57[11] = { Exception_t::get_offset_of_trace_ips_0(), Exception_t::get_offset_of_inner_exception_1(), Exception_t::get_offset_of_message_2(), Exception_t::get_offset_of_help_link_3(), Exception_t::get_offset_of_class_name_4(), Exception_t::get_offset_of_stack_trace_5(), Exception_t::get_offset_of__remoteStackTraceString_6(), Exception_t::get_offset_of_remote_stack_index_7(), Exception_t::get_offset_of_hresult_8(), Exception_t::get_offset_of_source_9(), Exception_t::get_offset_of__data_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize58 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize59 = { sizeof (RuntimeFieldHandle_tDDEB9F6EC2C3875C313750A5C3C33488A2F7A703)+ sizeof (RuntimeObject), sizeof(RuntimeFieldHandle_tDDEB9F6EC2C3875C313750A5C3C33488A2F7A703 ), 0, 0 }; extern const int32_t g_FieldOffsetTable59[1] = { RuntimeFieldHandle_tDDEB9F6EC2C3875C313750A5C3C33488A2F7A703::get_offset_of_value_0() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize60 = { sizeof (RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD)+ sizeof (RuntimeObject), sizeof(RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD ), 0, 0 }; extern const int32_t g_FieldOffsetTable60[1] = { RuntimeTypeHandle_t58BB862EF56F46A9518F8ACA413EF7D70238F1AD::get_offset_of_value_0() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize61 = { sizeof (ParamArrayAttribute_t2108C09F62ACD30BCEB0D170A0DE5D779783EC22), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize62 = { sizeof (OutAttribute_t0ED5A1CE96E11A5BDBFC614869FFD423495F43EB), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize63 = { sizeof (ObsoleteAttribute_tF664926888D92615CB9A166412D1E197874E2C94), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable63[2] = { ObsoleteAttribute_tF664926888D92615CB9A166412D1E197874E2C94::get_offset_of__message_0(), ObsoleteAttribute_tF664926888D92615CB9A166412D1E197874E2C94::get_offset_of__error_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize64 = { sizeof (DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable64[9] = { DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_CallingConvention_0(), DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_CharSet_1(), DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_Dll_2(), DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_EntryPoint_3(), DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_ExactSpelling_4(), DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_PreserveSig_5(), DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_SetLastError_6(), DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_BestFitMapping_7(), DllImportAttribute_t213D4F3B8CF912A021E83C034835112608EAC265::get_offset_of_ThrowOnUnmappableChar_8(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize65 = { sizeof (MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable65[7] = { MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE::get_offset_of_utype_0(), MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE::get_offset_of_ArraySubType_1(), MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE::get_offset_of_MarshalCookie_2(), MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE::get_offset_of_MarshalType_3(), MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE::get_offset_of_MarshalTypeRef_4(), MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE::get_offset_of_SizeConst_5(), MarshalAsAttribute_tFDD884D0B2ACF3CAAA2A4A3521063CEE5DB3EDAE::get_offset_of_SizeParamIndex_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize66 = { sizeof (InAttribute_t795BB5EC6BD74D2CF13BA1EAB6C112C98EB00E4D), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize67 = { sizeof (ConditionalAttribute_t65D186CC2DEFD4F839DDCFB180B8AEE8293779AA), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable67[1] = { ConditionalAttribute_t65D186CC2DEFD4F839DDCFB180B8AEE8293779AA::get_offset_of_myCondition_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize68 = { sizeof (SecurityAttribute_t532FD6D44D5E61D437F97ECCF7FD7DEFE265F0C5), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize69 = { sizeof (GuidAttribute_tFADD188D2E2B2BF32624D558D1E7D2A6086E35DB), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable69[1] = { GuidAttribute_tFADD188D2E2B2BF32624D558D1E7D2A6086E35DB::get_offset_of_guidValue_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize70 = { sizeof (ComImportAttribute_tAFEEBF41C09108C78BE098E6951686BDA2F92EEE), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize71 = { sizeof (OptionalAttribute_t850203AA3F7B1FF849C1FA61A09BC84E448F800B), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize72 = { sizeof (FixedBufferAttribute_t9367EDE2ADFA15474F1A91C8387D022B4728B064), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable72[2] = { FixedBufferAttribute_t9367EDE2ADFA15474F1A91C8387D022B4728B064::get_offset_of_elementType_0(), FixedBufferAttribute_t9367EDE2ADFA15474F1A91C8387D022B4728B064::get_offset_of_length_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize73 = { sizeof (CompilerGeneratedAttribute_t98B4A7C00E6A42E9E9D561FB9C8FC96304E069C5), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize74 = { sizeof (InternalsVisibleToAttribute_t63DF8EC119150BF501084AF970829C6AEFA2B0F4), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable74[2] = { InternalsVisibleToAttribute_t63DF8EC119150BF501084AF970829C6AEFA2B0F4::get_offset_of_assemblyName_0(), InternalsVisibleToAttribute_t63DF8EC119150BF501084AF970829C6AEFA2B0F4::get_offset_of_all_visible_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize75 = { sizeof (RuntimeCompatibilityAttribute_tCB1191BA01F9F4A9B02DE1F89A021DC4E9BAA23A), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable75[1] = { RuntimeCompatibilityAttribute_tCB1191BA01F9F4A9B02DE1F89A021DC4E9BAA23A::get_offset_of_wrap_non_exception_throws_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize76 = { sizeof (DebuggerHiddenAttribute_tC1385C90899898587339A9A236F8ED9800400417), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize77 = { sizeof (DefaultMemberAttribute_tA6BDB6141F5EE774BC59AA22BFFBE34A41C944C8), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable77[1] = { DefaultMemberAttribute_tA6BDB6141F5EE774BC59AA22BFFBE34A41C944C8::get_offset_of_member_name_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize78 = { sizeof (DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable78[5] = { DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821::get_offset_of_scale_0(), DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821::get_offset_of_sign_1(), DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821::get_offset_of_hi_2(), DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821::get_offset_of_mid_3(), DecimalConstantAttribute_t5A37F426D60FE70806686E34D623A296AFB90821::get_offset_of_low_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize79 = { sizeof (FieldOffsetAttribute_t6903AC169DD803EBEB6DD0FFE54D1568CA186DAC), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable79[1] = { FieldOffsetAttribute_t6903AC169DD803EBEB6DD0FFE54D1568CA186DAC::get_offset_of_val_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize80 = { sizeof (RuntimeArgumentHandle_tB0C3CDFC95F9CF95BE76B9B155D2AE12EA4ACF49)+ sizeof (RuntimeObject), sizeof(RuntimeArgumentHandle_tB0C3CDFC95F9CF95BE76B9B155D2AE12EA4ACF49 ), 0, 0 }; extern const int32_t g_FieldOffsetTable80[1] = { RuntimeArgumentHandle_tB0C3CDFC95F9CF95BE76B9B155D2AE12EA4ACF49::get_offset_of_args_0() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize81 = { sizeof (AsyncCallback_t74ABD1277F711E7FBDCB00E169A63DEFD39E86A2), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize82 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize83 = { sizeof (TypedReference_t6C50501B536C0B63B481CF84F67719D9B94D3593)+ sizeof (RuntimeObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable83[3] = { TypedReference_t6C50501B536C0B63B481CF84F67719D9B94D3593::get_offset_of_type_0() + static_cast<int32_t>(sizeof(RuntimeObject)), TypedReference_t6C50501B536C0B63B481CF84F67719D9B94D3593::get_offset_of_value_1() + static_cast<int32_t>(sizeof(RuntimeObject)), TypedReference_t6C50501B536C0B63B481CF84F67719D9B94D3593::get_offset_of_klass_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize84 = { sizeof (ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212)+ sizeof (RuntimeObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable84[4] = { ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212::get_offset_of_sig_0() + static_cast<int32_t>(sizeof(RuntimeObject)), ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212::get_offset_of_args_1() + static_cast<int32_t>(sizeof(RuntimeObject)), ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212::get_offset_of_next_arg_2() + static_cast<int32_t>(sizeof(RuntimeObject)), ArgIterator_t91764B0E783C8EB1E5FCCA14A5116FE666DB0212::get_offset_of_num_args_3() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize85 = { sizeof (MarshalByRefObject_t05F62A8AC86E36BAE3063CA28097945DE9E179C4), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable85[1] = { MarshalByRefObject_t05F62A8AC86E36BAE3063CA28097945DE9E179C4::get_offset_of__identity_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize86 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable86[2] = { 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize87 = { sizeof (RuntimeHelpers_t58E3CCC7308DD00F68A88BF555A80FF0FBABE8D3), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize88 = { sizeof (Locale_t12F756ABDAE9CA1C3A9518C0EF782FD1A54D2FEE), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize89 = { sizeof (MonoTODOAttribute_tC3BFF62878CE5A141978F4C91C28CFE340F3BB45), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable89[1] = { MonoTODOAttribute_tC3BFF62878CE5A141978F4C91C28CFE340F3BB45::get_offset_of_comment_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize90 = { sizeof (MonoDocumentationNoteAttribute_t3A046DD4447EB8D0E57187CBF5DEE1D02F1A24CF), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize91 = { sizeof (MonoLimitationAttribute_tD26F08333B27ADCAA36FD8328FFFF04FE9C103B2), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize92 = { sizeof (SafeHandleZeroOrMinusOneIsInvalid_tFB69962935CA6B88F4DB0AC72A19642AE5A01C1F), sizeof(void*), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize93 = { sizeof (SafeWaitHandle_t40C8EF13EE28AED31D814C26B860551E8962BEBE), sizeof(void*), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize94 = { sizeof (CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable94[4] = { CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A::get_offset_of_ranges_0(), CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A::get_offset_of_TotalCount_1(), CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A::get_offset_of_defaultIndex_2(), CodePointIndexer_tBEAB082D551EAD545D7B14B25BF02150303A3C2A::get_offset_of_defaultCP_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize95 = { sizeof (TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52)+ sizeof (RuntimeObject), sizeof(TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52 ), 0, 0 }; extern const int32_t g_FieldOffsetTable95[5] = { TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52::get_offset_of_Start_0() + static_cast<int32_t>(sizeof(RuntimeObject)), TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52::get_offset_of_End_1() + static_cast<int32_t>(sizeof(RuntimeObject)), TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52::get_offset_of_Count_2() + static_cast<int32_t>(sizeof(RuntimeObject)), TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52::get_offset_of_IndexStart_3() + static_cast<int32_t>(sizeof(RuntimeObject)), TableRange_t7412995BCD43AB0D42039C6DF1413777053C8C52::get_offset_of_IndexEnd_4() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize96 = { sizeof (TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable96[4] = { TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536::get_offset_of_LCID_0(), TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536::get_offset_of_TailoringIndex_1(), TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536::get_offset_of_TailoringCount_2(), TailoringInfo_t0D99C80D20D2733A229F5AD2A49B954381A8D536::get_offset_of_FrenchSort_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize97 = { sizeof (Contraction_t431612397072C270EAFC2580AC4F0BBC94632A7A), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable97[3] = { Contraction_t431612397072C270EAFC2580AC4F0BBC94632A7A::get_offset_of_Source_0(), Contraction_t431612397072C270EAFC2580AC4F0BBC94632A7A::get_offset_of_Replacement_1(), Contraction_t431612397072C270EAFC2580AC4F0BBC94632A7A::get_offset_of_SortKey_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize98 = { sizeof (ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0), -1, sizeof(ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable98[1] = { ContractionComparer_tE5C323345B887CA47B1B139D43C0CC053F89FFE0_StaticFields::get_offset_of_Instance_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize99 = { sizeof (Level2Map_t066C49DE57EDACBB77D6F873C258FC48BF409A58), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable99[2] = { Level2Map_t066C49DE57EDACBB77D6F873C258FC48BF409A58::get_offset_of_Source_0(), Level2Map_t066C49DE57EDACBB77D6F873C258FC48BF409A58::get_offset_of_Replace_1(), }; #ifdef __clang__ #pragma clang diagnostic pop #endif
41.533973
286
0.837703
[ "object" ]
3a7b41d3ca053ee6ae44c5e32f149d29fd584184
6,641
cpp
C++
3dEngine/src/scene/renderer3d/lighting/shadow/light/LightShadowMap.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
24
2015-10-05T00:13:57.000Z
2020-05-06T20:14:06.000Z
3dEngine/src/scene/renderer3d/lighting/shadow/light/LightShadowMap.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
1
2019-11-01T08:00:55.000Z
2019-11-01T08:00:55.000Z
3dEngine/src/scene/renderer3d/lighting/shadow/light/LightShadowMap.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
10
2015-11-25T07:33:13.000Z
2020-03-02T08:21:10.000Z
#include <stdexcept> #include <utility> #include <scene/renderer3d/lighting/shadow/light/LightShadowMap.h> #include <scene/renderer3d/lighting/shadow/light/LightSplitShadowMap.h> #include <scene/renderer3d/lighting/shadow/display/ShadowModelShaderVariable.h> namespace urchin { LightShadowMap::LightShadowMap(Light& light, const OctreeManager<Model>& modelOctreeManager, float viewingShadowDistance, std::shared_ptr<Texture> shadowMapTexture, unsigned int nbShadowMaps, std::unique_ptr<OffscreenRender> renderTarget) : light(light), modelOctreeManager(modelOctreeManager), viewingShadowDistance(viewingShadowDistance), nbShadowMaps(nbShadowMaps), renderTarget(std::move(renderTarget)), shadowMapTexture(std::move(shadowMapTexture)) { if (this->renderTarget) { //only false for unit tests this->renderTarget->initialize(); createOrUpdateShadowModelSetDisplayer(nbShadowMaps); } updateLightViewMatrix(); light.addObserver(this, Light::LIGHT_MOVE); } LightShadowMap::~LightShadowMap() { light.removeObserver(this, Light::LIGHT_MOVE); if (renderTarget) { renderTarget->cleanup(); } } void LightShadowMap::updateLightViewMatrix() { if (light.hasParallelBeams()) { //sunlight Vector3<float> lightDirection = light.getDirections()[0]; const Vector3<float>& f = lightDirection.normalize(); const Vector3<float>& s = f.crossProduct(Vector3<float>(0.0f, 1.0f, 0.0f)).normalize(); const Vector3<float>& u = s.crossProduct(f).normalize(); Matrix4<float> m( s[0], s[1], s[2], 0, u[0], u[1], u[2], 0, -f[0], -f[1], -f[2], 0, 0, 0, 0, 1); Matrix4<float> eye = Matrix4<float>::buildTranslation(lightDirection.X, lightDirection.Y, lightDirection.Z); this->lightViewMatrix = m * eye; } else { throw std::runtime_error("Shadow currently not supported on omnidirectional light."); } } void LightShadowMap::notify(Observable* observable, int notificationType) { if (dynamic_cast<Light*>(observable)) { if (notificationType == Light::LIGHT_MOVE) { updateLightViewMatrix(); } } } const Light& LightShadowMap::getLight() const { return light; } const OctreeManager<Model>& LightShadowMap::getModelOctreeManager() const { return modelOctreeManager; } float LightShadowMap::getViewingShadowDistance() const { return viewingShadowDistance; } unsigned int LightShadowMap::getNumberShadowMaps() const { return nbShadowMaps; } void LightShadowMap::createOrUpdateShadowModelSetDisplayer(unsigned int nbShadowMaps) { assert(renderTarget); std::vector<std::size_t> variablesDescriptions = {sizeof(nbShadowMaps)}; auto shaderConstants = std::make_unique<ShaderConstants>(variablesDescriptions, &nbShadowMaps); shadowModelSetDisplayer = std::make_unique<ModelSetDisplayer>(DisplayMode::DEPTH_ONLY_MODE); shadowModelSetDisplayer->setupShader("modelDepthOnly.vert.spv", "modelShadowMap.geom.spv", "modelShadowMap.frag.spv", std::move(shaderConstants)); shadowModelSetDisplayer->initialize(*renderTarget); shadowModelSetDisplayer->setupCustomShaderVariable(std::make_unique<ShadowModelShaderVariable>(this)); } /** * First split to add must be the split nearest to the eye. */ LightSplitShadowMap& LightShadowMap::addLightSplitShadowMap() { lightSplitShadowMaps.push_back(std::make_unique<LightSplitShadowMap>(this)); assert(lightSplitShadowMaps.size() <= nbShadowMaps); return *lightSplitShadowMaps.back(); } /** * @return Light split shadow maps. First split in the vector is the split nearest to the eye. */ const std::vector<std::unique_ptr<LightSplitShadowMap>>& LightShadowMap::getLightSplitShadowMaps() const { return lightSplitShadowMaps; } void LightShadowMap::addTextureFilter(std::unique_ptr<TextureFilter> textureFilter) { textureFilters.push_back(std::move(textureFilter)); } bool LightShadowMap::hasTextureFilter() const { return !textureFilters.empty(); } void LightShadowMap::applyTextureFilters(std::uint64_t frameIndex, unsigned int numDependenciesToOutput) const { for (std::size_t i = 0; i < textureFilters.size(); ++i) { if (i == textureFilters.size() - 1) { unsigned int numDependenciesToFilterOutputs = numDependenciesToOutput; textureFilters[i]->applyFilter(frameIndex, numDependenciesToFilterOutputs); } else { unsigned int numDependenciesToFilterOutputs = 1 /*next filter */; textureFilters[i]->applyFilter(frameIndex, numDependenciesToFilterOutputs); } } } const std::shared_ptr<Texture>& LightShadowMap::getFilteredShadowMapTexture() const { if (textureFilters.empty()) { return shadowMapTexture; } return textureFilters.back()->getTexture(); } const Matrix4<float>& LightShadowMap::getLightViewMatrix() const { return lightViewMatrix; } bool LightShadowMap::needShadowMapUpdate() const { return std::ranges::any_of(lightSplitShadowMaps, [](const std::unique_ptr<LightSplitShadowMap>& lightSplitShadowMap){ return lightSplitShadowMap->needShadowMapUpdate(); }); } void LightShadowMap::removeModel(Model* model) const { shadowModelSetDisplayer->removeModel(model); } std::span<Model*> LightShadowMap::retrieveModels() const { models.clear(); for (auto& lightSplitShadowMap : lightSplitShadowMaps) { std::span<Model* const> frustumSplitModels = lightSplitShadowMap->getModels(); OctreeableHelper<Model>::merge(models, frustumSplitModels); } return models; } void LightShadowMap::renderModels(std::uint64_t frameIndex, unsigned int numDependenciesToRawShadowMaps, unsigned int renderingOrder) const { shadowModelSetDisplayer->updateModels(retrieveModels()); renderTarget->disableAllRenderers(); shadowModelSetDisplayer->prepareRendering(renderingOrder, lightViewMatrix); renderTarget->render(frameIndex, numDependenciesToRawShadowMaps); } }
40.993827
180
0.664207
[ "render", "vector", "model" ]
3a7c5d8088781dceb60a1d6a818949231f326aab
1,171
cpp
C++
stdlib/public/runtime/ImageInspectionInit.cpp
paulmenage/apple-swift
3902688b04385bf8e9b45dea868855ce57cf5271
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
stdlib/public/runtime/ImageInspectionInit.cpp
paulmenage/apple-swift
3902688b04385bf8e9b45dea868855ce57cf5271
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
stdlib/public/runtime/ImageInspectionInit.cpp
paulmenage/apple-swift
3902688b04385bf8e9b45dea868855ce57cf5271
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
//===--- ImageInspectionInit.cpp ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// \file /// /// This file along with swift_sections.S is prepended to each shared library on /// an ELF target which contains protocol and metadata sections. /// //===----------------------------------------------------------------------===// #if defined(__ELF__) || defined(__ANDROID__) #include "ImageInspection.h" #include <memory> // This is called at startup and by each shared object as it is dlopen()'d to // allow the section data for the object to be loaded. __attribute__((constructor)) static void sectionDataInit() { void *addr = reinterpret_cast<void *>(std::addressof(sectionDataInit)); swift_addNewDSOImage(addr); } #endif
34.441176
80
0.604611
[ "object" ]
3a7deed24f1c6dd5ce4be95df86f54c6ecd8a9a1
568
cpp
C++
HackerRank/Algorithms/Easy/E0006.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
54
2019-05-13T12:13:09.000Z
2022-02-27T02:59:00.000Z
HackerRank/Algorithms/Easy/E0006.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
2
2020-10-02T07:16:43.000Z
2020-10-19T04:36:19.000Z
HackerRank/Algorithms/Easy/E0006.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
20
2020-05-26T09:48:13.000Z
2022-03-18T15:18:27.000Z
/* Problem Statement: https://www.hackerrank.com/challenges/plus-minus/problem */ #include <iostream> #include <vector> using namespace std; void plusMinus(vector<int> arr) { vector<double> count{0,0,0}; for(int num: arr){ if(num > 0) count[0]++; else if(num < 0) count[1]++; else count[2]++; } for(int i=0 ; i<count.size() ; i++){ count[i] /= arr.size(); printf("%0.6f\n",count[i]); } } int main() { int len, num; cin>>len; vector<int> arr; for(int i=0 ; i<len ; i++){ cin>>num; arr.push_back(num); } plusMinus(arr); return 0; }
15.351351
75
0.59507
[ "vector" ]
3a7edfd4c36f06099e6501f3217bd731f0cd6d1d
540
cpp
C++
codingame/practice/cp0/power_of_thor_episode_1.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
codingame/practice/cp0/power_of_thor_episode_1.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
codingame/practice/cp0/power_of_thor_episode_1.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
// https://www.codingame.com/training/easy/power-of-thor-episode-1 #include "common/geometry/d2/base.h" #include "common/geometry/d2/point_io.h" #include "common/numeric/utils/sign.h" #include "common/stl/base.h" #include <string> int main_power_of_thor_episode_1() { vector<string> vx{"W", "", "E"}, vy{"N", "", "S"}; I2Point light, thor; cin >> light >> thor; auto v = light - thor; while (1) { int dx = Sign(v.dx); int dy = Sign(v.dy); v += I2Vector(dx, dy); cout << vy[dy + 1] << vx[dx + 1] << endl; } }
23.478261
66
0.609259
[ "geometry", "vector" ]
3a7fbce06a9ffb38c563d8898282e70ddf6ebdf0
10,059
cpp
C++
opencv/native/jni/include/opencv2/MeanShift.cpp
Young-Jang/BarberMan
19bcf0637ff668da9cc31bd6e4cb4f3e0fe5e797
[ "MIT" ]
1
2022-03-22T18:39:30.000Z
2022-03-22T18:39:30.000Z
opencv/native/jni/include/opencv2/MeanShift.cpp
Young-Jang/BarberMan
19bcf0637ff668da9cc31bd6e4cb4f3e0fe5e797
[ "MIT" ]
null
null
null
opencv/native/jni/include/opencv2/MeanShift.cpp
Young-Jang/BarberMan
19bcf0637ff668da9cc31bd6e4cb4f3e0fe5e797
[ "MIT" ]
null
null
null
//---------------- Head File --------------------------------------- #include "MeanShift.h" #include <cmath> #include <thread> //---------------- Name space --------------------------------------- using namespace cv; using namespace std; //---------------- Definition --------------------------------------- #define MS_MAX_NUM_CONVERGENCE_STEPS 5 // up to 10 steps are for convergence #define MS_MEAN_SHIFT_TOL_COLOR 0.09 // minimum mean color shift change #define MS_MEAN_SHIFT_TOL_SPATIAL 0.09 // minimum mean spatial shift change const int dxdy[][2] = { {-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1} }; // Region Growing // Constructor Point5D::Point5D() { x = -1; y = -1; } // Destructor Point5D::~Point5D() { } // Scale the OpenCV Lab color to Lab range void Point5D::PointLab() { l = l * 100 / 255; a = a - 128; b = b - 128; } // Sclae the Lab color to OpenCV range that can be used to transform to RGB void Point5D::PointRGB() { l = l * 255 / 100; a = a + 128; b = b + 128; } // Accumulate points void Point5D::MSPoint5DAccum(Point5D Pt) { x += Pt.x; y += Pt.y; l += Pt.l; a += Pt.a; b += Pt.b; } // Copy a point void Point5D::MSPoint5DCopy(Point5D Pt) { x = Pt.x; y = Pt.y; l = Pt.l; a = Pt.a; b = Pt.b; } // Compute color space distance between two points float Point5D::MSPoint5DColorDistance(Point5D Pt) { return (l - Pt.l) * (l - Pt.l) + (a - Pt.a) * (a - Pt.a) + (b - Pt.b) * (b - Pt.b); } // Compute spatial space distance between two points float Point5D::MSPoint5DSpatialDistance(Point5D Pt) { return (x - Pt.x) * (x - Pt.x) + (y - Pt.y) * (y - Pt.y); } // Scale point void Point5D::MSPoint5DScale(float scale) { x *= scale; y *= scale; l *= scale; a *= scale; b *= scale; } // Set point value void Point5D::MSPOint5DSet(float px, float py, float pl, float pa, float pb) { x = px; y = py; l = pl; a = pa; b = pb; } // Print 5D point void Point5D::Print() { cout << x << " " << y << " " << l << " " << a << " " << b << endl; } // Constructor for spatial bandwidth and color bandwidth MeanShift::MeanShift(float s, float r) { hs = s; hr = r * r; } // Mean Shift Filtering void MeanShift::MSFiltering(Mat& Img) { const auto ROWS = Img.rows; // Get row number const auto COLS = Img.cols; // Get column number split(Img, IMGChannels); // Split Lab color vector<thread> operations; const auto div = thread::hardware_concurrency(); const auto dataSize = ROWS * COLS; const auto unit = dataSize / (div - 1); for (auto i = 0; i < div; ++i) { auto start = unit * i; if (start > dataSize) break; auto end = unit * (i + 1); if (end > dataSize) end = dataSize; operations.push_back(thread{ [start, end, &ROWS, &COLS, &Img](int hs, int hr, vector<Mat> IMGChannels)->void { int Left, Right, Top, Bottom, NumPts, step; Point5D PtCur, PtPrev, PtSum, Pt; constexpr auto channels = 3; for (auto idx = start; idx < end; ++idx) { auto row = idx / COLS, col = idx % COLS; Left = (col - hs) > 0 ? (col - hs) : 0; Right = (col + hs) < COLS ? (col + hs) : COLS; Top = (row - hs) > 0 ? (row - hs) : 0; Bottom = (row + hs) < ROWS ? (row + hs) : ROWS; PtCur.MSPOint5DSet(row, col, static_cast<float>(IMGChannels[0].data[idx]), static_cast<float>(IMGChannels[1].data[idx]), static_cast<float>(IMGChannels[2].data[idx])); PtCur.PointLab(); step = 0; do { PtPrev.MSPoint5DCopy(PtCur); PtSum.MSPOint5DSet(0, 0, 0, 0, 0); NumPts = 0; for (auto hx = Top; hx < Bottom; ++hx) { for (auto hy = Left; hy < Right; ++hy) { auto hIdx = hx * COLS + hy; Pt.MSPOint5DSet(hx, hy, static_cast<float>(IMGChannels[0].data[hIdx]), static_cast<float>(IMGChannels[1].data[hIdx]), static_cast<float>(IMGChannels[2].data[hIdx])); Pt.PointLab(); if (Pt.MSPoint5DColorDistance(PtCur) < hr) { PtSum.MSPoint5DAccum(Pt); NumPts++; } } } PtSum.MSPoint5DScale(1.0 / NumPts); PtCur.MSPoint5DCopy(PtSum); step++; } while ((PtCur.MSPoint5DColorDistance(PtPrev) > MS_MEAN_SHIFT_TOL_COLOR) && (PtCur.MSPoint5DSpatialDistance(PtPrev) > MS_MEAN_SHIFT_TOL_SPATIAL) && (step < MS_MAX_NUM_CONVERGENCE_STEPS)); PtCur.PointRGB(); auto vIdx = row * COLS * channels + col; Img.data[vIdx + 0] = PtCur.l; Img.data[vIdx + 1] = PtCur.a; Img.data[vIdx + 2] = PtCur.b; } }, hs, hr, IMGChannels }); } for (auto& op : operations) op.join(); } void MeanShift::MSSegmentation(Mat& Img, Mat& Labels) { const auto ROWS = Img.rows, COLS = Img.cols; split(Img, IMGChannels); vector<thread> operations; const auto div = thread::hardware_concurrency(); const auto dataSize = ROWS * COLS; const auto unit = dataSize / (div - 1); for (auto i = 0; i < div; ++i) { auto start = unit * i; if (start > dataSize) break; auto end = unit * (i + 1); if (end > dataSize) end = dataSize; operations.push_back(thread{ [start, end, &ROWS, &COLS, &Img](float hs, float hr, vector<Mat> IMGChannels)->void { int Left, Right, Top, Bottom, NumPts, step; Point5D PtCur, PtPrev, PtSum, Pt; constexpr auto channels = 3; for (auto idx = start; idx < end; ++idx) { auto row = idx / COLS, col = idx % COLS; Left = (col - hs) > 0 ? (col - hs) : 0; Right = (col + hs) < COLS ? (col + hs) : COLS; Top = (row - hs) > 0 ? (row - hs) : 0; Bottom = (row + hs) < ROWS ? (row + hs) : ROWS; PtCur.MSPOint5DSet(row, col, static_cast<float>(IMGChannels[0].data[idx]), static_cast<float>(IMGChannels[1].data[idx]), static_cast<float>(IMGChannels[2].data[idx])); PtCur.PointLab(); step = 0; do { PtPrev.MSPoint5DCopy(PtCur); PtSum.MSPOint5DSet(0, 0, 0, 0, 0); NumPts = 0; for (auto hx = Top; hx < Bottom; ++hx) { for (auto hy = Left; hy < Right; ++hy) { auto hIdx = hx * COLS + hy; Pt.MSPOint5DSet(hx, hy, static_cast<float>(IMGChannels[0].data[hIdx]), static_cast<float>(IMGChannels[1].data[hIdx]), static_cast<float>(IMGChannels[2].data[hIdx])); Pt.PointLab(); if (Pt.MSPoint5DColorDistance(PtCur) < hr) { PtSum.MSPoint5DAccum(Pt); NumPts++; } } } PtSum.MSPoint5DScale(1.0 / NumPts); PtCur.MSPoint5DCopy(PtSum); step++; } while ((PtCur.MSPoint5DColorDistance(PtPrev) > MS_MEAN_SHIFT_TOL_COLOR) && (PtCur.MSPoint5DSpatialDistance(PtPrev) > MS_MEAN_SHIFT_TOL_SPATIAL) && (step < MS_MAX_NUM_CONVERGENCE_STEPS)); PtCur.PointRGB(); auto vIdx = row * COLS * channels + col * channels; Img.data[vIdx + 0] = PtCur.l; Img.data[vIdx + 1] = PtCur.a; Img.data[vIdx + 2] = PtCur.b; } }, hs, hr, IMGChannels }); } for (auto& op : operations) op.join(); //----------------------- Segmentation ------------------------------ Point5D PtCur, Pt; int label = 0; // Label number float *Mode = new float[ROWS * COLS * 3]; // Store the Lab color of each region int *MemberModeCount = new int[ROWS * COLS]; // Store the number of each region memset(MemberModeCount, 0, ROWS * COLS * sizeof(int)); // Initialize the MemberModeCount split(Img, IMGChannels); Labels.create(ROWS, COLS, CV_32S); Labels.setTo(0); auto ptrLabel = Labels.ptr<int>(0); for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { auto idx = i * COLS + j; // If the point is not being labeled if (ptrLabel[idx] == 0) { ptrLabel[idx] = ++label; // Give it a new label number // Get the point PtCur.MSPOint5DSet(i, j, static_cast<float>(IMGChannels[0].data[idx]), static_cast<float>(IMGChannels[1].data[idx]), static_cast<float>(IMGChannels[2].data[idx])); PtCur.PointLab(); // Store each value of Lab Mode[label * 3 + 0] = PtCur.l; Mode[label * 3 + 1] = PtCur.a; Mode[label * 3 + 2] = PtCur.b; // Region Growing 8 Neighbours vector<Point5D> NeighbourPoints; NeighbourPoints.push_back(PtCur); while (!NeighbourPoints.empty()) { Pt = NeighbourPoints.back(); NeighbourPoints.pop_back(); // Get 8 neighbours for (int k = 0; k < 8; k++) { int hx = Pt.x + dxdy[k][0]; int hy = Pt.y + dxdy[k][1]; auto hIdx = hx * COLS + hy; if ((hx >= 0) && (hy >= 0) && (hx < ROWS) && (hy < COLS) && (ptrLabel[hIdx] == 0)) { Point5D P; P.MSPOint5DSet(hx, hy, static_cast<float>(IMGChannels[0].data[hIdx]), static_cast<float>(IMGChannels[1].data[hIdx]), static_cast<float>(IMGChannels[2].data[hIdx])); P.PointLab(); // Check the color if (PtCur.MSPoint5DColorDistance(P) < hr) { // Satisfied the color bandwidth ptrLabel[hIdx] = label; // Give the same label NeighbourPoints.push_back(P); // Push it into stack MemberModeCount[label]++; // This region number plus one // Sum all color in same region Mode[label * 3 + 0] += P.l; Mode[label * 3 + 1] += P.a; Mode[label * 3 + 2] += P.b; } } } } MemberModeCount[label]++; // Count the point itself Mode[label * 3 + 0] /= MemberModeCount[label]; // Get average color Mode[label * 3 + 1] /= MemberModeCount[label]; Mode[label * 3 + 2] /= MemberModeCount[label]; } } } // Get result image from Mode array operations.clear(); static constexpr auto channels = 3; for (auto i = 0; i < div; ++i) { auto start = unit * i; if (start > dataSize) break; auto end = unit * (i + 1); if (end > dataSize) end = dataSize; operations.push_back(thread{ [start, end, &ptrLabel, &Img, &ROWS, &Mode]()->void { int label; for (auto idx = start; idx < end; ++idx) { auto vIdx = idx * channels; label = ptrLabel[idx]; Img.data[vIdx] = Mode[label * channels] * 255 / 100; for (auto added = 1, lIdx = label * channels; added < channels; ++added) Img.data[vIdx + added] = Mode[lIdx + added] + 128; } } }); } for (auto& op : operations) op.join(); //--------------- Delete Memory Applied Before ----------------------- delete[] Mode; delete[] MemberModeCount; }
31.336449
192
0.586042
[ "vector", "transform" ]
3a819c6d346c529a0e24912ad6fb91f87d480c2e
19,277
cpp
C++
OpenGL_Primitive_Restart_Example.cpp
Jammyhammy/Accessible-OpenGL
23a2ea83a69d58f7f0db002b63ea8fb60999a396
[ "BSD-3-Clause" ]
null
null
null
OpenGL_Primitive_Restart_Example.cpp
Jammyhammy/Accessible-OpenGL
23a2ea83a69d58f7f0db002b63ea8fb60999a396
[ "BSD-3-Clause" ]
null
null
null
OpenGL_Primitive_Restart_Example.cpp
Jammyhammy/Accessible-OpenGL
23a2ea83a69d58f7f0db002b63ea8fb60999a396
[ "BSD-3-Clause" ]
null
null
null
#include <gmtl\gmtl.h> #include <stdlib.h> #include <stdio.h> #include <GL/glew.h> #include <GLFW\glfw3.h> #pragma comment (lib, "opengl32.lib") #pragma comment (lib, "glew32.lib") #pragma comment (lib, "glfw3.lib") using namespace std; // std::vector -> vector // GLOBAL VARIABLES gmtl::Matrix44f M; // The matrix we'll wind up sending to the shaders gmtl::Matrix44f W_C; // The matrix representing the pose of our cube float transDelta = 0.1f; // How much any translation operation will translate by float rotDelta = gmtl::Math::PI_OVER_4 / 2.0; // How much any rotation operation rotates by // Matrices that we can reuse so we don't have to declare them every time. They will be set to identity in main gmtl::Matrix44f xTrans; gmtl::Matrix44f zRot; gmtl::Matrix44f yRot; // Setup lists for our vertices and indices vector<GLfloat> arrowVertexBufferData; vector<GLuint> arrowIndexBufferData; vector<GLfloat> cubeVertexBufferData; vector<GLuint> cubeIndexBufferData; // Handle for our Vertex array object GLuint arrowVertexArrayID; GLuint cubeVertexArrayID; // Handles for our buffer objects GLuint arrowVertexBuffer; GLuint arrowIndexBuffer; GLuint arrowColorBuffer; GLuint cubeVertexBuffer; GLuint cubeIndexBuffer; GLuint cubeColorBuffer; // Shader attribute handles GLuint vertex_position, vertex_color; // RGB triples for each coordinate in vertex list data. vector<GLfloat> cubeColorBufferData; vector<GLfloat> arrowColorBufferData; /* Setup handles for our Vertex Array Objects and Buffer Objects */ void setupDrawObject(GLuint &vertexArrayID, GLuint &vertexBuffer, vector<GLfloat> &vertexBufferData, GLuint &indexBuffer, vector<GLuint> &indexBufferData, GLuint &ColorBuffer, vector<GLfloat> &ColorBufferData) { /* Assign ID for a Vertex Array Object to our handle */ glGenVertexArrays(1, &vertexArrayID); /* Bind our Vertex Array Object as the current used object. In OpenGL, you typically will bind a VAO, and then all gl operations after this will be applied to that VAO.*/ glBindVertexArray(vertexArrayID); /* Assign ID for Vertex Buffer Object to our handle */ glGenBuffers(1, &vertexBuffer); /* Bind our VBO as being the active buffer and storing vertex attributes (coordinates) */ glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); /* Copy the vertex data from mesh to our buffer */ /* num_verts * 3 * sizeof(GLfloat) is the size of the mesh list, since */ /* it contains num_verts * 3 GLfloat values */ glBufferData(GL_ARRAY_BUFFER, vertexBufferData.size() * sizeof(GLfloat), &vertexBufferData[0], GL_STATIC_DRAW); /* Assign ID for Index Buffer Object to our handle */ glGenBuffers(1, &indexBuffer); /* Copy the index data from indices to our buffer */ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); /* num_indices * sizeof(GLuint) is the size of the indices list, since it contains num_indices GLuint values */ glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferData.size() * sizeof(GLuint), &indexBufferData[0], GL_STATIC_DRAW); /* Specify that our coordinate data is going into attribute index 0 (SHADER_POSITION_INDEX), and contains three floats per vertex */ glVertexAttribPointer(vertex_position, 3, GL_FLOAT, GL_FALSE, 0, ((void*)0)); /* Enable attribute index 0 (SHADER_POSITION_INDEX) as being used.*/ glEnableVertexAttribArray(vertex_position); /* Assign ID for Color Buffer Object to our handle */ glGenBuffers(1, &ColorBuffer); /* Copy the color data from colors to our buffer */ glBindBuffer(GL_ARRAY_BUFFER, ColorBuffer); /* Copy the color data from colors to our buffer */ /* num_verts * 3 * sizeof(GLfloat) is the size of the color list, since */ /* it contains num_verts * 3 GLfloat values */ glBufferData(GL_ARRAY_BUFFER, ColorBufferData.size() * sizeof(GLfloat), &ColorBufferData[0], GL_STATIC_DRAW); /* Specify that our color data is going into attribute index 1 (SHADER_COLOR_INDEX), and contains three floats per vertex */ glVertexAttribPointer(vertex_color, 3, GL_FLOAT, GL_FALSE, 0, ((void*)0)); /* Enable attribute index 1 (SHADER_COLOR_INDEX) as being used */ glEnableVertexAttribArray(vertex_color); } /* A simple function that will read a file into an allocated char pointer buffer */ char* filetobuf(char *file) { FILE *fptr; long length; char *buf; fopen_s(&fptr, file, "rb"); /* Open file for reading */ if (!fptr) /* Return NULL on failure */ return NULL; fseek(fptr, 0, SEEK_END); /* Seek to the end of the file */ length = ftell(fptr); /* Find out how many bytes into the file we are */ buf = (char*)malloc(length + 1); /* Allocate a buffer for the entire length of the file and a null terminator */ fseek(fptr, 0, SEEK_SET); /* Go back to the beginning of the file */ fread(buf, length, 1, fptr); /* Read the contents of the file in to the buffer */ fclose(fptr); /* Close the file */ buf[length] = 0; /* Null terminator */ return buf; /* Return the buffer */ } void error_callback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); if (action == GLFW_PRESS) { switch (mods) { default: // Do local operations switch (key) { case GLFW_KEY_LEFT: // Local negative x trans // This is basically the same as world x trans, only we apply xTrans to the right of M xTrans[0][3] = -transDelta; xTrans.setState(gmtl::Matrix44f::TRANS); M = M * xTrans; break; case GLFW_KEY_RIGHT: // Local positive x trans xTrans[0][3] = transDelta; xTrans.setState(gmtl::Matrix44f::TRANS); M = M * xTrans; break; case GLFW_KEY_UP: // Local positive z rot zRot[0][0] = gmtl::Math::cos(rotDelta); zRot[0][1] = -gmtl::Math::sin(rotDelta); zRot[1][0] = gmtl::Math::sin(rotDelta); zRot[1][1] = gmtl::Math::cos(rotDelta); zRot.setState(gmtl::Matrix44f::ORTHOGONAL); M = M * zRot; break; } break; } } } /** This function sets up our window, OpenGL context, etc. For assignments, you don't need to know how it works. */ GLFWwindow* setupWindow() { GLFWwindow *window; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(700, 700, "Simple example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); //gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); glfwSwapInterval(1); if (glewInit() != GLEW_OK) exit(EXIT_FAILURE); glEnable(GL_DEPTH_TEST); return window; } /** This function sets up shaders on the graphics card. For assignments, you don't need to know how it works. */ GLuint setupShaderProgram() { GLuint vertex_shader, fragment_shader, shader_program; int IsCompiled_VS, IsCompiled_FS, IsLinked, max_length; char *vertex_shader_log; char *fragment_shader_log; char *shader_program_log; /* Read our shaders into the appropriate buffers */ char* vertex_source = filetobuf((char*)"OpenGL_Example.vert"); char* fragment_source = filetobuf((char*)"OpenGL_Example.frag"); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_source, NULL); glCompileShader(vertex_shader); glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &IsCompiled_VS); if (IsCompiled_VS == GL_FALSE) { glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &max_length); /* The max_length includes the NULL character */ vertex_shader_log = (char *)malloc(max_length); glGetShaderInfoLog(vertex_shader, max_length, &max_length, vertex_shader_log); printf("Error: %s", vertex_shader_log); /* Handle the error in an appropriate way such as displaying a message or writing to a log file. */ /* In this simple program, we'll just leave */ free(vertex_shader_log); free(vertex_source); return 0; } fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_source, NULL); glCompileShader(fragment_shader); glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &IsCompiled_FS); if (IsCompiled_FS == GL_FALSE) { glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &max_length); /* The max_length includes the NULL character */ fragment_shader_log = (char *)malloc(max_length); glGetShaderInfoLog(fragment_shader, max_length, &max_length, fragment_shader_log); printf("Error: %s", fragment_shader_log); /* Handle the error in an appropriate way such as displaying a message or writing to a log file. */ /* In this simple program, we'll just leave */ free(fragment_shader_log); free(vertex_source); free(fragment_source); return 0; } /* If we reached this point it means the vertex and fragment shaders compiled and are syntax error free. */ /* We must link them together to make a GL shader program */ /* GL shader programs are monolithic. It is a single piece made of 1 vertex shader and 1 fragment shader. */ /* Assign our program handle a "name" */ shader_program = glCreateProgram(); /* Attach our shaders to our program */ glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); /* Link our program */ /* At this stage, the vertex and fragment programs are inspected, optimized and a binary code is generated for the shader. */ /* The binary code is uploaded to the GPU, if there is no error. */ glLinkProgram(shader_program); /* Again, we must check and make sure that it linked. If it fails, it would mean either there is a mismatch between the vertex */ /* and fragment shaders. It might be that you have surpassed your GPU's abilities. Perhaps too many ALU operations or */ /* too many texel fetch instructions or too many interpolators or dynamic loops. */ glGetProgramiv(shader_program, GL_LINK_STATUS, (int *)&IsLinked); if (IsLinked == GL_FALSE) { /* Noticed that glGetProgramiv is used to get the length for a shader program, not glGetShaderiv. */ glGetProgramiv(shader_program, GL_INFO_LOG_LENGTH, &max_length); /* The max_length includes the NULL character */ shader_program_log = (char *)malloc(max_length); /* Notice that glGetProgramInfoLog, not glGetShaderInfoLog. */ glGetProgramInfoLog(shader_program, max_length, &max_length, shader_program_log); printf("Error: %s", shader_program_log); /* Handle the error in an appropriate way such as displaying a message or writing to a log file. */ /* In this simple program, we'll just leave */ free(shader_program_log); free(vertex_source); free(fragment_source); return 0; } // glBindAttribLocation(shader_program, SHADER_POSITION_INDEX, "in_position"); // glBindAttribLocation(shader_program, SHADER_COLOR_INDEX, "in_color"); free(vertex_source); free(fragment_source); return shader_program; } /** This function gets attribute and uniform locations from shaders. For _this_ assignment (A2), you don't need to know how it works. Do not modify the shader in any way for this assignment. */ void init(GLuint shader_program, GLuint &pos_loc_out, GLuint &color_loc_out, GLuint &m_loc_out) { pos_loc_out = glGetAttribLocation(shader_program, "in_position"); color_loc_out = glGetAttribLocation(shader_program, "in_color"); m_loc_out = glGetUniformLocation(shader_program, "M"); } /** This function sets up a mesh with a crude diamond base and an arrowhead. You should change the vertex and index lists to generate sphere/cylinder geometry as described in the assignment handout and in class. */ void setupDrawnObjects() { const int numVerts = 25; // Number of verts in the final arrow // Base of the arrow shape GLfloat baseVerts[5][3] = { {0, 0, 0}, {0, -.25f, 0}, {.4f, -.25f, 0}, {.4f, -.5f, 0}, {.6f, 0, 0} }; // ---------------- REVOLUTION ALGORITHM -------------------------- const float theta = gmtl::Math::TWO_PI / 4.0; // We place a new vertex after this many radians of revolution float currentTheta; // Set in the loop int vertIndex = 0; // index counter for accessing vertex array GLfloat *basePoint; // A quick pointer to the base vertex we'll be basing the generated vertex off of for (int i = 0; i <= 4; i++) { for (int j = 0; j < 5; j++) { basePoint = baseVerts[j]; currentTheta = theta * i; // Make the new point based off the base vertex arrowVertexBufferData.push_back(basePoint[0]); // x always stays the same, cause we're revolving around x axis arrowVertexBufferData.push_back(basePoint[1] * gmtl::Math::cos(currentTheta)); arrowVertexBufferData.push_back(basePoint[1] * gmtl::Math::sin(currentTheta)); // Give vertex a random color arrowColorBufferData.push_back((rand() % 255) / 255.0f); arrowColorBufferData.push_back((rand() % 255) / 255.0f); arrowColorBufferData.push_back((rand() % 255) / 255.0f); vertIndex++; } } // ----------------- INDEX LIST ALGORITHM -------------------------- const int numIndices = 44; // Size of the index. Think of it as 2 * area of the vertex grid just created, + one row for primitive restarts arrowIndexBufferData.resize(numIndices);// Size of the index. Think of it as 2 * area of the vertex grid just created, + one row for primitive restarts glEnable(GL_PRIMITIVE_RESTART); glPrimitiveRestartIndex(0xFFFF); int indexIndex = 0; // Which index of the index list we're modifying // Traverse through the nm * np grid. First we grab one vertex, then we grab the one on top of it, then move right and repeat til we end the row, then do primitive restart. for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { arrowIndexBufferData[indexIndex++] = i * 5 + j; arrowIndexBufferData[indexIndex++] = (i + 1) * 5 + j; } /* Every time GL reads our specified primitive-restart value from the index buffer it will start a new primitive. */ /* This is nice, because this allows us to use one array-buffer and one element-buffer to draw separate GL_TRIANGLE_STRIPS */ arrowIndexBufferData[indexIndex++] = 0xFFFF; } // This is a slightly modified cube. cubeVertexBufferData = { -0.33f, 0.33f, -0.33f, -0.33f, 0.33f, 0.33f, -0.33f, -0.33f, -0.33f, -0.33f, -0.33f, 0.33f, 0.33f, 0.33f, 0.33f, 0.33f, -0.33f, 0.33f, 0.33f, 0.33f, -0.33f, 0.33f, -0.33f, -0.33f, -0.33f, 0.33f, -0.33f, 0.33f, 0.33f, -0.33f, -0.33f, 0.33f, 0.33f, 0.33f, 0.33f, 0.33f, -0.33f, -0.33f, -0.33f, 0.33f, -0.33f, -0.33f, -0.33f, -0.33f, 0.33f, 0.33f, -0.33f, 0.33f }; cubeColorBufferData = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.50f, 1.0f, 0.50f, 0.0f, 1.0f, 0.50f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f }; // Indices for the triangle strips cubeIndexBufferData = { 0, 1, 2, 3, // First triangle strip 0xFFFF, // Primitive restart 1, 4, 3, 5, // Second triangle strip 0xFFFF, 4, 6, 5, 7, 0xFFFF, 0, 6, 2, 7, 0xFFFF, 8, 9, 10, 11, 0xFFFF, 12, 13, 14, 15 }; } /* Call our function that performs opengl operations. This is where your changes for matrix and vertex manipulation should be. */ void drawSingleMesh(GLFWwindow* window, GLuint shader_program, GLuint m_location, GLuint VAO, gmtl::Matrix44f mat, vector<GLuint> &indexData) { glUniformMatrix4fv( m_location, // uniform location 1, // count GL_FALSE, // transpose (no) mat.mData // data ); glBindVertexArray(VAO); // Draw the triangles glDrawElements( GL_TRIANGLE_STRIP, // mode indexData.size(), // count, should be updated with your index list size. GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); } // Add in note "Do not modify shader" /* Our program's entry point */ int main(int argc, char *argv[]) { GLFWwindow* mainwindow = NULL; GLuint program = NULL, VAO = NULL; GLuint pos_location = NULL, color_location = NULL, m_location = NULL; // Make those global matrices identity gmtl::identity(xTrans); gmtl::identity(yRot); gmtl::identity(zRot); gmtl::identity(W_C); // Set up our cube's pose so that it is translated 0.4 units along negative x-axis. W_C[0][3] = -0.4; // Set this matrix's state for greater efficiency in gmtl W_C.setState(gmtl::Matrix44f::TRANS); /* This function sets up our window, OpenGL context, etc. For assignments, you don't need to know how it works. */ mainwindow = setupWindow(); /* This function sets up shaders on the graphics card. For assignments, you don't need to know how it works. */ program = setupShaderProgram(); /* This function gets attribute and uniform locations from shaders. For _this_ assignment, you don't need to know how it works. */ init(program, vertex_position, vertex_color, m_location); /* This function sets up the vertices and attributes for our objects. You should change the vertex and index lists to generate sphere geometry as described in the assignment handout and in class.*/ setupDrawnObjects(); /* This function sets up a Vertex Array Object and buffers vertex and attribute data on the graphics card. Remember that a VAO is typically going to represent one "object" made of vertices and attributes.*/ setupDrawObject(arrowVertexArrayID, arrowVertexBuffer, arrowVertexBufferData, arrowIndexBuffer, arrowIndexBufferData, arrowColorBuffer, arrowColorBufferData); /* Do the same for our cube*/ setupDrawObject(cubeVertexArrayID, cubeVertexBuffer, cubeVertexBufferData, cubeIndexBuffer, cubeIndexBufferData, cubeColorBuffer, cubeColorBufferData); /* This is where we enable primitive restart; Note that we have only two draw objects but we're drawing multiple separate triangle strips.*/ glEnable(GL_PRIMITIVE_RESTART); /* Primitive restart allows you to flag an index of a element buffer as "special". */ glPrimitiveRestartIndex(0xFFFF); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); while (!glfwWindowShouldClose(mainwindow)) { // Call our function that performs opengl operations // This is where your changes for matrix and vertex manipulation should be. glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Load the shader into the rendering pipeline */ //One example of how to draw two meshes // One example of having same mesh and two poses glUseProgram(program); // Draw our arrow mesh. drawSingleMesh(mainwindow, program, m_location, arrowVertexArrayID, M, arrowIndexBufferData); // Draw our cube mesh. drawSingleMesh(mainwindow, program, m_location, cubeVertexArrayID, M * W_C, cubeIndexBufferData); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); /* Swap our buffers to make our changes visible */ glfwSwapBuffers(mainwindow); glfwPollEvents(); } /* Delete our opengl context, destroy our window, and shutdown SDL */ glfwDestroyWindow(mainwindow); glUseProgram(NULL); glDisableVertexAttribArray(pos_location); glDisableVertexAttribArray(color_location); glDeleteProgram(program); glDeleteVertexArrays(1, &VAO); return 0; }
36.234962
211
0.724594
[ "mesh", "geometry", "object", "shape", "vector" ]
3a826520e60220b49cf9c8527e4992f4f53a24f6
9,098
cpp
C++
samples/CinderProject/src/CinderProjectApp.cpp
saynono/cinderHoa
cfba3a2011506e5e3280c178293becd804506e2d
[ "BSD-3-Clause" ]
null
null
null
samples/CinderProject/src/CinderProjectApp.cpp
saynono/cinderHoa
cfba3a2011506e5e3280c178293becd804506e2d
[ "BSD-3-Clause" ]
null
null
null
samples/CinderProject/src/CinderProjectApp.cpp
saynono/cinderHoa
cfba3a2011506e5e3280c178293becd804506e2d
[ "BSD-3-Clause" ]
null
null
null
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/Serial.h" #include "cinder/audio/audio.h" #include "cinder/GeomIo.h" #include "cinder/audio/ChannelRouterNode.h" #include "cinder/Rand.h" #include "cinder/Utilities.h" #include "HoaNode.h" using namespace ci; using namespace ci::app; using namespace std; using namespace nono::audio; class CinderProjectApp : public App { public: void setup() override; void setupInputs(); void setupAudioDevice(); void update() override; void draw() override; void mouseDrag( MouseEvent event ) override; void mouseMove( MouseEvent event ) override; void mouseUp( MouseEvent event ) override; void keyDown( KeyEvent event ) override; nono::audio::HoaNodeMultiRef mHoaNode; audio::GainNodeRef mGain; audio::ChannelRouterNodeRef mChannelRouterRef; float mDisplayScale; audio::InputDeviceNodeRef p4; vector<audio::InputNodeRef> mPlayers; Rand mRandom; nono::audio::HoaSourceRef mHoaSourceHover; nono::audio::HoaSourceRef mHoaSourceSelected; nono::audio::HoaOutputRef mHoaOutputHover; nono::audio::HoaOutputRef mHoaOutputSelected; }; void CinderProjectApp::setup() { setupAudioDevice(); auto ctx = audio::Context::master(); setupInputs(); mDisplayScale = .25; int numAudioSources = mPlayers.size(); int numAudioOutputs = 6; mHoaNode = ctx->makeNode( new HoaNodeMulti( numAudioSources, numAudioOutputs) ); mHoaNode->enable(); // add a Gain to reduce the volume mGain = ctx->makeNode( new audio::GainNode( 0.125f ) ); // connect and enable the Context mHoaNode >> mGain >> ctx->getOutput(); console() << " =========================== ADDING ROUTES =======================" << std::endl; for( int i=0;i<mPlayers.size();i++ ){ mHoaNode->addInputRoute(mPlayers[i]); } ctx->enable(); } void CinderProjectApp::setupInputs(){ auto ctx = audio::Context::master(); string file = "../../../../../samples/data/sound/DrainMagic.ogg"; audio::SourceFileRef sourceFile = audio::load( loadAsset(file), ctx->getSampleRate() ); audio::BufferRef buffer = sourceFile->loadBuffer(); audio::BufferPlayerNodeRef p1 = ctx->makeNode( new audio::BufferPlayerNode( buffer ) ); p1->setLoopEnabled(); p1->start(); p1->setName("Player1"); audio::GenNodeRef p2 = ctx->makeNode( new audio::GenOscNode( audio::WaveformType::SINE, 440 ) ); p2->setName("OSC Sine 220"); p2->enable(); audio::GenNodeRef p3 = ctx->makeNode( new audio::GenOscNode( audio::WaveformType::SQUARE, 220 ) ); p3->setName("OSC Square 220"); p3->enable(); audio::InputDeviceNodeRef p4 = ctx->createInputDeviceNode(); p4->enable(); p4->setName("Microphone"); // mPlayers.push_back( p1 ); // mPlayers.push_back( p2 ); // mPlayers.push_back( p3 ); // mPlayers.push_back( p4 ); for( int i=0;i<5;i++){ // audio::BufferRef buffer = sourceFile->loadBuffer(); // audio::BufferPlayerNodeRef p = ctx->makeNode( new audio::BufferPlayerNode( buffer ) ); // p->setLoopEnabled(); // int pos = mRandom.nextInt(p->getNumFrames()); // console() << i << " => Pos : " << pos << std::endl; // p->start(); // p->seek( pos ); int sine = 100 + i*i; audio::GenNodeRef p = ctx->makeNode( new audio::GenOscNode( audio::WaveformType::SINE, sine ) ); p->setName("OSC Sine " + toString(sine)); p->enable( 1 ); mPlayers.push_back( p ); } } void CinderProjectApp::setupAudioDevice(){ // debug print all devices to console console() << audio::Device::printDevicesToString() << endl; audio::DeviceRef deviceWithMaxOutputs; for( const auto &dev : audio::Device::getDevices() ) { if( ! deviceWithMaxOutputs || deviceWithMaxOutputs->getNumOutputChannels() < dev->getNumOutputChannels() ) deviceWithMaxOutputs = dev; } getWindow()->setTitle( "Cinder HOA Test. Output[" + deviceWithMaxOutputs->getName() +"]" ); console() << "Selecting audioDevice: " << deviceWithMaxOutputs->getName() << std::endl; auto ctx = audio::master(); audio::OutputDeviceNodeRef multichannelOutputDeviceNode = ctx->createOutputDeviceNode( deviceWithMaxOutputs, audio::Node::Format().channels( deviceWithMaxOutputs->getNumOutputChannels() ) ); ctx->setOutput( multichannelOutputDeviceNode ); } void CinderProjectApp::update() { auto sources = mHoaNode->getHoaInputs(); float scale = getWindowWidth()*mDisplayScale; for( auto s: sources ){ vec3 pos = s->mHoaElement->getPosition(); pos = glm::rotate( pos, .01f*length(pos), vec3(0,0,1)); vec2 pos2D( pos.x*scale, pos.y*scale ); s->mHoaElement->setPosition(pos); } mHoaNode->updatePositions(); } void CinderProjectApp::draw() { gl::clear( Color( 0, 0, 0 ) ); gl::color( Color( 1,1,1 ) ); gl::pushMatrices(); gl::translate( getWindowWidth()/2, getWindowHeight()/2 ); float scale = getWindowWidth()*mDisplayScale; auto outputs = mHoaNode->getHoaOutputs(); for( const auto& os: outputs ){ vec3 pos = os->mHoaElement->getPosition(); vec2 pos2D(pos.x*scale,pos.y*scale); if( mHoaOutputHover == os ){ gl::color(1, 0, 0); }else{ gl::color(1, 1, 0); } if( os->bEnabled ){ gl::drawSolidCircle(pos2D, 10); }else{ gl::drawStrokedCircle(pos2D, 10); } gl::color(1, 1, 1); gl::drawString( toString(os->mHoaId+1), pos2D+vec2(20,0)); } auto sources = mHoaNode->getHoaInputs(); for( const auto& s: sources ){ vec3 pos = s->mHoaElement->getPosition(); vec2 pos2D(pos.x*scale,pos.y*scale); if( mHoaSourceHover == s ){ gl::color(1, 0, 0); }else{ gl::color(1, 1, 1); } if( s->bEnabled ){ gl::drawSolidCircle(pos2D, 10); }else{ gl::drawStrokedCircle(pos2D, 10); } // gl::drawSolidCircle(pos2D, 10); gl::color(1, 1, 1); gl::drawString( toString(s->mInput->getName()), pos2D+vec2(20,0)); } gl::popMatrices(); } void CinderProjectApp::mouseUp( MouseEvent e ){ if( e.isRight() || e.isControlDown() ){ if( mHoaOutputHover != nullptr ){ mHoaOutputHover->bEnabled = !mHoaOutputHover->bEnabled; }else if ( mHoaSourceHover != nullptr ){ mHoaSourceHover->bEnabled = !mHoaSourceHover->bEnabled; } } } void CinderProjectApp::mouseDrag( MouseEvent e ){ vec2 mPos = vec2((float)e.getPos().x,(float)e.getPos().y) - vec2(getWindowWidth()/2, getWindowHeight()/2); float scale = getWindowWidth()*mDisplayScale; if( mHoaOutputHover != nullptr ){ vec3 pos( mPos.x/scale, mPos.y/scale, 0 ); pos /= length(pos); mHoaOutputHover->mHoaElement->setPosition(pos); mHoaNode->updateOutputPositions(); } if( mHoaOutputHover == nullptr && mHoaSourceHover != nullptr ){ vec3 pos( mPos.x/scale, mPos.y/scale, 0 ); mHoaSourceHover->mHoaElement->setPosition(pos); mHoaNode->updatePositions(); } } void CinderProjectApp::mouseMove( MouseEvent e ){ if( !mHoaNode ) return; vec2 mPos = vec2((float)e.getPos().x,(float)e.getPos().y) - vec2(getWindowWidth()/2, getWindowHeight()/2); float scale = getWindowWidth()*mDisplayScale; auto outputs = mHoaNode->getHoaOutputs(); mHoaOutputHover = nullptr; for( auto os: outputs ){ vec3 pos = os->mHoaElement->getPosition(); vec2 pos2D( pos.x*scale, pos.y*scale ); if( length(pos2D-mPos) < 10 ){ mHoaOutputHover = os; } } if( mHoaOutputHover == nullptr ){ auto sources = mHoaNode->getHoaInputs(); mHoaSourceHover = nullptr; for( auto s: sources ){ vec3 pos = s->mHoaElement->getPosition(); vec2 pos2D( pos.x*scale, pos.y*scale ); if( length(pos2D-mPos) < 10 ){ mHoaSourceHover = s; } } } } void CinderProjectApp::keyDown( KeyEvent event ){ int val = event.getChar() - '0'; // if( val > 0 && val < 7 ){ // // } // if( event.getChar() == ' ' && mHoaOutputHover != nullptr ){ // mHoaNode->getHoaOutput( mHoaOutputHover->mHoaId )->bEnabled = !mHoaNode->getHoaOutput( mHoaOutputHover->mHoaId )->bEnabled; // } } CINDER_APP( CinderProjectApp, RendererGl (RendererGl::Options().stencil().msaa (16)), [&] (App::Settings * settings) { settings->setWindowSize (800, 800); settings->setFrameRate (60.0f); settings->setTitle ("Cinder HOA Wrapper Basic"); settings->setHighDensityDisplayEnabled(); })
30.428094
194
0.597164
[ "vector" ]
3a83808bf285a02fcce4c8c4fba9ec486789a6bf
6,417
cpp
C++
FKCore/FKRealmConnectionManager.cpp
FajraKatviro/FKFramework2
0b55b402c255b50fe07ee568bbf46acd6617a6e4
[ "MIT" ]
2
2015-10-01T07:25:36.000Z
2015-11-02T23:14:10.000Z
FKCore/FKRealmConnectionManager.cpp
FajraKatviro/FKFramework2
0b55b402c255b50fe07ee568bbf46acd6617a6e4
[ "MIT" ]
13
2015-11-02T22:15:14.000Z
2015-11-03T21:08:51.000Z
FKCore/FKRealmConnectionManager.cpp
FajraKatviro/FKFramework2
0b55b402c255b50fe07ee568bbf46acd6617a6e4
[ "MIT" ]
null
null
null
#include "FKRealmConnectionManager.h" #include "FKRealm.h" #include "FKMessage.h" #include "FKBasicEvent.h" #include "FKEventObject.h" #include "FKLogger.h" #include "FKBasicEventSubjects.h" /*! \class FKRealmConnectionManager \brief This class used to process guest connectors at realm-side */ /*! * \brief Create manager for \i connector at \i realm with \i parent */ FKRealmConnectionManager::FKRealmConnectionManager(FKRealm* realm,FKConnector* connector,QObject *parent): FKConnectionManager(connector,parent),_realm(realm){ FK_CBEGIN FK_CEND } /*! * \brief Deletes manager */ FKRealmConnectionManager::~FKRealmConnectionManager(){ FK_DBEGIN FK_DEND } void FKRealmConnectionManager::processMessage(FKMessage* msg){ FK_MLOGV("Unexpected message from guest to realm",msg->subject()) msg->deleteLater(); realm()->stopGuestConnection(this); } void FKRealmConnectionManager::processGuestEvent(FKBasicEvent* ev){ const QString subject=ev->subject(); const QVariant value=ev->value(); ev->deleteLater(); if(subject==FKBasicEventSubject::login){ realm()->ausvise(this,value); }else{ FK_MLOGV("Unexpected guest event subject from guest to realm",subject) realm()->stopGuestConnection(this); } } void FKRealmConnectionManager::processBasicEvent(FKBasicEvent* ev){ FK_MLOGV("Unexpected basic event from guest to realm",ev->subject()) ev->deleteLater(); realm()->stopGuestConnection(this); } void FKRealmConnectionManager::processEvent(FKEventObject* ev){ FK_MLOGV("Unexpected event from guest to realm",ev->subject()) ev->deleteLater(); realm()->stopGuestConnection(this); } void FKRealmConnectionManager::incomeMessageError(const QString& msgType, const QString& reason){ FK_MLOGV(QString("Income message error from guest to realm: ")+reason,msgType) realm()->stopGuestConnection(this); } /*! * \fn FKRealm* FKRealmConnectionManager::realm()const * \brief Returns realm object reference */ /*! \class FKRealmConnectionManagerC \brief This class used to process connectors from clients at realm-side */ /*! * \brief Create manager for \i connector at \i realm with \i parent */ FKRealmConnectionManagerC::FKRealmConnectionManagerC(const QString& id,FKRealm* realm, FKConnector* connector, QObject* parent): FKRealmConnectionManager(realm,connector,parent),_id(id){ FK_CBEGIN FK_CEND } /*! * \brief Deletes manager */ FKRealmConnectionManagerC::~FKRealmConnectionManagerC(){ FK_DBEGIN FK_DEND } void FKRealmConnectionManagerC::processMessage(FKMessage* msg){ FK_MLOGV("Unexpected message from client to realm",msg->subject()) msg->deleteLater(); realm()->stopClientConnection(_id); } void FKRealmConnectionManagerC::processGuestEvent(FKBasicEvent* ev){ FK_MLOGV("Unexpected guest event from client to realm",ev->subject()) ev->deleteLater(); realm()->stopClientConnection(_id); } void FKRealmConnectionManagerC::processBasicEvent(FKBasicEvent* ev){ const QString subject=ev->subject(); const QVariant value=ev->value(); ev->deleteLater(); if(subject==FKBasicEventSubject::roomList){ todo;//realm()->refreshRoomList(_id,value); }else if(subject==FKBasicEventSubject::createUser){ realm()->createUser(_id,value); }else if(subject==FKBasicEventSubject::deleteUser){ realm()->deleteUser(_id,value); }else if(subject==FKBasicEventSubject::createRoom){ realm()->createRoomRequested(_id,value); }else if(subject==FKBasicEventSubject::joinRoom){ realm()->joinRoomRequested(_id,value); }else{ FK_MLOGV("Unexpected basic event subject from client to realm",subject) realm()->stopClientConnection(_id); } } void FKRealmConnectionManagerC::processEvent(FKEventObject* ev){ FK_MLOGV("Unexpected event from client to realm",ev->subject()) ev->deleteLater(); realm()->stopClientConnection(_id); } void FKRealmConnectionManagerC::incomeMessageError(const QString& msgType, const QString& reason){ FK_MLOGV(QString("Income message error from client to realm: ")+reason,msgType) realm()->stopClientConnection(_id); } /*! \class FKRealmConnectionManagerS \brief This class used to process connectors from servers at realm-side */ /*! * \brief Create manager for \i connector at \i realm with \i parent */ FKRealmConnectionManagerS::FKRealmConnectionManagerS(const qint32 id,FKRealm* realm, FKConnector* connector, QObject* parent): FKRealmConnectionManager(realm,connector,parent),_id(id){ FK_CBEGIN FK_CEND } /*! * \brief Deletes manager */ FKRealmConnectionManagerS::~FKRealmConnectionManagerS(){ FK_DBEGIN FK_DEND } void FKRealmConnectionManagerS::processMessage(FKMessage* msg){ FK_MLOGV("Unexpected message from server to realm",msg->subject()) msg->deleteLater(); realm()->stopServerConnection(_id); } void FKRealmConnectionManagerS::processGuestEvent(FKBasicEvent* ev){ FK_MLOGV("Unexpected guest event from server to realm",ev->subject()) ev->deleteLater(); realm()->stopServerConnection(_id); } void FKRealmConnectionManagerS::processBasicEvent(FKBasicEvent* ev){ const QString subject=ev->subject(); const QVariant value=ev->value(); ev->deleteLater(); if(subject==FKBasicEventSubject::roomData){ realm()->refreshRoomData(_id,value); }else if(subject==FKBasicEventSubject::registerRoomType){ realm()->registerServerRoomType(_id,value); }else if(subject==FKBasicEventSubject::removeRoomType){ realm()->removeServerRoomType(_id,value); }else if(subject==FKBasicEventSubject::dropClient){ realm()->clientDisonnectedFromServer(_id,value); }else if(subject==FKBasicEventSubject::stopRoom){ realm()->roomStopped(_id,value); }else{ FK_MLOGV("Unexpected basic event subject from server to realm",subject) realm()->stopServerConnection(_id); } } void FKRealmConnectionManagerS::processEvent(FKEventObject* ev){ FK_MLOGV("Unexpected event from server to realm",ev->subject()) ev->deleteLater(); realm()->stopServerConnection(_id); } void FKRealmConnectionManagerS::incomeMessageError(const QString& msgType, const QString& reason){ FK_MLOGV(QString("Income message error from server to realm: ")+reason,msgType) realm()->stopServerConnection(_id); }
30.703349
128
0.728066
[ "object" ]
3a89efccb0875012e7317e9e04791558c446718c
28,194
cpp
C++
deps/usr/src/libwav/libwav/CsWav.cpp
xia-lixun/Libaudio.jl
0e3b60d2d7c3e73f9741e7ab8721c213a9b4bf2d
[ "MIT" ]
4
2018-09-27T13:09:53.000Z
2022-02-14T12:25:29.000Z
deps/usr/src/libwav/libwav/CsWav.cpp
xia-lixun/Libaudio.jl
0e3b60d2d7c3e73f9741e7ab8721c213a9b4bf2d
[ "MIT" ]
null
null
null
deps/usr/src/libwav/libwav/CsWav.cpp
xia-lixun/Libaudio.jl
0e3b60d2d7c3e73f9741e7ab8721c213a9b4bf2d
[ "MIT" ]
null
null
null
#include <cstring> #include <cstdio> #include <cstdlib> #include "CsWav.h" CsWav::CsWav() { FrameMatrix = NULL; FrameVector = NULL; StreamFID = NULL; } CsWav::~CsWav() { delete[] FrameVector; delete[] FrameMatrix; FrameVector = NULL; FrameMatrix = NULL; } size_t CsWav::ExtractMetaInfo(const char * FilePath) { uint8_t id[4]; size_t BytesMetaInfo = 0; FILE * f; errno_t Err = fopen_s(&f, FilePath, "rb"); if (Err != 0) { printf("File open failure: %s (%d)\n", FilePath, Err); } //RIFF header BytesMetaInfo += fread( MetaInfo.riff_ckID, sizeof(uint8_t), 4, f); BytesMetaInfo += fread(&(MetaInfo.riff_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesMetaInfo += fread( MetaInfo.riff_waveID, sizeof(uint8_t), 4, f); //check if RF64 format is encountered, we don't do RF64 here if (MetaInfo.riff_cksize == 0xFFFFFFFF) { printf("error: RF64 format is not supported so far.\n"); return 0; } //flush possible JUNK chunk, this chunk is reserved for file recording > 4GB BytesMetaInfo += fread(id, sizeof(uint8_t), 4, f); while (id[0] != 'f' || id[1] != 'm' || id[2] != 't' || id[3] != ' ') { //unknown chunk that we need to skip BytesMetaInfo += fread(&(MetaInfo.unknown_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); uint8_t ByteSkip; for (uint32_t k = 0; k < MetaInfo.unknown_cksize; ++k) BytesMetaInfo += fread(&ByteSkip, sizeof(uint8_t), 1, f); BytesMetaInfo += fread(id, sizeof(uint8_t), 4, f); } //FORMAT header //BytesMetaInfo += fread( MetaInfo.fmt_ckID, sizeof(uint8_t), 4, f); memcpy(MetaInfo.fmt_ckID, id, 4 * sizeof(uint8_t)); BytesMetaInfo += fread(&(MetaInfo.fmt_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesMetaInfo += fread(&(MetaInfo.fmt_wFormatTag), sizeof(uint16_t), 1, f) * sizeof(uint16_t); BytesMetaInfo += fread(&(MetaInfo.fmt_nChannels), sizeof(uint16_t), 1, f) * sizeof(uint16_t); BytesMetaInfo += fread(&(MetaInfo.fmt_nSamplesPerSec), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesMetaInfo += fread(&(MetaInfo.fmt_nAvgbytesPerSec), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesMetaInfo += fread(&(MetaInfo.fmt_nBlockAlign), sizeof(uint16_t), 1, f) * sizeof(uint16_t); BytesMetaInfo += fread(&(MetaInfo.fmt_wBitsPerSample), sizeof(uint16_t), 1, f) * sizeof(uint16_t); //cbSize field if (MetaInfo.fmt_cksize == 18 || MetaInfo.fmt_cksize == 40) { BytesMetaInfo += fread(&(MetaInfo.fmt_cbSize), sizeof(uint16_t), 1, f) * sizeof(uint16_t); } if (MetaInfo.fmt_cksize == 40) { BytesMetaInfo += fread(&(MetaInfo.fmt_wValidBitsPerSample), sizeof(uint16_t), 1, f) * sizeof(uint16_t); BytesMetaInfo += fread(&(MetaInfo.fmt_dwChannelMask), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesMetaInfo += fread(&(MetaInfo.fmt_SubFormat), sizeof(uint8_t), 16, f); } //judge between FACT and DATA BytesMetaInfo += fread(id, sizeof(uint8_t), 4, f); //if FACT chunck memset(MetaInfo.fact_ckID, '-', sizeof(uint8_t) * 4); if (id[0] == 'f' && id[1] == 'a' && id[2] == 'c' && id[3] == 't') { memcpy(MetaInfo.fact_ckID, id, sizeof(uint8_t) * 4); BytesMetaInfo += fread(&(MetaInfo.fact_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesMetaInfo += fread(&(MetaInfo.fact_dwSampleLength), sizeof(uint32_t), 1, f) * sizeof(uint32_t); if (MetaInfo.fact_cksize > 4) { for (int k = 0; k < (int)(MetaInfo.fact_cksize - 4); ++k) { BytesMetaInfo += fread(id, sizeof(uint8_t), 1, f); } } BytesMetaInfo += fread(id, sizeof(uint8_t), 4, f); } while (id[0] != 'd' || id[1] != 'a' || id[2] != 't' || id[3] != 'a') { //unknown chunk that we need to skip BytesMetaInfo += fread(&(MetaInfo.unknown_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); uint8_t ByteSkip; for(uint32_t k = 0; k < MetaInfo.unknown_cksize; ++k) BytesMetaInfo += fread(&ByteSkip, sizeof(uint8_t), 1, f); BytesMetaInfo += fread(id, sizeof(uint8_t), 4, f); } if (id[0] == 'd' && id[1] == 'a' && id[2] == 't' && id[3] == 'a'){ memcpy(MetaInfo.data_ckID, id, sizeof(uint8_t) * 4); //read rest of the DATA chunck BytesMetaInfo += fread(&(MetaInfo.data_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); } else { printf("Header Parse Error!\n"); } fclose(f); //update parameter info NumChannel = (size_t)(MetaInfo.fmt_nChannels); SampleRate = (size_t)(MetaInfo.fmt_nSamplesPerSec); NumFrame = (size_t)(MetaInfo.data_cksize / MetaInfo.fmt_nBlockAlign); return BytesMetaInfo; } void CsWav::PrintMetaInfo(void) { printf("\n"); printf("+------------------------------[RIFF]\n"); printf("|ckID %c%c%c%c\n", MetaInfo.riff_ckID[0], MetaInfo.riff_ckID[1], MetaInfo.riff_ckID[2], MetaInfo.riff_ckID[3]); printf("|cksize %d\n", MetaInfo.riff_cksize); printf("|WAVEID %c%c%c%c\n", MetaInfo.riff_waveID[0], MetaInfo.riff_waveID[1], MetaInfo.riff_waveID[2], MetaInfo.riff_waveID[3]); printf("+----------------------------[FORMAT]\n"); printf("|ckID %c%c%c%c\n", MetaInfo.fmt_ckID[0], MetaInfo.fmt_ckID[1], MetaInfo.fmt_ckID[2], MetaInfo.fmt_ckID[3]); printf("|cksize %d\n", MetaInfo.fmt_cksize); printf("|wFormatTag %x\n", MetaInfo.fmt_wFormatTag); printf("|nChannels %d\n", MetaInfo.fmt_nChannels); printf("|nSamplesPerSec %d\n", MetaInfo.fmt_nSamplesPerSec); printf("|nAvgbytesPerSec %d\n", MetaInfo.fmt_nAvgbytesPerSec); printf("|nBlockAlign %d\n", MetaInfo.fmt_nBlockAlign); printf("|wBitsPerSample %d\n", MetaInfo.fmt_wBitsPerSample); if (MetaInfo.fmt_cksize == 16) { printf("|cbSize -\n"); } else { printf("|cbSize %d\n", MetaInfo.fmt_cbSize); } if (MetaInfo.fmt_cksize == 40) { printf("|wValidBitsPerSample %d\n", MetaInfo.fmt_wValidBitsPerSample); printf("|dwChannelMask %d\n", MetaInfo.fmt_dwChannelMask); printf("|SubFormat "); printf("0x%02X%02X ", MetaInfo.fmt_SubFormat[1], MetaInfo.fmt_SubFormat[0]); for (int j = 2; j < 16; j++) { printf("0x%02X ", MetaInfo.fmt_SubFormat[j]); } printf("\n"); } else { printf("|wValidBitsPerSample -\n"); printf("|dwChannelMask -\n"); printf("|SubFormat -\n"); } printf("+------------------------------[FACT]\n"); printf("|ckID %c%c%c%c\n", MetaInfo.fact_ckID[0], MetaInfo.fact_ckID[1], MetaInfo.fact_ckID[2], MetaInfo.fact_ckID[3]); if (MetaInfo.fact_ckID[0] == '-') { printf("|cksize -\n"); printf("|dwSampleLength -\n"); } else { printf("|cksize %d\n", MetaInfo.fact_cksize); printf("|dwSampleLength %d\n", MetaInfo.fact_dwSampleLength); } printf("+------------------------------[DATA]\n"); printf("|ckID %c%c%c%c\n", MetaInfo.data_ckID[0], MetaInfo.data_ckID[1], MetaInfo.data_ckID[2], MetaInfo.data_ckID[3]); printf("|cksize %d\n", MetaInfo.data_cksize); printf("+-------------------------------[END]\n"); } size_t CsWav::GetFrameLength(void) const { return NumFrame; } size_t CsWav::GetNumChannel(void) const { return NumChannel; } size_t CsWav::GetSampleRate(void) const { return SampleRate; } size_t CsWav::GetBitsPerSample(void) const { return fmt; } // use getters to prepare buffers before invoking this method size_t CsWav::ExtractData_flt(const char * FilePath) { // update the meta information size_t MetaInfoTotalBytes = ExtractMetaInfo(FilePath); uint8_t * flush = (uint8_t *)malloc(MetaInfoTotalBytes * sizeof(uint8_t)); // read data out to buffer size_t EleRead; size_t BytesTotal = 0; float * EachFrame = new float[MetaInfo.fmt_nChannels]; FILE * f; errno_t ERR = fopen_s(&f, FilePath, "rb"); // flush the meta info block BytesTotal += fread(flush, sizeof(uint8_t), MetaInfoTotalBytes, f); free(flush); //read PCM data to buffers for (size_t i = 0; i < NumFrame; i++) { EleRead = fread(EachFrame, sizeof(float), MetaInfo.fmt_nChannels, f); BytesTotal += EleRead * sizeof(float); if (EleRead != MetaInfo.fmt_nChannels) { printf("Data frame read error: %d out of %d\n", i, NumFrame); } for (size_t j = 0; j < MetaInfo.fmt_nChannels; j++) { FrameMatrix[i * MetaInfo.fmt_nChannels + j] = EachFrame[j]; } } fclose(f); delete[] EachFrame; //printf("total: %zd bytes\n", BytesTotal); return BytesTotal; } size_t CsWav::ExtractData_16b(const char * FilePath) { // update the meta information size_t MetaInfoTotalBytes = ExtractMetaInfo(FilePath); uint8_t * flush = (uint8_t *)malloc(MetaInfoTotalBytes * sizeof(uint8_t)); // read data out to buffer size_t BytesTotal = 0; int16_t * Sample = new int16_t[MetaInfo.fmt_nChannels]; float * EachFrame = new float [MetaInfo.fmt_nChannels]; FILE * f; errno_t ERR = fopen_s(&f, FilePath, "rb"); // flush the meta info block BytesTotal += fread(flush, sizeof(uint8_t), MetaInfoTotalBytes, f); free(flush); //printf("bytes flushed: %d\n", BytesTotal); //printf("number of channels: %d\n", MetaInfo.fmt_nChannels); //printf("number of frames %d, channels %d\n", NumFrame, NumChannel); //read PCM data to buffers //there are 2 cases: mono and stereo for (size_t i = 0; i < NumFrame; i++) { BytesTotal += fread(Sample, sizeof(int16_t), MetaInfo.fmt_nChannels, f) * sizeof(int16_t); for (size_t j = 0; j < MetaInfo.fmt_nChannels; j++) { EachFrame[j] = (float)((double)Sample[j] / (double)32768); FrameMatrix[i * MetaInfo.fmt_nChannels + j] = EachFrame[j]; } //if(i >= 0 && i < 8) printf("%d %d\n", Sample[0], Sample[1]); } fclose(f); delete[] EachFrame; delete[] Sample; //printf("total: %zd bytes\n", BytesTotal); return BytesTotal; } size_t CsWav::ExtractData_24b(const char * FilePath) { // update the meta information size_t MetaInfoTotalBytes = ExtractMetaInfo(FilePath); uint8_t * flush = (uint8_t *)malloc(MetaInfoTotalBytes * sizeof(uint8_t)); // read data out to buffer size_t BytesTotal = 0; uint8_t Sample[3]; float * EachFrame = new float[MetaInfo.fmt_nChannels]; FILE * f; errno_t ERR = fopen_s(&f, FilePath, "rb"); // flush the meta info block BytesTotal += fread(flush, sizeof(uint8_t), MetaInfoTotalBytes, f); free(flush); //read PCM data to buffers //there are 2 cases: mono and stereo for (size_t i = 0; i < NumFrame; i++) { for (size_t j = 0; j < MetaInfo.fmt_nChannels; j++) { BytesTotal += fread(Sample, sizeof(uint8_t), 3, f); int32_t Word24b = 0x0; for (int k = 2; k >= 0; k--) { Word24b = (Word24b | Sample[k]) << 8; } EachFrame[j] = (float)((double)Word24b / (double)0x80000000); } //if (i >= 0 && i < 8) printf("%f %f\n", EachFrame[0], EachFrame[1]); for (size_t j = 0; j < MetaInfo.fmt_nChannels; j++) { FrameMatrix[i * MetaInfo.fmt_nChannels + j] = EachFrame[j]; } } fclose(f); delete[] EachFrame; return BytesTotal; //printf("total: %d bytes\n", BytesTotal); } float * CsWav::GetFrameMatrix(const char * FilePath) { // wFormatTag == 0x0001 PCM // 0x0003 IEEE_FLOAT // 0x0006 A-LAW // 0x0007 u-LAW // 0xFFFE EXTENSIBLE // // nBlockAlign 4 / 6 / 8 // wBitsPerSample 16 / 24 / 32 if (FrameMatrix != NULL) { return NULL; } size_t MetaInfoBytesAll = ExtractMetaInfo(FilePath); //printf("wav header: %zd bytes\n", MetaInfoBytesAll); //PrintMetaInfo(); // allocation of space for frame matrix FrameMatrix = new float[NumFrame * NumChannel]; if (FrameMatrix == NULL) { printf("wav frame-matrix alloc error!\n"); return NULL; } //else //printf("wav frame-matrix alloc ok.\n"); // dispatch tree based on header info size_t BytesRead = 0; if (MetaInfo.fmt_wFormatTag == 0x0003) { BytesRead = ExtractData_flt(FilePath); fmt = 32; } else if (MetaInfo.fmt_wFormatTag == 0x0001) { if (MetaInfo.fmt_wBitsPerSample == 16) { BytesRead = ExtractData_16b(FilePath); fmt = 16; } else if (MetaInfo.fmt_wBitsPerSample == 24) { BytesRead = ExtractData_24b(FilePath); fmt = 24; } else { printf("PCM Error: bits/sample == %d not supported\n", MetaInfo.fmt_wBitsPerSample); fmt = 0; } } else if ((MetaInfo.fmt_wFormatTag == 0xFFFE) && (MetaInfo.fmt_SubFormat[1] == 0x00) && (MetaInfo.fmt_SubFormat[0] == 0x03)) { BytesRead = ExtractData_flt(FilePath); fmt = 32; } else if ((MetaInfo.fmt_wFormatTag == 0xFFFE) && (MetaInfo.fmt_SubFormat[1] == 0x00) && (MetaInfo.fmt_SubFormat[0] == 0x01)) { if (MetaInfo.fmt_wBitsPerSample == 16) { BytesRead = ExtractData_16b(FilePath); fmt = 16; } else if (MetaInfo.fmt_wBitsPerSample == 24) { BytesRead = ExtractData_24b(FilePath); fmt = 24; } else { printf("PCM Error: bits/sample == %d not supported\n", MetaInfo.fmt_wBitsPerSample); fmt = 0; } } else { printf("Read Error: A-Law / u-Law not supported: %x \n", MetaInfo.fmt_wFormatTag); fmt = 0; } //printf("bytes read from file: %zd\n", BytesRead); return FrameMatrix; } float * CsWav::SetFrameMatrix(size_t nFrame, size_t nChannel, size_t nSampleRate) { if (FrameMatrix != NULL) { return NULL; } NumChannel = nChannel; SampleRate = nSampleRate; NumFrame = nFrame; // allocation of space for frame matrix FrameMatrix = new float[NumFrame * NumChannel]; if (FrameMatrix == NULL) { printf("wav frame-matrix alloc error!\n"); } else { std::memset(FrameMatrix, 0, sizeof(float) * NumFrame * NumChannel); } return FrameMatrix; } // fmt == 16, 16-bit PCM // fmt == 24, 24-bit PCM // fmt == 32, IEEE float void CsWav::MakeMetaInfo(size_t nChannel, size_t nSampleRate, size_t nSample, size_t fmt) { // RIFF MASTER CHUNK MetaInfo.riff_ckID[0] = 'R'; MetaInfo.riff_ckID[1] = 'I'; MetaInfo.riff_ckID[2] = 'F'; MetaInfo.riff_ckID[3] = 'F'; MetaInfo.riff_cksize = 0; //update place holder MetaInfo.riff_waveID[0] = 'W'; MetaInfo.riff_waveID[1] = 'A'; MetaInfo.riff_waveID[2] = 'V'; MetaInfo.riff_waveID[3] = 'E'; // FORMAT CHUNK MetaInfo.fmt_ckID[0] = 'f'; MetaInfo.fmt_ckID[1] = 'm'; MetaInfo.fmt_ckID[2] = 't'; MetaInfo.fmt_ckID[3] = ' '; MetaInfo.fmt_cksize = 18; if (fmt == 32) { MetaInfo.fmt_wFormatTag = 0x0003; } else if (fmt == 16 || fmt == 24) { MetaInfo.fmt_wFormatTag = 0x0001; } else { MetaInfo.fmt_wFormatTag = 0x0000; printf("Error: we don't support formats beyond PCM and FLOAT!\n"); } MetaInfo.fmt_nChannels = (uint16_t)nChannel; MetaInfo.fmt_nSamplesPerSec = nSampleRate; MetaInfo.fmt_nAvgbytesPerSec = nSampleRate * nChannel * (fmt/8); MetaInfo.fmt_nBlockAlign = (uint16_t)(nChannel * (fmt/8)); MetaInfo.fmt_wBitsPerSample = (uint16_t)fmt; MetaInfo.fmt_cbSize = 0; // FACT CHUNK MetaInfo.fact_ckID[0] = 'f'; MetaInfo.fact_ckID[1] = 'a'; MetaInfo.fact_ckID[2] = 'c'; MetaInfo.fact_ckID[3] = 't'; MetaInfo.fact_cksize = 4; MetaInfo.fact_dwSampleLength = 0; //update place holder // DATA CHUNK MetaInfo.data_ckID[0] = 'd'; MetaInfo.data_ckID[1] = 'a'; MetaInfo.data_ckID[2] = 't'; MetaInfo.data_ckID[3] = 'a'; MetaInfo.data_cksize = 0; //update place holder //fill place holder information MetaInfo.riff_cksize = 4 + (8 + 18) + (8 + 4) + (8 + ((fmt/8) * nChannel * nSample)); MetaInfo.fact_dwSampleLength = nSample; MetaInfo.data_cksize = (fmt/8) * nChannel * nSample; } size_t CsWav::SaveMetaInfo(const char * FilePath) { size_t BytesWritten = 0; FILE * f; errno_t Err = fopen_s(&f, FilePath, "wb"); //RIFF header BytesWritten += fwrite(MetaInfo.riff_ckID, sizeof(uint8_t), 4, f); BytesWritten += fwrite(&(MetaInfo.riff_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesWritten += fwrite(MetaInfo.riff_waveID, sizeof(uint8_t), 4, f); //FORMAT header BytesWritten += fwrite(MetaInfo.fmt_ckID, sizeof(uint8_t), 4, f); BytesWritten += fwrite(&(MetaInfo.fmt_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesWritten += fwrite(&(MetaInfo.fmt_wFormatTag), sizeof(uint16_t), 1, f) * sizeof(uint16_t); BytesWritten += fwrite(&(MetaInfo.fmt_nChannels), sizeof(uint16_t), 1, f) * sizeof(uint16_t); BytesWritten += fwrite(&(MetaInfo.fmt_nSamplesPerSec), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesWritten += fwrite(&(MetaInfo.fmt_nAvgbytesPerSec), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesWritten += fwrite(&(MetaInfo.fmt_nBlockAlign), sizeof(uint16_t), 1, f) * sizeof(uint16_t); BytesWritten += fwrite(&(MetaInfo.fmt_wBitsPerSample), sizeof(uint16_t), 1, f) * sizeof(uint16_t); BytesWritten += fwrite(&(MetaInfo.fmt_cbSize), sizeof(uint16_t), 1, f) * sizeof(uint16_t); //FACT header BytesWritten += fwrite(MetaInfo.fact_ckID, sizeof(uint8_t), 4, f); BytesWritten += fwrite(&(MetaInfo.fact_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); BytesWritten += fwrite(&(MetaInfo.fact_dwSampleLength), sizeof(uint32_t), 1, f) * sizeof(uint32_t); //DATA BytesWritten += fwrite(MetaInfo.data_ckID, sizeof(uint8_t), 4, f); BytesWritten += fwrite(&(MetaInfo.data_cksize), sizeof(uint32_t), 1, f) * sizeof(uint32_t); fclose(f); return BytesWritten; } size_t CsWav::Save2File_flt(const char * FilePath) { size_t BytesWritten = 0; MakeMetaInfo(NumChannel, SampleRate, NumFrame, 32); BytesWritten = SaveMetaInfo(FilePath); //add data body float * data = new float[NumChannel]; FILE * f; errno_t Err = fopen_s(&f, FilePath, "ab"); for (size_t i = 0; i < NumFrame; i++) { for (size_t j = 0; j < NumChannel; j++) { data[j] = FrameMatrix[i * NumChannel + j]; } BytesWritten += fwrite(data, sizeof(float), NumChannel, f) * sizeof(float); } fclose(f); delete[] data; return BytesWritten; } size_t CsWav::Save2File_16b(const char * FilePath) { size_t BytesWritten = 0; MakeMetaInfo(NumChannel, SampleRate, NumFrame, 16); BytesWritten = SaveMetaInfo(FilePath); //add data body int16_t * data = new int16_t[NumChannel]; FILE * f; errno_t Err = fopen_s(&f, FilePath, "ab"); for (size_t i = 0; i < NumFrame; i++) { for (size_t j = 0; j < NumChannel; j++) { data[j] = (int16_t)(FrameMatrix[i * NumChannel + j] * 32768.0); } BytesWritten += fwrite(data, sizeof(int16_t), NumChannel, f) * sizeof(int16_t); } fclose(f); delete[] data; return BytesWritten; } size_t CsWav::Save2File_24b(const char * FilePath) { size_t BytesWritten = 0; MakeMetaInfo(NumChannel, SampleRate, NumFrame, 24); BytesWritten = SaveMetaInfo(FilePath); //add data body int32_t data; FILE * f; errno_t Err = fopen_s(&f, FilePath, "ab"); for (size_t i = 0; i < NumFrame; i++) { for (size_t j = 0; j < NumChannel; j++) { data = (int32_t)(FrameMatrix[i * NumChannel + j] * 8388608.0); BytesWritten += fwrite(&data, sizeof(uint8_t), 3, f); } } fclose(f); return BytesWritten; } // the trimmed slice has the same sample rate and number of channels as the input wav file // so we don't use channel or sample rate info here size_t CsWav::Save2File_16b(const char * FilePath, double Start, double Stop) { size_t BytesWritten = 0; // calculate slice to be saved // FrameMatrix[IdxStart][Ch] .. FrameMatrix[IdxStop-1][ch] size_t IdxStart = (size_t)(Start * (double)SampleRate); size_t IdxStop = (size_t)(Stop * (double)SampleRate); if (IdxStart >= IdxStop || IdxStop > NumFrame) { printf("Error: illegal time stamp found!\n"); } MakeMetaInfo(NumChannel, SampleRate, IdxStop - IdxStart, 16); BytesWritten = SaveMetaInfo(FilePath); //add data body int16_t * data = new int16_t[NumChannel]; FILE * f; errno_t Err = fopen_s(&f, FilePath, "ab"); for (size_t i = IdxStart; i < IdxStop; i++) { for (size_t j = 0; j < NumChannel; j++) { data[j] = (int16_t)(FrameMatrix[i * NumChannel + j] * 32768.0); } BytesWritten += fwrite(data, sizeof(int16_t), NumChannel, f) * sizeof(int16_t); } fclose(f); delete[] data; return BytesWritten; } size_t CsWav::Save2File_24b(const char * FilePath, double Start, double Stop) { size_t BytesWritten = 0; // calculate slice to be saved // FrameMatrix[IdxStart][Ch] .. FrameMatrix[IdxStop-1][ch] size_t IdxStart = (size_t)(Start * (double)SampleRate); size_t IdxStop = (size_t)(Stop * (double)SampleRate); if (IdxStart >= IdxStop || IdxStop > NumFrame) { printf("Error: illegal time stamp found!\n"); } MakeMetaInfo(NumChannel, SampleRate, IdxStop - IdxStart, 24); BytesWritten = SaveMetaInfo(FilePath); //add data body int32_t data; FILE * f; errno_t Err = fopen_s(&f, FilePath, "ab"); for (size_t i = IdxStart; i < IdxStop; i++) { for (size_t j = 0; j < NumChannel; j++) { data = (int32_t)(FrameMatrix[i * NumChannel + j] * 8388608.0); BytesWritten += fwrite(&data, sizeof(uint8_t), 3, f); } } fclose(f); return BytesWritten; } size_t CsWav::Save2File_flt(const char * FilePath, double Start, double Stop) { size_t BytesWritten = 0; // calculate slice to be saved // FrameMatrix[IdxStart][Ch] .. FrameMatrix[IdxStop-1][ch] size_t IdxStart = (size_t)(Start * (double)SampleRate); size_t IdxStop = (size_t)(Stop * (double)SampleRate); if (IdxStart >= IdxStop || IdxStop > NumFrame) { printf("Error: illegal time stamp found!\n"); } MakeMetaInfo(NumChannel, SampleRate, IdxStop - IdxStart, 32); BytesWritten = SaveMetaInfo(FilePath); //add data body float * data = new float[NumChannel]; FILE * f; errno_t Err = fopen_s(&f, FilePath, "ab"); for (size_t i = IdxStart; i < IdxStop; i++) { for (size_t j = 0; j < NumChannel; j++) { data[j] = FrameMatrix[i * NumChannel + j]; } BytesWritten += fwrite(data, sizeof(float), NumChannel, f) * sizeof(float); } fclose(f); delete[] data; return BytesWritten; } size_t CsWav::SaveFile(const char * FilePath, double Start, double Stop, size_t BitsPerSample) { size_t BytesWritten; if (BitsPerSample == 16) BytesWritten = Save2File_16b(FilePath, Start, Stop); else if (BitsPerSample == 24) BytesWritten = Save2File_24b(FilePath, Start, Stop); else if (BitsPerSample == 32) BytesWritten = Save2File_flt(FilePath, Start, Stop); else printf("error: BitsPerSample fmt wrong\n"); return BytesWritten; } size_t CsWav::SaveFile(const char * FilePath, size_t BitsPerSample) { size_t BytesWritten; if (BitsPerSample == 16) BytesWritten = Save2File_16b(FilePath); else if (BitsPerSample == 24) BytesWritten = Save2File_24b(FilePath); else if (BitsPerSample == 32) BytesWritten = Save2File_flt(FilePath); else printf("error: BitsPerSample fmt wrong\n"); return BytesWritten; } //2016-11-30 void CsWav::OpenFileDescriptor(const char * FilePath) { // update the meta information size_t MetaInfoTotalBytes = ExtractMetaInfo(FilePath); uint8_t * flush = (uint8_t *)malloc(MetaInfoTotalBytes * sizeof(uint8_t)); // read data out to buffer size_t HeaderBytes; errno_t StreamErr = fopen_s(&StreamFID, FilePath, "rb"); // flush the meta info block HeaderBytes = fread(flush, sizeof(uint8_t), MetaInfoTotalBytes, StreamFID); free(flush); } float * CsWav::OpenStreamFrom(const char * FilePath) { // wFormatTag == 0x0001 PCM // 0x0003 IEEE_FLOAT // 0x0006 A-LAW // 0x0007 u-LAW // 0xFFFE EXTENSIBLE // // nBlockAlign 4 / 6 / 8 // wBitsPerSample 16 / 24 / 32 if (FrameVector != NULL) { return NULL; } size_t MetaInfoBytesAll = ExtractMetaInfo(FilePath); printf("wav header: %zd bytes\n", MetaInfoBytesAll); //PrintMetaInfo(); // allocation of space for frame matrix FrameVector = new float[NumChannel]; if (FrameVector == NULL) { printf("wav frame-vector alloc error!\n"); return NULL; } else printf("wav frame-vector alloc ok.\n"); // dispatch tree based on header info if (MetaInfo.fmt_wFormatTag == 0x0003) { OpenFileDescriptor(FilePath); fmt = 32; } else if (MetaInfo.fmt_wFormatTag == 0x0001) { if (MetaInfo.fmt_wBitsPerSample == 16) { OpenFileDescriptor(FilePath); fmt = 16; } else if (MetaInfo.fmt_wBitsPerSample == 24) { OpenFileDescriptor(FilePath); fmt = 24; } else { printf("pcm error: bits/sample == %d not supported\n", MetaInfo.fmt_wBitsPerSample); fmt = 0; } } else if ((MetaInfo.fmt_wFormatTag == 0xFFFE) && (MetaInfo.fmt_SubFormat[1] == 0x00) && (MetaInfo.fmt_SubFormat[0] == 0x03)) { OpenFileDescriptor(FilePath); fmt = 32; } else if ((MetaInfo.fmt_wFormatTag == 0xFFFE) && (MetaInfo.fmt_SubFormat[1] == 0x00) && (MetaInfo.fmt_SubFormat[0] == 0x01)) { if (MetaInfo.fmt_wBitsPerSample == 16) { OpenFileDescriptor(FilePath); fmt = 16; } else if (MetaInfo.fmt_wBitsPerSample == 24) { OpenFileDescriptor(FilePath); fmt = 24; } else { printf("pcm error: bits/sample == %d not supported\n", MetaInfo.fmt_wBitsPerSample); fmt = 0; } } else { printf("read error: A-Law / u-Law not supported: %x \n", MetaInfo.fmt_wFormatTag); fmt = 0; } printf("stream opened.\n"); //reset the stream frame counter StreamFrameCounter = 0; return FrameVector; } float * CsWav::OpenStreamTo(const char * FilePath, size_t nFrame, size_t nChannel, size_t nSampleRate, size_t BitsPerSample) { NumChannel = nChannel; SampleRate = nSampleRate; NumFrame = nFrame; fmt = BitsPerSample; size_t BytesWritten = 0; MakeMetaInfo(NumChannel, SampleRate, NumFrame, fmt); BytesWritten = SaveMetaInfo(FilePath); errno_t StreamError = fopen_s(&StreamFID, FilePath, "ab"); StreamFrameCounter = 0; FrameVector = new float[NumChannel]; if (FrameVector == NULL) { printf("wav frame-vector alloc error!\n"); return NULL; } else printf("wav frame-vector alloc ok.\n"); return FrameVector; } void CsWav::CloseStream() { if(StreamFID) fclose(StreamFID); } void CsWav::ExtractFrame_16b() { size_t EleRead = fread(SampleInt16, sizeof(int16_t), MetaInfo.fmt_nChannels, StreamFID); if (EleRead != MetaInfo.fmt_nChannels) printf("read error at frame %d\n", StreamFrameCounter); for (size_t j = 0; j < MetaInfo.fmt_nChannels; j++) FrameVector[j] = (float)((double)SampleInt16[j] / (double)32768); } void CsWav::ExtractFrame_24b() { uint8_t Sample24b[3]; for (size_t j = 0; j < MetaInfo.fmt_nChannels; j++) { size_t EleRead = fread(Sample24b, sizeof(uint8_t), 3, StreamFID); if (EleRead != 3) printf("read error at frame %d\n", StreamFrameCounter); int32_t Word24b = 0x0; for (int k = 2; k >= 0; k--) { Word24b = (Word24b | Sample24b[k]) << 8; } FrameVector[j] = (float)((double)Word24b / (double)0x80000000); } } void CsWav::ExtractFrame_flt() { //read pcm frame to framevector size_t EleRead = fread(FrameVector, sizeof(float), MetaInfo.fmt_nChannels, StreamFID); if (EleRead != MetaInfo.fmt_nChannels) printf("read error at frame %d\n", StreamFrameCounter); } void CsWav::ReadFrameFromStream() { if (fmt == 32) ExtractFrame_flt(); else if (fmt == 24) ExtractFrame_24b(); else if (fmt == 16) ExtractFrame_16b(); else printf("fmt error: %d\n", fmt); StreamFrameCounter += 1; } void CsWav::SaveFrame_16b() { size_t EleWritten; for (size_t j = 0; j < NumChannel; j++) { SampleInt16[j] = (int16_t)(FrameVector[j] * 32768.0); } EleWritten = fwrite(SampleInt16, sizeof(int16_t), NumChannel, StreamFID); if (EleWritten != NumChannel) printf("write error at frame %d\n", StreamFrameCounter); } void CsWav::SaveFrame_24b() { size_t EleWritten; int32_t data; for (size_t j = 0; j < NumChannel; j++) { data = (int32_t)(FrameVector[j] * 8388608.0); EleWritten = fwrite(&data, sizeof(uint8_t), 3, StreamFID); if (EleWritten != 3) printf("write error at frame %d\n", StreamFrameCounter); } } void CsWav::SaveFrame_flt() { size_t EleWritten = 0; EleWritten = fwrite(FrameVector, sizeof(float), NumChannel, StreamFID); if (EleWritten != NumChannel) printf("write error at frame %d\n", StreamFrameCounter); } void CsWav::WriteFrameToStream() { if (fmt == 32) SaveFrame_flt(); else if (fmt == 24) SaveFrame_24b(); else if (fmt == 16) SaveFrame_16b(); else printf("fmt error: %d\n", fmt); StreamFrameCounter += 1; } float * CsWav::GetFrameVector() { return FrameVector; }
28.137725
143
0.658332
[ "vector" ]
3a8eb6d8e97c2e6451ca9a7fb5666b1c3fc0bb3e
9,646
cpp
C++
src/reaction/reactionBase.cpp
myrabiedermann/rsmd
97ccc65dbb3d9d16e5e6a88f256d97a36c511740
[ "Apache-2.0" ]
2
2021-01-30T00:30:32.000Z
2021-04-20T11:54:53.000Z
src/reaction/reactionBase.cpp
myrabiedermann/rsmd
97ccc65dbb3d9d16e5e6a88f256d97a36c511740
[ "Apache-2.0" ]
null
null
null
src/reaction/reactionBase.cpp
myrabiedermann/rsmd
97ccc65dbb3d9d16e5e6a88f256d97a36c511740
[ "Apache-2.0" ]
null
null
null
/************************************************ * * * rs@md * * (reactive steps @ molecular dynamics ) * * * ************************************************/ /* Copyright 2020 Myra Biedermann Licensed under the Apache License, Version 2.0 */ #include "reactionBase.hpp" // // copy constructor // ReactionBase::ReactionBase(const ReactionBase& other) : name(other.name) , reactants(other.reactants) , products(other.products) , transitionTables(other.transitionTables) , translationTables(other.translationTables) , reactionEnergy(other.reactionEnergy) , activationEnergy(other.activationEnergy) , reactionRate(other.reactionRate) { for( auto& c: other.criterions ) { criterions.push_back(c->clone()); } } const auto ReactionBase::getReactant(const std::size_t& molid) const { // attention: returns first molecule that matches molid (assumes that molid is unique) auto it = std::find_if( std::begin(reactants), std::end(reactants), [&molid](auto& m){ return molid == m.getID(); } ); if( it == std::end(reactants) ) rsmdCRITICAL("couldn't find molecule in reactants: " << molid); return std::cref(*it); } const auto ReactionBase::getProduct(const std::size_t& molid) const { // attention: returns first molecule that matches molid (assumes that molid is unique) auto it = std::find_if( std::begin(products), std::end(products), [&molid](auto& m){ return molid == m.getID(); } ); if( it == std::end(products) ) rsmdCRITICAL("couldn't find molecule in products: " << molid); return std::cref(*it); } Molecule& ReactionBase::getAddReactant(const std::size_t& molid) { auto it = std::find_if( std::begin(reactants), std::end(reactants), [&molid](auto& m){ return molid == m.getID(); }); if( it == std::end(reactants) ) { it = reactants.emplace(std::end(reactants)); it->setID(molid); } return std::ref(*it); } Molecule& ReactionBase::getAddProduct(const std::size_t& molid) { auto it = std::find_if( std::begin(products), std::end(products), [&molid](auto& m){ return molid == m.getID(); }); if( it == std::end(products) ) { it = products.emplace(std::end(products)); it->setID(molid); } return std::ref(*it); } void ReactionBase::addTransition(const std::size_t& oldMolix, const std::size_t& oldix, const std::size_t& newMolix, const std::size_t& newix) { transitionTables.emplace_back(oldMolix, oldix, newMolix, newix); } void ReactionBase::addCriterion(const std::vector<std::pair<std::size_t, std::size_t>>& ixList, const std::pair<REAL, REAL>& thresholds) { auto it = criterions.end(); if( ixList.size() == 2 ) { it = criterions.emplace( std::end(criterions), std::make_unique<CriterionDistance>() ); } else if( ixList.size() == 3 ) { it = criterions.emplace( std::end(criterions),std::make_unique<CriterionAngle>() ); } else if( ixList.size() == 4 ) { it = criterions.emplace( std::end(criterions), std::make_unique<CriterionDihedral>() ); } else { rsmdCRITICAL("no criterion involving more than 4 atoms has been implemented yet"); } for(auto ix: ixList) it->get()->addAtomIndices(ix); it->get()->setThresholds(thresholds ); } void ReactionBase::addTranslation(const std::vector<std::pair<std::size_t, std::size_t>>& indices, const REAL& value) { assert(indices.size() == 2); translationTables.emplace_back(indices[0], indices[1], value); } // // consistency check: // - check that at least one reactant molecule is listed // - check that at least one product molecule is listed // - check that at least one criterion of type 'distance' is listed // (and is the first criterion, i.e. index 0) // - check if all atoms named in transitionTables or // within criterions actually exist within reactants/products // void ReactionBase::consistencyCheck() const { // check reactants / products if( reactants.size() == 0 ) { rsmdEXIT( "error in input: no reactant molecule was found" ); } if( products.size() == 0 ) { rsmdEXIT( "error in input: no product molecule was found" ); } // check for distance criterion if( criterions[0]->getType() != "distance" ) { rsmdEXIT( "error in input: the first listed criterion needs to be a distance" ); } // check for consistency within reactants/products/transitionTables for( const auto& tt: transitionTables ) { if( tt.oldMolix >= reactants.size() ) { rsmdEXIT( "error in input directive [products]: given atom (" << tt.oldMolix + 1 << ", " << tt.oldix + 1 << ") doesn't exist in reactants"); } else if( tt.oldix >= reactants[tt.oldMolix].size() ) { rsmdEXIT( "error in input directive [products]: given atom (" << tt.oldMolix + 1 << ", " << tt.oldix + 1 << ") doesn't exist in reactants"); } if( tt.newMolix >= products.size() ) { rsmdEXIT( "error in input directive [products]: given atom (" << tt.newMolix + 1 << ", " << tt.newix + 1 << ") doesn't exist in products"); } else if( tt.newix >= products[tt.newMolix].size() ) { rsmdEXIT( "error in input directive [products]: given atom (" << tt.newMolix + 1 << ", " << tt.newix + 1 << ") doesn't exist in products"); } } // check for consistency within reactants/products/movementTables for( const auto& tt: translationTables ) { if( tt.indices1.first >= products.size() ) { rsmdEXIT( "error in input directive [translations]: given atom (" << tt.indices1.first + 1 << ", " << tt.indices1.second + 1 << ") doesn't exist in products"); } else if( tt.indices1.second >= products[tt.indices1.first].size() ) { rsmdEXIT( "error in input directive [translations]: given atom (" << tt.indices1.first + 1 << ", " << tt.indices1.second + 1 << ") doesn't exist in products"); } if( tt.indices2.first >= products.size() ) { rsmdEXIT( "error in input directive [translations]: given atom (" << tt.indices2.first + 1 << ", " << tt.indices2.second + 1 << ") doesn't exist in products"); } else if( tt.indices2.second >= products[tt.indices2.first].size() ) { rsmdEXIT( "error in input directive [translations]: given atom (" << tt.indices2.first + 1 << ", " << tt.indices2.second + 1 << ") doesn't exist in products"); } } // check for consistency within reactants/products/criterions for( const auto& criterion: criterions ) { for( const auto& ixs: *criterion ) { if( ixs.first >= reactants.size() ) { rsmdEXIT( "error in input directive [criterions]: given atom (" << ixs.first + 1 << ", " << ixs.second + 1 << ") doesn't exist in reactants" ); } else if ( ixs.second >= reactants[ixs.first].size() ) { rsmdEXIT( "error in input directive [criterions]: given atom (" << ixs.first + 1 << ", " << ixs.second + 1 << ") doesn't exist in reactants" ); } } if( criterion->getMin() >= criterion->getMax() ) { rsmdEXIT( "error in input directive [criterions]: it seems that you have interchanged minimum and maximum value" ); } } } // // write info in a string // std::string ReactionBase::str() const { std::stringstream stream; stream << "<Reaction '" << name << "', \n"; stream << rsmdALL_formatting << " reactants: "; for(const auto& mol: reactants) { stream << mol.getID() << " " << mol.getName() << ", "; } stream << '\n'; stream << rsmdALL_formatting << " products: "; for(const auto& mol: products) stream << mol.getID() << " " << mol.getName() << ", "; stream << '\n'; // add +1 for indices in translation tables, movement tables and criterion templates // to match numbering in input files stream << rsmdALL_formatting << " transitions reactant -> product: "; for(const auto& tt: transitionTables) stream << "\n (" << tt.oldMolix + 1 << ", " << tt.oldix + 1 << ") -> (" << tt.newMolix + 1 << ", " << tt.newix + 1 << ") "; stream << '\n'; stream << rsmdALL_formatting << " translational movements: "; for(const auto& mt: translationTables) { stream << "\n (" << mt.indices1.first + 1 << ", " << mt.indices1.second + 1 << ") (" << mt.indices2.first + 1 << ", " << mt.indices2.second + 1 << ") " << mt.value; } stream << '\n'; stream << rsmdALL_formatting << " criterions: "; for(const auto& c: criterions) { stream << "\n "; for(const auto& pair: *c) stream << "(" << pair.first + 1 << ", " << pair.second + 1 << ") "; stream << "[" << c->getMin() << ", " << c->getMax() << "]"; } stream << '\n'; stream << rsmdALL_formatting << " reaction energy: " << reactionEnergy << '\n'; stream << rsmdALL_formatting << " activation energy: " << activationEnergy << '\n'; stream << rsmdALL_formatting << " rate: "; for(const auto& r: reactionRate) stream << "\n " << r.first << " " << r.second; stream << '\n'; stream << rsmdALL_formatting << ">"; return stream.str(); }
37.243243
185
0.571429
[ "vector" ]
3a8f696f411154458448025c25aa378e2c75edc0
9,735
cpp
C++
src/unicode_cpp_generator.cpp
StableCoder/unicode-hpp
e701f30d7cecafaa53cf1f499593b61f30b9e006
[ "MIT" ]
3
2019-05-22T04:29:44.000Z
2022-01-22T06:27:49.000Z
src/unicode_cpp_generator.cpp
StableCoder/unicode-hpp
e701f30d7cecafaa53cf1f499593b61f30b9e006
[ "MIT" ]
null
null
null
src/unicode_cpp_generator.cpp
StableCoder/unicode-hpp
e701f30d7cecafaa53cf1f499593b61f30b9e006
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2017-2018 George Cave - gcave@stablecoder.ca * * 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. * */ // RapidXML #include <rapidxml-1.13/rapidxml.hpp> // C++ #include <algorithm> #include <cstring> #include <fstream> #include <iostream> #include <locale> #include <string> #include <vector> struct Unicode_block_data { std::string name; uint32_t start; uint32_t end; }; const char *description_str = "/* This header was auto-generated by the UnicodeHPP (Unicode C++ Header Generator)\n" " * that is located at https://github.com/stablecoder/unicode-hpp or\n" " * https://git.stabletec.com/utilities/unicode-hpp\n" " *\n" " * Check for an updated version anytime, or state concerns/bugs.\n" " */\n"; const char *help_str = "This program builds a quick Unicode header for use in C++11 or\n" "higher programs. It lists all unicode blocks, and their starting\n" "and ending code points." "\nProgram Arguments:" "\n -h, --help : Help Blurb" "\n -b, --blocksize : Also builds a function enumerating each block's size, rather" "\n than calculating it." "\n -f <filename> : The input file to build the unicode block from." "\n Must be an XML from Unicode org, such as from" "\n http://www.unicode.org/Public/9.0.0/ucdxml/ for 9.0.0" "\n -o <out_dir> : This is the directory where the file unicode_blocks_#.hpp" "\n will be written to."; int main(int argc, const char **argv) { std::string input_file = ""; std::string output_dir = "./"; bool include_block_size = false; // Run through the args for (int idx = 0; idx < argc; ++idx) { if (strcmp(argv[idx], "--help") == 0 || strcmp(argv[idx], "-h") == 0) { // Spit out the help std::cout << help_str << std::endl; return 0; } if (strcmp(argv[idx], "--blocksize") == 0 || strcmp(argv[idx], "-b") == 0) { include_block_size = true; } if (strcmp(argv[idx], "-f") == 0) { if (idx + 1 <= argc) { input_file = argv[idx + 1]; } } if (strcmp(argv[idx], "-o") == 0) { if (idx + 1 <= argc) { output_dir = argv[idx + 1]; } } } if (input_file == "") { std::cerr << "Error: No input file given. Type --help for help." << std::endl; return 1; } // In order to parse a file, we need to load the whole thing into memory. std::ifstream in_file(input_file.c_str(), std::ifstream::in); if (!in_file.is_open()) { std::cerr << "Error: Failed to open file " << input_file << std::endl; return 1; } // Seek to the end. in_file.seekg(0, std::ifstream::end); // Tell us how many chars to set aside. std::size_t fileSize = in_file.tellg(); // Create a buffer large enough to hold the whole file. char *unicode_file = new char[fileSize]; // Seek back the beginning in_file.seekg(0, std::ifstream::beg); // Read in the file. in_file.read(unicode_file, fileSize); // We're done with the raw file now. in_file.close(); // Begin the XML parsing. rapidxml::xml_document<> unicode_doc; unicode_doc.parse<0>(unicode_file); // Only base-level node should be <ucd> rapidxml::xml_node<> *ucdNode = unicode_doc.first_node("ucd"); if (ucdNode == nullptr) { std::cerr << "Error: No <ucd> base-level tag found. Invalid Unicode Block XML file." << std::endl; return 1; } /// Get the Unicode Version std::string unicode_vers = ""; rapidxml::xml_node<> *descriptionNode = ucdNode->first_node("description"); unicode_vers = descriptionNode->value(); std::cout << "Parsing Unicode Version " << unicode_vers << std::endl; // Format the version number std::replace(unicode_vers.begin(), unicode_vers.end(), '.', '_'); unicode_vers = unicode_vers.substr(unicode_vers.find_last_of(' ') + 1); // Search for Blocks rapidxml::xml_node<> *blockNode = ucdNode->first_node("blocks"); if (blockNode == nullptr) { std::cerr << "Error: No Unicode Blocks described in file." << std::endl; return 1; } /// Collect Block Data std::vector<Unicode_block_data> unicode_blocks; rapidxml::xml_node<> *block_data_node = blockNode->first_node(); while (true) { Unicode_block_data data; data.name = block_data_node->first_attribute("name")->value(); data.start = strtol(block_data_node->first_attribute("first-cp")->value(), NULL, 16); data.end = strtol(block_data_node->first_attribute("last-cp")->value(), NULL, 16); unicode_blocks.push_back(data); if (block_data_node != blockNode->last_node()) { block_data_node = block_data_node->next_sibling(); } else { break; } } // All done, free the file data. delete[] unicode_file; /// Write Header // Now we proceed forward. if (output_dir[output_dir.size() - 1] != '/' && output_dir[output_dir.size() - 1] != '\\') { output_dir += '/'; } std::ofstream out_file(output_dir + "unicode_blocks_" + unicode_vers + ".hpp", std::ofstream::out); if (!out_file.is_open()) { std::cerr << "Error: Failed to open header for writing: " << output_dir << "unicode_blocks_" << unicode_vers << ".hpp"; return 1; } // First, write the license disclaimer. out_file << description_str; // Next, the definition lines. out_file << "\n\n#ifndef UNICODE_BLOCKS_HPP\n" << "#define UNICODE_BLOCKS_HPP" << std::endl; // Headers out_file << "\n#include <cstdint>"; // namespace out_file << "\n\nnamespace unicode {"; // Set the Unicode Version String out_file << "\n\n// The Unicode Version this is based on.\nconst char* version_str = \"" << unicode_vers << "\";"; // Set the Unicode Block Enums out_file << "\n\nenum class Block : uint32_t {"; for (auto iter = unicode_blocks.begin(); iter != unicode_blocks.end(); ++iter) { // For each block, replace spaces and dashes with underscores. std::replace(iter->name.begin(), iter->name.end(), ' ', '_'); std::replace(iter->name.begin(), iter->name.end(), '-', '_'); // Now, write the enum name out. out_file << "\n " << iter->name << ','; } out_file << "\n};"; // Now we build the unicode block start function out_file << std::hex << std::uppercase; out_file << "\n\nconstexpr uint32_t getFirstCodePoint(Block unicode_block) {"; out_file << "\n switch(unicode_block) {"; for (auto iter = unicode_blocks.begin(); iter != unicode_blocks.end(); ++iter) { out_file << "\n case Block::" << iter->name << " :"; out_file << "\n return 0x" << iter->start << ';'; } out_file << "\n }"; out_file << "\n}"; // Now we build the Unicode block end function out_file << "\n\nconstexpr uint32_t getLastCodePoint(Block unicode_block) {"; out_file << "\n switch(unicode_block) {"; for (auto iter = unicode_blocks.begin(); iter != unicode_blocks.end(); ++iter) { out_file << "\n case Block::" << iter->name << " :"; out_file << "\n return 0x" << iter->end << ';'; } out_file << "\n }"; out_file << "\n}"; if (include_block_size) { // Only add block size enumeration if requested. out_file << std::dec; out_file << "\n\nconstexpr uint32_t getBlockSize(Block unicode_block) {"; out_file << "\n switch(unicode_block) {"; for (auto iter = unicode_blocks.begin(); iter != unicode_blocks.end(); ++iter) { out_file << "\n case Block::" << iter->name << " :"; out_file << "\n return " << (iter->end - iter->start + 1) << ';'; } out_file << "\n }"; out_file << "\n}"; } else { // just give the basic calculating function instead. out_file << "\n\nconstexpr uint32_t getBlockSize(Block unicode_block) {"; out_file << "\n return getLastCodePoint(unicode_block) - getFirstCodePoint(unicode_block);"; out_file << "\n}"; } // End namespace out_file << "\n\n};"; // The #endif statement out_file << "\n\n\n#endif // UNICODE_BLOCKS_HPP"; // Close the file. out_file.close(); std::cout << ""; return 0; }
36.324627
127
0.591474
[ "vector" ]
3a9318b83fc8e4a9da24e702942d987cad5e93a3
21,755
cc
C++
content/browser/service_worker/service_worker_client_utils.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-05-24T13:52:28.000Z
2021-05-24T13:53:10.000Z
content/browser/service_worker/service_worker_client_utils.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/service_worker/service_worker_client_utils.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-03-12T07:58:10.000Z
2019-08-31T04:53:58.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/service_worker/service_worker_client_utils.h" #include <algorithm> #include <tuple> #include "base/location.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/browser/service_worker/service_worker_context_core.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_provider_host.h" #include "content/browser/service_worker/service_worker_version.h" #include "content/browser/storage_partition_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/service_worker/service_worker_client_info.h" #include "content/common/service_worker/service_worker_types.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/common/child_process_host.h" #include "url/gurl.h" namespace content { namespace service_worker_client_utils { namespace { using OpenURLCallback = base::Callback<void(int, int)>; using GetWindowClientsCallback = base::Callback<void(std::unique_ptr<ServiceWorkerClients>)>; // The OpenURLObserver class is a WebContentsObserver that will wait for a // WebContents to be initialized, run the |callback| passed to its constructor // then self destroy. // The callback will receive the process and frame ids. If something went wrong // those will be (kInvalidUniqueID, MSG_ROUTING_NONE). // The callback will be called in the IO thread. class OpenURLObserver : public WebContentsObserver { public: OpenURLObserver(WebContents* web_contents, int frame_tree_node_id, const OpenURLCallback& callback) : WebContentsObserver(web_contents), frame_tree_node_id_(frame_tree_node_id), callback_(callback) {} void DidFinishNavigation(NavigationHandle* navigation_handle) override { DCHECK(web_contents()); if (!navigation_handle->HasCommitted()) { // Return error. RunCallback(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE); return; } if (navigation_handle->GetFrameTreeNodeId() != frame_tree_node_id_) { // Return error. RunCallback(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE); return; } RenderFrameHost* render_frame_host = navigation_handle->GetRenderFrameHost(); RunCallback(render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); } void RenderProcessGone(base::TerminationStatus status) override { RunCallback(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE); } void WebContentsDestroyed() override { RunCallback(ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE); } private: void RunCallback(int render_process_id, int render_frame_id) { // After running the callback, |this| will stop observing, thus // web_contents() should return nullptr and |RunCallback| should no longer // be called. Then, |this| will self destroy. DCHECK(web_contents()); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(callback_, render_process_id, render_frame_id)); Observe(nullptr); base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } int frame_tree_node_id_; const OpenURLCallback callback_; DISALLOW_COPY_AND_ASSIGN(OpenURLObserver); }; ServiceWorkerClientInfo GetWindowClientInfoOnUI( int render_process_id, int render_frame_id, base::TimeTicks create_time, const std::string& client_uuid) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* render_frame_host = RenderFrameHostImpl::FromID(render_process_id, render_frame_id); if (!render_frame_host) return ServiceWorkerClientInfo(); // TODO(mlamouri,michaeln): it is possible to end up collecting information // for a frame that is actually being navigated and isn't exactly what we are // expecting. return ServiceWorkerClientInfo( client_uuid, render_frame_host->GetVisibilityState(), render_frame_host->IsFocused(), render_frame_host->GetLastCommittedURL(), render_frame_host->GetParent() ? REQUEST_CONTEXT_FRAME_TYPE_NESTED : REQUEST_CONTEXT_FRAME_TYPE_TOP_LEVEL, render_frame_host->frame_tree_node()->last_focus_time(), create_time, blink::kWebServiceWorkerClientTypeWindow); } ServiceWorkerClientInfo FocusOnUI(int render_process_id, int render_frame_id, base::TimeTicks create_time, const std::string& client_uuid) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* render_frame_host = RenderFrameHostImpl::FromID(render_process_id, render_frame_id); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>( WebContents::FromRenderFrameHost(render_frame_host)); if (!render_frame_host || !web_contents) return ServiceWorkerClientInfo(); FrameTreeNode* frame_tree_node = render_frame_host->frame_tree_node(); // Focus the frame in the frame tree node, in case it has changed. frame_tree_node->frame_tree()->SetFocusedFrame( frame_tree_node, render_frame_host->GetSiteInstance()); // Focus the frame's view to make sure the frame is now considered as focused. render_frame_host->GetView()->Focus(); // Move the web contents to the foreground. web_contents->Activate(); return GetWindowClientInfoOnUI(render_process_id, render_frame_id, create_time, client_uuid); } // This is only called for main frame navigations in OpenWindowOnUI(). void DidOpenURLOnUI(const OpenURLCallback& callback, WebContents* web_contents) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!web_contents) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(callback, ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); return; } // ContentBrowserClient::OpenURL calls ui::BaseWindow::Show which // makes the destination window the main+key window, but won't make Chrome // the active application (https://crbug.com/470830). Since OpenWindow is // always called from a user gesture (e.g. notification click), we should // explicitly activate the window, which brings Chrome to the front. static_cast<WebContentsImpl*>(web_contents)->Activate(); RenderFrameHostImpl* rfhi = static_cast<RenderFrameHostImpl*>(web_contents->GetMainFrame()); new OpenURLObserver(web_contents, rfhi->frame_tree_node()->frame_tree_node_id(), callback); } void OpenWindowOnUI( const GURL& url, const GURL& script_url, int worker_process_id, const scoped_refptr<ServiceWorkerContextWrapper>& context_wrapper, WindowOpenDisposition disposition, const OpenURLCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserContext* browser_context = context_wrapper->storage_partition() ? context_wrapper->storage_partition()->browser_context() : nullptr; // We are shutting down. if (!browser_context) return; RenderProcessHost* render_process_host = RenderProcessHost::FromID(worker_process_id); if (render_process_host->IsForGuestsOnly()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(callback, ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); return; } OpenURLParams params( url, Referrer::SanitizeForRequest( url, Referrer(script_url, blink::kWebReferrerPolicyDefault)), disposition, ui::PAGE_TRANSITION_AUTO_TOPLEVEL, true /* is_renderer_initiated */); GetContentClient()->browser()->OpenURL(browser_context, params, base::Bind(&DidOpenURLOnUI, callback)); } void NavigateClientOnUI(const GURL& url, const GURL& script_url, int process_id, int frame_id, const OpenURLCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* rfhi = RenderFrameHostImpl::FromID(process_id, frame_id); WebContents* web_contents = WebContents::FromRenderFrameHost(rfhi); if (!rfhi || !web_contents) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(callback, ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); return; } ui::PageTransition transition = rfhi->GetParent() ? ui::PAGE_TRANSITION_AUTO_SUBFRAME : ui::PAGE_TRANSITION_AUTO_TOPLEVEL; int frame_tree_node_id = rfhi->frame_tree_node()->frame_tree_node_id(); OpenURLParams params( url, Referrer::SanitizeForRequest( url, Referrer(script_url, blink::kWebReferrerPolicyDefault)), frame_tree_node_id, WindowOpenDisposition::CURRENT_TAB, transition, true /* is_renderer_initiated */); web_contents->OpenURL(params); new OpenURLObserver(web_contents, frame_tree_node_id, callback); } void DidNavigate(const base::WeakPtr<ServiceWorkerContextCore>& context, const GURL& origin, const NavigationCallback& callback, int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!context) { callback.Run(SERVICE_WORKER_ERROR_ABORT, ServiceWorkerClientInfo()); return; } if (render_process_id == ChildProcessHost::kInvalidUniqueID && render_frame_id == MSG_ROUTING_NONE) { callback.Run(SERVICE_WORKER_ERROR_FAILED, ServiceWorkerClientInfo()); return; } for (std::unique_ptr<ServiceWorkerContextCore::ProviderHostIterator> it = context->GetClientProviderHostIterator(origin); !it->IsAtEnd(); it->Advance()) { ServiceWorkerProviderHost* provider_host = it->GetProviderHost(); if (provider_host->process_id() != render_process_id || provider_host->frame_id() != render_frame_id) { continue; } BrowserThread::PostTaskAndReplyWithResult( BrowserThread::UI, FROM_HERE, base::Bind(&GetWindowClientInfoOnUI, provider_host->process_id(), provider_host->route_id(), provider_host->create_time(), provider_host->client_uuid()), base::Bind(callback, SERVICE_WORKER_OK)); return; } // If here, it means that no provider_host was found, in which case, the // renderer should still be informed that the window was opened. callback.Run(SERVICE_WORKER_OK, ServiceWorkerClientInfo()); } void AddWindowClient( ServiceWorkerProviderHost* host, std::vector<std::tuple<int, int, base::TimeTicks, std::string>>* client_info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (host->client_type() != blink::kWebServiceWorkerClientTypeWindow) return; client_info->push_back(std::make_tuple(host->process_id(), host->frame_id(), host->create_time(), host->client_uuid())); } void AddNonWindowClient(ServiceWorkerProviderHost* host, const ServiceWorkerClientQueryOptions& options, ServiceWorkerClients* clients) { DCHECK_CURRENTLY_ON(BrowserThread::IO); blink::WebServiceWorkerClientType host_client_type = host->client_type(); if (host_client_type == blink::kWebServiceWorkerClientTypeWindow) return; if (options.client_type != blink::kWebServiceWorkerClientTypeAll && options.client_type != host_client_type) return; ServiceWorkerClientInfo client_info( host->client_uuid(), blink::kWebPageVisibilityStateHidden, false, // is_focused host->document_url(), REQUEST_CONTEXT_FRAME_TYPE_NONE, base::TimeTicks(), host->create_time(), host_client_type); clients->push_back(client_info); } void OnGetWindowClientsOnUI( // The tuple contains process_id, frame_id, create_time, client_uuid. const std::vector<std::tuple<int, int, base::TimeTicks, std::string>>& clients_info, const GURL& script_url, const GetWindowClientsCallback& callback, std::unique_ptr<ServiceWorkerClients> clients) { DCHECK_CURRENTLY_ON(BrowserThread::UI); for (const auto& it : clients_info) { ServiceWorkerClientInfo info = GetWindowClientInfoOnUI( std::get<0>(it), std::get<1>(it), std::get<2>(it), std::get<3>(it)); // If the request to the provider_host returned an empty // ServiceWorkerClientInfo, that means that it wasn't possible to associate // it with a valid RenderFrameHost. It might be because the frame was killed // or navigated in between. if (info.IsEmpty()) continue; // We can get info for a frame that was navigating end ended up with a // different URL than expected. In such case, we should make sure to not // expose cross-origin WindowClient. if (info.url.GetOrigin() != script_url.GetOrigin()) continue; clients->push_back(info); } BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(callback, base::Passed(&clients))); } struct ServiceWorkerClientInfoSort { bool operator()(const ServiceWorkerClientInfo& a, const ServiceWorkerClientInfo& b) const { // Clients for windows should be appeared earlier. if (a.client_type == blink::kWebServiceWorkerClientTypeWindow && b.client_type != blink::kWebServiceWorkerClientTypeWindow) { return true; } if (a.client_type != blink::kWebServiceWorkerClientTypeWindow && b.client_type == blink::kWebServiceWorkerClientTypeWindow) { return false; } // Clients focused recently should be appeared earlier. if (a.last_focus_time != b.last_focus_time) return a.last_focus_time > b.last_focus_time; // Clients created before should be appeared earlier. return a.create_time < b.create_time; } }; void DidGetClients(const ClientsCallback& callback, std::unique_ptr<ServiceWorkerClients> clients) { DCHECK_CURRENTLY_ON(BrowserThread::IO); std::sort(clients->begin(), clients->end(), ServiceWorkerClientInfoSort()); callback.Run(std::move(clients)); } void GetNonWindowClients(const base::WeakPtr<ServiceWorkerVersion>& controller, const ServiceWorkerClientQueryOptions& options, const ClientsCallback& callback, std::unique_ptr<ServiceWorkerClients> clients) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!options.include_uncontrolled) { for (auto& controllee : controller->controllee_map()) AddNonWindowClient(controllee.second, options, clients.get()); } else if (controller->context()) { GURL origin = controller->script_url().GetOrigin(); for (auto it = controller->context()->GetClientProviderHostIterator(origin); !it->IsAtEnd(); it->Advance()) { AddNonWindowClient(it->GetProviderHost(), options, clients.get()); } } DidGetClients(callback, std::move(clients)); } void DidGetWindowClients(const base::WeakPtr<ServiceWorkerVersion>& controller, const ServiceWorkerClientQueryOptions& options, const ClientsCallback& callback, std::unique_ptr<ServiceWorkerClients> clients) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (options.client_type == blink::kWebServiceWorkerClientTypeAll) { GetNonWindowClients(controller, options, callback, std::move(clients)); return; } DidGetClients(callback, std::move(clients)); } void GetWindowClients(const base::WeakPtr<ServiceWorkerVersion>& controller, const ServiceWorkerClientQueryOptions& options, const ClientsCallback& callback, std::unique_ptr<ServiceWorkerClients> clients) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(options.client_type == blink::kWebServiceWorkerClientTypeWindow || options.client_type == blink::kWebServiceWorkerClientTypeAll); std::vector<std::tuple<int, int, base::TimeTicks, std::string>> clients_info; if (!options.include_uncontrolled) { for (auto& controllee : controller->controllee_map()) AddWindowClient(controllee.second, &clients_info); } else if (controller->context()) { GURL origin = controller->script_url().GetOrigin(); for (auto it = controller->context()->GetClientProviderHostIterator(origin); !it->IsAtEnd(); it->Advance()) { AddWindowClient(it->GetProviderHost(), &clients_info); } } if (clients_info.empty()) { DidGetWindowClients(controller, options, callback, std::move(clients)); return; } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &OnGetWindowClientsOnUI, clients_info, controller->script_url(), base::Bind(&DidGetWindowClients, controller, options, callback), base::Passed(&clients))); } } // namespace void FocusWindowClient(ServiceWorkerProviderHost* provider_host, const ClientCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(blink::kWebServiceWorkerClientTypeWindow, provider_host->client_type()); BrowserThread::PostTaskAndReplyWithResult( BrowserThread::UI, FROM_HERE, base::Bind(&FocusOnUI, provider_host->process_id(), provider_host->frame_id(), provider_host->create_time(), provider_host->client_uuid()), callback); } void OpenWindow(const GURL& url, const GURL& script_url, int worker_process_id, const base::WeakPtr<ServiceWorkerContextCore>& context, WindowOpenDisposition disposition, const NavigationCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &OpenWindowOnUI, url, script_url, worker_process_id, make_scoped_refptr(context->wrapper()), disposition, base::Bind(&DidNavigate, context, script_url.GetOrigin(), callback))); } void NavigateClient(const GURL& url, const GURL& script_url, int process_id, int frame_id, const base::WeakPtr<ServiceWorkerContextCore>& context, const NavigationCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &NavigateClientOnUI, url, script_url, process_id, frame_id, base::Bind(&DidNavigate, context, script_url.GetOrigin(), callback))); } void GetClient(ServiceWorkerProviderHost* provider_host, const ClientCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); blink::WebServiceWorkerClientType client_type = provider_host->client_type(); DCHECK(client_type == blink::kWebServiceWorkerClientTypeWindow || client_type == blink::kWebServiceWorkerClientTypeWorker || client_type == blink::kWebServiceWorkerClientTypeSharedWorker) << client_type; if (client_type == blink::kWebServiceWorkerClientTypeWindow) { BrowserThread::PostTaskAndReplyWithResult( BrowserThread::UI, FROM_HERE, base::Bind(&GetWindowClientInfoOnUI, provider_host->process_id(), provider_host->route_id(), provider_host->create_time(), provider_host->client_uuid()), callback); return; } ServiceWorkerClientInfo client_info( provider_host->client_uuid(), blink::kWebPageVisibilityStateHidden, false, // is_focused provider_host->document_url(), REQUEST_CONTEXT_FRAME_TYPE_NONE, base::TimeTicks(), provider_host->create_time(), provider_host->client_type()); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(callback, client_info)); } void GetClients(const base::WeakPtr<ServiceWorkerVersion>& controller, const ServiceWorkerClientQueryOptions& options, const ClientsCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); auto clients = base::MakeUnique<ServiceWorkerClients>(); if (!controller->HasControllee() && !options.include_uncontrolled) { DidGetClients(callback, std::move(clients)); return; } // For Window clients we want to query the info on the UI thread first. if (options.client_type == blink::kWebServiceWorkerClientTypeWindow || options.client_type == blink::kWebServiceWorkerClientTypeAll) { GetWindowClients(controller, options, callback, std::move(clients)); return; } GetNonWindowClients(controller, options, callback, std::move(clients)); } } // namespace service_worker_client_utils } // namespace content
39.411232
80
0.702367
[ "vector" ]
3a93dfe37a4f20d978f2135d9a7e0284959d7ebc
1,899
cpp
C++
Uncategorized/oly21practice24.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/oly21practice24.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
Uncategorized/oly21practice24.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() using namespace std; const int MM = 3e5+5; int n, q, dis[MM], par[MM], pw[MM], dep[MM], head[MM], heavy[MM]; vector<pair<int, int>> adj[MM]; array<int, 4> v[MM]; int dfs(int cur, int pre){ dep[cur] = dep[pre]+1; par[cur] = pre; int sz = 1, mx = 0; for(auto [u, w]: adj[cur]){ if(u == pre){ pw[cur] = w; continue; } dis[u] = dis[cur]+w; int su = dfs(u, cur); sz += su; if(su > mx){ mx = su; heavy[cur] = u; } } return ++sz; } void hld(int cur, int h){ head[cur] = h; if(heavy[cur]) hld(heavy[cur], h); for(auto [u, w]: adj[cur]){ if(u != par[cur] and u != heavy[cur]) hld(u, u); } } int getlca(int a, int b){ while(head[a] != head[b]){ if(dep[head[a]] < dep[head[b]]) b = par[head[b]]; else a = par[head[a]]; } return dep[a] < dep[b] ? a : b; } int dif[MM], k, mx; int prop(int cur){ for(auto [u, w]: adj[cur]){ if(u != par[cur]) dif[cur] += prop(u); } if(dif[cur] == k){ mx = max(mx, pw[cur]); } return dif[cur]; } bool go(int m){ k = mx = 0; memset(dif, 0, sizeof dif); for(auto [a, b, lca, len] : v){ if(len <= m) break; k++; dif[a]++; dif[b]++; dif[lca] -= 2; } prop(1); return v[0][3]-mx <= m; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>q; for(int i = 0,a,b,c; i < n-1; i++){ cin>>a>>b>>c; adj[a].emplace_back(b, c); adj[b].emplace_back(a, c); } dfs(1, 0); hld(1, 1); for(int i = 0,a,b; i < q; i++){ cin>>a>>b; int lca = getlca(a, b); int len = dis[a] + dis[b] - 2*dis[lca]; v[i] = {a, b, lca, len}; } sort(v, v+q, [](auto x, auto y){ return x[3] > y[3]; }); int l = 0, m, r = 3e8; while(l <= r){ m = l+r>>1; if(go(m)) r = m-1; else l = m+1; } cout<<l<<'\n'; }
17.263636
66
0.462349
[ "vector" ]
3a97c9a83f6d1523af5c31a759c70e578d8a387c
3,754
cpp
C++
src/settings.cpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
src/settings.cpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
src/settings.cpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
/* Implementation for settings.hpp. author: andreasl */ #include "settings.hpp" #include "cli.hpp" #include "log.hpp" #include <experimental/filesystem> #include <fstream> #include <string> #include <unordered_map> #include <vector> namespace barn { namespace bbm { namespace { /*Convert settings from yaml to a Settings object.*/ Settings yaml_to_settings(const YAML::Node& node, const DefaultSettings& defaults) { Settings settings; const std::unordered_map<std::string, Dialog> str_to_dialog { {"ask_for_comment", Dialog::ask_for_comment}, {"ask_for_path", Dialog::ask_for_path}, {"ask_for_rating", Dialog::ask_for_rating}, {"ask_for_tags", Dialog::ask_for_tags}, {"review_url", Dialog::review_url} }; std::vector<std::string> str_dialog_sequence = node["add_bookmark_dialog_sequence"] .as<std::vector<std::string>>(defaults.add_bookmark_dialog_sequence); for (const std::string& dialog_str : str_dialog_sequence) { try { const Dialog dialog = str_to_dialog.at(dialog_str); settings.add_bookmark_dialog_sequence.emplace_back(dialog); } catch (const std::out_of_range& e) { log(WARN) << "Warning: string value not in enum \"" << dialog_str << "\"" << std::endl; } } settings.bookmarks_root_path = node["bookmarks_root_path"] .as<std::string>(defaults.bookmarks_root_path); settings.download_websites = node["download_websites"] .as<bool>(defaults.download_websites); settings.editor = node["editor"] .as<std::string>(defaults.editor); settings.open_browser_command = node["open_browser_command"] .as<std::string>(defaults.open_browser_command); return settings; } /*Write the default settings to the given file paths.*/ void write_default_settings(const fs::path& path) { const auto directory(fs::path(path).remove_filename()); try { fs::create_directories(directory); } catch (const std::exception& e) { log(ERROR) << "Could not create directory " << directory << ":\n" << e.what() << std::endl; exit(exitcode::SYSTEM_ERROR); } YAML::Node node; const DefaultSettings defaults{directory / "bookmarks"}; node["bookmarks_root_path"] = defaults.bookmarks_root_path.string(); node["download_websites"] = defaults.download_websites; node["editor"] = defaults.editor; node["open_browser_command"] = defaults.open_browser_command; for (const std::string& item : defaults.add_bookmark_dialog_sequence) { node["add_bookmark_dialog_sequence"].push_back(item); } std::ofstream out(path); out << node; if (!out) { log(ERROR) << "Could not write settings to file: " << path << std::endl; exit(exitcode::SYSTEM_ERROR); } } } // namespace /*Load settings from file.*/ Settings load_settings(const fs::path& path) { const auto directory(fs::path(path).remove_filename()); const DefaultSettings defaults{directory / "bookmarks"}; try { const YAML::Node node = YAML::LoadFile(path); return yaml_to_settings(node, defaults); } catch (const YAML::BadFile& e) { log(ERROR) << "Could not read file " << path << std::endl; try { if (!fs::exists(path)) { log(INFO) << "Creating file " << path << "..." << std::endl; write_default_settings(path); return load_settings(path); } } catch (const std::exception& e) { log(ERROR) << e.what() << std::endl; } } catch (const YAML::Exception& e) { log(ERROR) << e.what() << std::endl; } exit(exitcode::SYSTEM_ERROR); } } // namespace bbm } // namespace barn
34.127273
99
0.643047
[ "object", "vector" ]
3a9e5b9471d10ba776566f1ed185f273822bf45c
16,546
hpp
C++
src/del/codegen/codeblocks/Operations.hpp
NablaVM/Del
d353bc40a225635fc5b6efd0134b797c161acc11
[ "MIT" ]
null
null
null
src/del/codegen/codeblocks/Operations.hpp
NablaVM/Del
d353bc40a225635fc5b6efd0134b797c161acc11
[ "MIT" ]
null
null
null
src/del/codegen/codeblocks/Operations.hpp
NablaVM/Del
d353bc40a225635fc5b6efd0134b797c161acc11
[ "MIT" ]
null
null
null
#ifndef DEL_BLOCK_OPERATIONS_HPP #define DEL_BLOCK_OPERATIONS_HPP #include "Codeblock.hpp" namespace DEL { namespace CODE { // // A base conditional block // class Conditional : public Block { public: Conditional(uint64_t label_id, std::string comparison) : Block() { std::string label = "conditional_check_" + std::to_string(label_id); std::string complete = "conditional_complete_" + std::to_string(label_id); comparison = comparison + label; std::stringstream ss; ss << NLT << remove_for_calc << NL << comparison << NL << NLT << "mov" << WS << "r" << REG_CONDITIONAL << WS << "$0" << TAB << "; False" << NL << NLT << "jmp" << WS << complete << NL << NL << label << ":" << NL << NLT << "mov" << WS << "r" << REG_CONDITIONAL << WS << "$1" << TAB << "; True" << NL << NL << complete << ":" << NL << NLT << "pushw" << WS << CALC_STACK << WS << "r" << REG_CONDITIONAL << TAB << "; Put result into calc stack" << NL; code.push_back(ss.str()); } }; // // Addition // class Addition : public Block { public: Addition(CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "add.d" : "add"; std::stringstream ss; ss << NLT << "; <<< ADDITION >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // Subtraction // class Subtraction : public Block { public: Subtraction(CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "sub.d" : "sub"; std::stringstream ss; ss << NLT << "; <<< SUBTRACTION >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // Division // class Division : public Block { public: Division(CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "div.d" : "div"; std::stringstream ss; ss << NLT << "; <<< DIVISION >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // Multiplication // class Multiplication : public Block { public: Multiplication(CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "mul.d" : "mul"; std::stringstream ss; ss << NLT << "; <<< MULTIPLICATION >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // Right Shift // class RightShift : public Block { public: RightShift() : Block() { std::string cmd = "rsh"; std::stringstream ss; ss << NLT << "; <<< RIGHT SHIFT >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // Left Shift // class LeftShift : public Block { public: LeftShift() : Block() { std::string cmd = "lsh"; std::stringstream ss; ss << NLT << "; <<< LEFT SHIFT >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // BW Or // class BwOr : public Block { public: BwOr() : Block() { std::string cmd = "or"; std::stringstream ss; ss << NLT << "; <<< BITWISE OR >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // BW Not // class BwNot : public Block { public: BwNot() : Block(true) { std::string cmd = "not"; std::stringstream ss; ss << NLT << "; <<< BITWISE NOT >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // BW Xor // class BwXor : public Block { public: BwXor() : Block() { std::string cmd = "xor"; std::stringstream ss; ss << NLT << "; <<< BITWISE XOR >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // BW And // class BwAnd : public Block { public: BwAnd() : Block() { std::string cmd = "and"; std::stringstream ss; ss << NLT << "; <<< BITWISE AND >>> " << NL << remove_for_calc << NLT << cmd << WS << calculate_and_store; code.push_back(ss.str()); } }; // // LTE // class Lte : public Block { public: Lte(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "blte.d" : "blte"; std::stringstream sscmd; sscmd << TAB << cmd << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_ARITH_RHS << WS; std::stringstream ss; ss << NLT << "; <<< LTE >>>" << NL; code.push_back(ss.str()); Conditional * c = new Conditional(label_id, sscmd.str()); std::vector<std::string> ccode = c->get_code(); code.insert(code.end(), ccode.begin(), ccode.end()); delete c; } }; // // LT // class Lt : public Block { public: Lt(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "blt.d" : "blt"; std::stringstream sscmd; sscmd << TAB << cmd << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_ARITH_RHS << WS; std::stringstream ss; ss << NLT << "; <<< LT >>>" << NL; code.push_back(ss.str()); Conditional * c = new Conditional(label_id, sscmd.str()); std::vector<std::string> ccode = c->get_code(); code.insert(code.end(), ccode.begin(), ccode.end()); delete c; } }; // // GTE // class Gte : public Block { public: Gte(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "bgte.d" : "bgte"; std::stringstream sscmd; sscmd << TAB << cmd << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_ARITH_RHS << WS; std::stringstream ss; ss << NLT << "; <<< GTE >>>" << NL; code.push_back(ss.str()); Conditional * c = new Conditional(label_id, sscmd.str()); std::vector<std::string> ccode = c->get_code(); code.insert(code.end(), ccode.begin(), ccode.end()); delete c; } }; // // GT // class Gt : public Block { public: Gt(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "bgt.d" : "bgt"; std::stringstream sscmd; sscmd << TAB << cmd << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_ARITH_RHS << WS; std::stringstream ss; ss << NLT << "; <<< GT >>>" << NL; code.push_back(ss.str()); Conditional * c = new Conditional(label_id, sscmd.str()); std::vector<std::string> ccode = c->get_code(); code.insert(code.end(), ccode.begin(), ccode.end()); delete c; } }; // // EQ // class Eq : public Block { public: Eq(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "beq.d" : "beq"; std::stringstream sscmd; sscmd << TAB << cmd << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_ARITH_RHS << WS; std::stringstream ss; ss << NLT << "; <<< EQ >>>" << NL; code.push_back(ss.str()); Conditional * c = new Conditional(label_id, sscmd.str()); std::vector<std::string> ccode = c->get_code(); code.insert(code.end(), ccode.begin(), ccode.end()); delete c; } }; // // NEQ // class Neq : public Block { public: Neq(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block() { std::string cmd = (is_double_variant(classification)) ? "bne.d" : "bne"; std::stringstream sscmd; sscmd << TAB << cmd << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_ARITH_RHS << WS; std::stringstream ss; ss << NLT << "; <<< NEQ >>>" << NL; code.push_back(ss.str()); Conditional * c = new Conditional(label_id, sscmd.str()); std::vector<std::string> ccode = c->get_code(); code.insert(code.end(), ccode.begin(), ccode.end()); delete c; } }; // // OR // class Or : public Block { public: Or(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block() { std::string true_label = "OR_is_true_" + std::to_string(label_id); std::string complete = "OR_is_complete_" + std::to_string(label_id); std::string comparison = (is_double_variant(classification)) ? "bgt.d" : "bgt"; std::stringstream ss; ss << NLT << "; <<< OR >>>" << NL << remove_for_calc << NL << NLT << "mov" << WS << "r" << REG_COMPARISON << WS << "$0" << TAB << "; Comparison Value" << NL << NLT << comparison << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_COMPARISON << WS << true_label << NL << NLT << comparison << WS << "r" << REG_ARITH_RHS << WS << "r" << REG_COMPARISON << WS << true_label << NL << NLT << "mov" << WS << "r" << REG_ARITH_LHS << WS << "$0" << TAB << "; False" << NL << NLT << "jmp" << WS << complete << NL << NL << true_label << ":" << NL << NLT << "mov" << WS << "r" << REG_ARITH_LHS << WS << "$1" << TAB << "; True" << NL << NL << complete << ":" << NL << NLT << "pushw" << WS << CALC_STACK << WS << "r" << REG_ARITH_LHS << TAB << "; Put result in calc stack" << NL; code.push_back(ss.str()); } }; // // And // class And : public Block { public: And(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block() { std::string first_true = "AND_first_true_" + std::to_string(label_id); std::string second_true = "AND_second_true_" + std::to_string(label_id); std::string complete = "AND_complete_" + std::to_string(label_id); std::string comparison = (is_double_variant(classification)) ? "bgt.d" : "bgt"; std::stringstream ss; ss << NLT << "; <<< AND >>> " << NL << remove_for_calc << NL << NLT // Load comparison value << "mov" << WS << "r" << REG_COMPARISON << WS << "$0" << TAB << "; Comparison value" << NL << NLT // Check the lhs << comparison << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_COMPARISON << WS << first_true << NL << NLT << "mov" << WS << "r" << REG_ARITH_LHS << WS << "$0" << TAB << "; False" << NL << NLT << "jmp" << WS << complete << NL << NL // Check the rhs << first_true << ":" << NL << NLT << comparison << WS << "r" << REG_ARITH_RHS << WS << "r" << REG_COMPARISON << WS << second_true << NL << NLT << "mov" << WS << "r" << REG_ARITH_LHS << WS << "$0" << TAB << "; False" << NL << NLT << "jmp" << WS << complete << NL << NL // Both were true, mark true << second_true << ":" << NL << NLT << "mov" << WS << "r" << REG_ARITH_LHS << WS << "$1" << TAB << "; True" << NL << NL // Complete the check << complete << ":" << NL << NLT << "pushw" << WS << CALC_STACK << WS << "r" << REG_ARITH_LHS << TAB << "; Put result into calc stack" << NL; code.push_back(ss.str()); } }; // // Negate // class Negate : public Block { public: Negate(uint64_t label_id, CODEGEN::TYPES::DataClassification classification) : Block(true) { std::string set_zero = "NEGATE_set_zero_" + std::to_string(label_id); std::string set_comp = "NEGATE_complete_" + std::to_string(label_id); std::string comparison = (is_double_variant(classification)) ? "bgt.d" : "bgt"; std::stringstream ss; ss << NLT << "; <<< NEGATE >>>" << NL << remove_for_calc << NL << NLT << "mov" << WS << "r" << REG_COMPARISON << WS << "$0" << TAB << "; Comparison" << NL << NLT << comparison << WS << "r" << REG_ARITH_LHS << WS << "r" << REG_COMPARISON << WS << set_zero << NL << NLT << "mov" << WS << "r" << REG_ARITH_LHS << WS << "$1" << NLT << "jmp" << WS << set_comp << NL << NL << set_zero << ":" << NLT << "mov" << WS << "r" << REG_ARITH_LHS << WS << "$0" << NL << NL << set_comp << ":" << NLT << "pushw" << WS << CALC_STACK << WS << "r" << REG_ARITH_LHS << TAB << "; Push result into calcl stack" << NL; code.push_back(ss.str()); } }; // // BuiltIn // class BuiltIn : public Block { public: BuiltIn(std::string title_comment, std::string function_name) : Block() { std::stringstream ss; ss << NLT << "; <<< " << title_comment << " >>> " << NL << NLT << bif_remove_for_calc << NL << NLT << "call" << WS << function_name << TAB << "; Call built-in function " + title_comment << NL << NLT << "pushw" << WS << CALC_STACK << WS << "r" << REG_ADDR_RO << TAB << "; Push value on calc stack" << NL; code.push_back(ss.str()); } }; // // Call Function // class Call : public Block { public: Call(CODEGEN::TYPES::CallInstruction * ins) : Block() { std::stringstream ss; ss << NLT << "; <<< CALL >>> " << NL << NLT << "call" << WS << ins->function_name << TAB << "; Call function" << NL; if(ins->expect_return_value) { ss << NLT << "; Get result from call " << NL << NLT << "ldw" << WS << "r" << REG_ADDR_RO << WS << "$" << SETTINGS::GS_INDEX_RETURN_SPACE << "(gs)" << NLT << "pushw" << WS << CALC_STACK << WS << "r" << REG_ADDR_RO << TAB << "; Push result to calculation stack" << NL; } code.push_back(ss.str()); } }; } } #endif
29.812613
131
0.451046
[ "vector" ]
3aa091921d78113f5ac34b83a41f3afe07f3a9d8
14,158
cpp
C++
PSME/application/src/rest/endpoints/chassis/chassis.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/application/src/rest/endpoints/chassis/chassis.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
null
null
null
PSME/application/src/rest/endpoints/chassis/chassis.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/*! * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * Edgecore DeviceManager * Copyright 2020-2021 Edgecore Networks, Inc. * * This product includes software developed at * Edgecore Networks Inc. (http://www.edge-core.com/). * * */ #include "agent-framework/module/constants/chassis.hpp" #include "agent-framework/module/requests/common.hpp" #include "agent-framework/module/responses/common.hpp" #include "psme/rest/endpoints/chassis/chassis.hpp" #include "psme/rest/utils/status_helpers.hpp" #include "psme/rest/validators/json_validator.hpp" #include "psme/rest/validators/schemas/chassis.hpp" #include "psme/rest/server/error/error_factory.hpp" #include "ecsys_helper/ecsys_helper.hpp" #include "ecrf_pal_helper/api/ecrf_pal_helper.hpp" #include "psme/rest/utils/ec_common_utils.hpp" using namespace psme::rest::utils; using namespace ecrf_pal_helper; using namespace ecsys_helper; using namespace psme::rest; using namespace psme::rest::constants; using namespace psme::rest::validators; namespace { json::Value make_prototype() { json::Value r(json::Value::Type::OBJECT); r[Common::ODATA_CONTEXT] = "/redfish/v1/$metadata#Chassis.Chassis"; //For pass DMTF conference check // r[Common::ODATA_ID] = json::Value::Type::NIL; r[Common::ODATA_TYPE] = "#Chassis.v1_3_0.Chassis"; r[Common::ID] = json::Value::Type::NIL; r[Chassis::CHASSIS_TYPE] = json::Value::Type::NIL; r[Common::NAME] = "Chassis"; r[Common::DESCRIPTION] = json::Value::Type::NIL; r[Chassis::POWER_STATE] = "On"; r[Common::MANUFACTURER] = json::Value::Type::NIL; r[Common::MODEL] = json::Value::Type::NIL; r[Chassis::SKU] = json::Value::Type::NIL; r[Common::SERIAL] = json::Value::Type::NIL; r[Common::PART_NUMBER] = json::Value::Type::NIL; r[Common::ASSET_TAG] = json::Value::Type::NIL; r[Chassis::INDICATOR_LED] = json::Value::Type::NIL; r[Common::STATUS][Common::STATE] = json::Value::Type::NIL; r[Common::STATUS][Common::HEALTH] = json::Value::Type::NIL; r[Common::STATUS][Common::HEALTH_ROLLUP] = json::Value::Type::NIL; json::Value rs; rs[Common::ODATA_TYPE] = "#Intel.Oem.Chassis"; rs[Common::LOCATION][Common::ID] = json::Value::Type::NIL; rs[Common::LOCATION][Chassis::PARENT_ID] = json::Value::Type::NIL; r[Common::OEM][Common::RACKSCALE] = std::move(rs); r[Common::LINKS][Common::ODATA_TYPE] = "#Chassis.v1_2_0.Links"; r[Common::LINKS][Chassis::CONTAINS] = json::Value::Type::ARRAY; r[Common::LINKS][Common::MANAGED_BY] = json::Value::Type::ARRAY; return r; } void fill_containing_links(const agent_framework::model::Chassis &chassis, json::Value &r) { auto is_drawer = [](const agent_framework::model::Chassis &ch) -> bool { return ch.get_type() == agent_framework::model::enums::ChassisType::Drawer; }; auto is_enclosure = [](const agent_framework::model::Chassis &ch) -> bool { return ch.get_type() == agent_framework::model::enums::ChassisType::Enclosure; }; // find manager of the chassis if (is_drawer(chassis) || is_enclosure(chassis)) { for (const auto &chassis_id : agent_framework::module::CommonComponents::get_instance() ->get_chassis_manager() .get_ids()) { if (chassis_id != chassis.get_id()) { json::Value link; link[Common::ODATA_ID] = "/redfish/v1/Chassis/" + std::to_string(chassis_id); r[Common::LINKS][Chassis::CONTAINS].push_back(std::move(link)); } } } else { try { for (const auto &chass : agent_framework::module::CommonComponents::get_instance()->get_chassis_manager().get_keys(is_drawer)) { auto ch = agent_framework::module::CommonComponents::get_instance()->get_chassis_manager().get_entry_reference(chass); json::Value link; link[Common::ODATA_ID] = endpoint::PathBuilder(PathParam::BASE_URL) .append(constants::Common::CHASSIS) .append(ch->get_id()) .build(); r[Common::LINKS][Common::CONTAINED_BY] = std::move(link); r[Common::OEM][Common::RACKSCALE][Common::LOCATION][constants::Chassis::PARENT_ID] = std::to_string(ch->get_location_offset()); } } catch (const std::exception &e) { log_error(GET_LOGGER("app"), "Exception caught during filling Chassis" "links Contains and ContainedBy: " << e.what()); } } } void fill_links(const agent_framework::model::Chassis &chassis, json::Value &r) { // find manager of this chassis try { json::Value allowable; allowable.push_back(Chassis::FORCE_OFF); allowable.push_back(Chassis::GRACEFUL_SHUTDOWN); allowable.push_back(Chassis::GRACEFUL_RESTART); allowable.push_back(Chassis::FORCE_RESTART); json::Value actions; std::string hash_chassis_reset(constants::Common::HASH); hash_chassis_reset.append(constants::Chassis::CHASSIS_RESET); actions[hash_chassis_reset][Chassis::TARGET] = endpoint::PathBuilder(constants::PathParam::BASE_URL) .append(Common::CHASSIS) .append(chassis.get_id()) .append(constants::Common::ACTIONS) .append(constants::Chassis::CHASSIS_RESET) .build(); actions[hash_chassis_reset][Chassis::ALLOWABLE_RESET_TYPES] = std::move(allowable); r[Common::ACTIONS] = std::move(actions); json::Value managed_by; managed_by[Common::ODATA_ID] = psme::rest::endpoint::utils::get_component_url( agent_framework::model::enums::Component::Manager, chassis.get_parent_uuid()); r[Common::LINKS][Common::MANAGED_BY].push_back(managed_by); } catch (const agent_framework::exceptions::InvalidUuid &) { } // systems and storage subsystems in chassis auto &system_manager = agent_framework::module::CommonComponents::get_instance()->get_system_manager(); auto &storage_manager = agent_framework::module::get_manager<agent_framework::model::StorageSubsystem>(); auto system_uuids = system_manager.get_keys(); for (const auto &system_uuid : system_uuids) { auto system = system_manager.get_entry(system_uuid); if (system.get_chassis() == chassis.get_uuid()) { json::Value link; link[Common::ODATA_ID] = endpoint::PathBuilder(PathParam::BASE_URL) .append(constants::Root::SYSTEMS) .append(system.get_id()) .build(); for (const auto storage_id : storage_manager.get_ids(system.get_uuid())) { json::Value storage_link; storage_link[Common::ODATA_ID] = endpoint::PathBuilder(PathParam::BASE_URL) .append(constants::Root::SYSTEMS) .append(system.get_id()) .append(constants::System::STORAGE) .append(storage_id) .build(); } } } #ifdef THERMAL_PSU // Thermal contains Fans and Temperatures Sensors // json::Value link; // /Redfish/v1/Chassis/X/Thermal/ link[Common::ODATA_ID] = endpoint::PathBuilder(PathParam::BASE_URL).append(Common::CHASSIS).append(chassis.get_id()).append(constants::Root::THERMAL).build(); r[constants::Chassis::THERMAL] = link; // PSUs in chassis // /Redfish/v1/Chassis/X/Power/ link[Common::ODATA_ID] = endpoint::PathBuilder(PathParam::BASE_URL).append(Common::CHASSIS).append(chassis.get_id()).append(constants::Root::PSU).build(); r[constants::Chassis::PSU] = link; #endif } static const std::map<std::string, std::string> gami_to_rest_attributes = { {agent_framework::model::literals::Chassis::ASSET_TAG, constants::Common::ASSET_TAG}}; } // namespace endpoint::Chassis::Chassis(const std::string& path) : EndpointBase(path) {} endpoint::Chassis::~Chassis() {} void endpoint::Chassis::get(const server::Request& req, server::Response& res) { auto r = make_prototype(); r[Common::ODATA_ID] = PathBuilder(req).build(); r[Common::ID] = req.params[PathParam::CHASSIS_ID]; auto chassis = psme::rest::model::Find<agent_framework::model::Chassis>(req.params[PathParam::CHASSIS_ID]).get(); psme::rest::endpoint::status_to_json(chassis, r); // for now, we assume that a chassis has no children r[Common::STATUS][Common::HEALTH_ROLLUP] = chassis.get_status().get_health(); fill_links(chassis, r); fill_containing_links(chassis, r); #ifndef COMCAST char command[BUFFER_LEN] = {0}; char resultA[BUFFER_LEN] = {0}; char IfName[BUFFER_LEN] = "ma1"; sprintf(command, "psme.sh get mgmt_port_name"); EcCommonUtils::exec_shell(command, resultA, 0); if(strlen(resultA) !=0 ) { sprintf(IfName, "%s", resultA); } sprintf(command, "lldp.sh get PortID %s", IfName); EcCommonUtils::exec_shell(command, resultA, 0); if(strlen(resultA) !=0 ) { resultA[strcspn(resultA, "\r\n")]=0; r[Common::OEM][Common::RACKSCALE][Common::LOCATION][Common::ID] = resultA; } sprintf(command, "lldp.sh get ParentID %s", IfName); EcCommonUtils::exec_shell(command, resultA, 0); if(strlen(resultA) !=0 ) { resultA[strcspn(resultA, "\r\n")]=0; r[Common::OEM][Common::RACKSCALE][Common::LOCATION][constants::Chassis::PARENT_ID] = resultA; } #endif auto& secrf_pal = ecrf_pal_helper::Switch::get_instance(); r[Common::DESCRIPTION] = secrf_pal.get_product_name().c_str(); r[Common::MANUFACTURER] = secrf_pal.get_manufacturer().c_str(); r[Common::SERIAL] = secrf_pal.get_serial_number().c_str(); r[Common::PART_NUMBER] = secrf_pal.get_part_number().c_str(); r[Common::MODEL] = secrf_pal.get_platform_name().c_str(); r[Common::OEM][Common::RACKSCALE][Common::ACT_OEM][Common::SERVICE_TAG] = secrf_pal.get_service_tag().c_str(); r[Common::ASSET_TAG] = chassis.get_asset_tag(); r[constants::Chassis::SKU] = chassis.get_sku(); r[constants::Chassis::CHASSIS_TYPE] = chassis.get_type().to_string(); r[constants::Chassis::INDICATOR_LED] = "Lit"; //Todo // set_response(res, r); } void endpoint::Chassis::patch(const server::Request &request, server::Response &response) { auto chassis = model::Find<agent_framework::model::Chassis>(request.params[PathParam::CHASSIS_ID]).get(); const auto json = JsonValidator::validate_request_body<schema::ChassisPatchSchema>(request); agent_framework::model::attribute::Attributes attributes{}; if (json.is_member(constants::Common::ASSET_TAG)) { const auto &asset_tag = json[constants::Common::ASSET_TAG].as_string(); attributes.set_value(agent_framework::model::literals::Chassis::ASSET_TAG, asset_tag); char command[BUFFER_LEN] = {0}; char resultA[BUFFER_LEN] = {0}; sprintf(command, "echo %s > /etc/psme/ASSET_TAG", asset_tag.c_str()); EcCommonUtils::exec_shell(command, resultA, 0); } if (!attributes.empty()) { agent_framework::model::requests::SetComponentAttributes set_component_attributes_request{chassis.get_uuid(), attributes}; const auto &gami_agent = psme::core::agent::AgentManager::get_instance()->get_agent(chassis.get_agent_id()); auto set_chassis_attributes = [&, gami_agent] { // Call set component attribute method const auto &set_component_attributes_response = gami_agent->execute<agent_framework::model::responses::SetComponentAttributes>( set_component_attributes_request); const auto &result_statuses = set_component_attributes_response.get_statuses(); if (!result_statuses.empty()) { const auto &error = error::ErrorFactory::create_error_from_set_component_attributes_results( result_statuses, gami_to_rest_attributes); throw error::ServerException(error); } psme::rest::model::handler::HandlerManager::get_instance()->get_handler( agent_framework::model::enums::Component::Chassis) ->load(gami_agent, chassis.get_parent_uuid(), agent_framework::model::enums::Component::Manager, chassis.get_uuid(), false); }; gami_agent->execute_in_transaction(set_chassis_attributes); } get(request, response); }
42.516517
162
0.612163
[ "object", "model" ]
3aa1e0ad084053aaa4f09da868a93292912c9518
2,794
cpp
C++
src/persistent_structures/bit_array.cpp
ufal/korektor
3764a6965b8f1f900a74ad6df0034f65d16aa725
[ "BSD-2-Clause" ]
18
2015-03-21T21:55:45.000Z
2022-02-09T12:59:33.000Z
src/persistent_structures/bit_array.cpp
ufal/korektor
3764a6965b8f1f900a74ad6df0034f65d16aa725
[ "BSD-2-Clause" ]
27
2015-01-19T07:26:20.000Z
2020-07-03T20:21:29.000Z
src/persistent_structures/bit_array.cpp
ufal/korektor
3764a6965b8f1f900a74ad6df0034f65d16aa725
[ "BSD-2-Clause" ]
5
2015-07-06T09:41:01.000Z
2020-08-02T11:53:44.000Z
// This file is part of korektor <http://github.com/ufal/korektor/>. // // Copyright 2015 by Institute of Formal and Applied Linguistics, Faculty // of Mathematics and Physics, Charles University in Prague, Czech Republic. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under 3-clause BSD licence. #include "bit_array.h" #include "utils/io.h" namespace ufal { namespace korektor { BitArray::BitArray(istream &ifs) { if (IO::ReadString(ifs) != "MBA") runtime_failure("Cannot load BitArray, file is corrupted!"); output_mask.push_back(0); uint32_t curr_mask = 0; for (unsigned i = 1; i <= 32; i++) { curr_mask = curr_mask << 1; curr_mask++; output_mask.push_back(curr_mask); } ifs.read((char*)&num_bytes, sizeof(uint32_t)); //TODO: initialization of the output masks; //ifs.read((char*)&output_mask, sizeof(uint32_t)); data = new unsigned char[num_bytes]; ifs.read((char*)data, sizeof(unsigned char) * num_bytes); } void BitArray::WriteToStream(ostream &ofs) const { IO::WriteString(ofs, "MBA"); ofs.write((char*)&num_bytes, sizeof(uint32_t)); //TODO: output masks! //ofs.write((char*)&output_mask, sizeof(uint32_t)); ofs.write((char*)data, sizeof(unsigned char) * num_bytes); } BitArray::BitArray(const vector<pair<uint32_t, unsigned> > &values) { uint32_t bits_needed = 0; for (uint32_t i = 0; i < values.size(); i++) { bits_needed += values[i].second; } num_bytes = (bits_needed + 7) / 8; output_mask.push_back(0); uint32_t curr_mask = 0; for (unsigned i = 1; i <= 32; i++) { curr_mask = curr_mask << 1; curr_mask++; output_mask.push_back(curr_mask); } data = new unsigned char[num_bytes]; for (uint32_t i = 0; i < num_bytes; i++) data[i] = 0; uint32_t byte_pointer; uint32_t bit_pointer; uint32_t bit_position = 0; uint64_t curr_value; unsigned char* ukaz; for (uint32_t i = 0; i < values.size(); i++) { int bites_left = values[i].second; byte_pointer = bit_position >> 3; bit_pointer = bit_position % 8; curr_value = values[i].first; curr_value = curr_value << bit_pointer; ukaz = (unsigned char*)&curr_value; bites_left -= 8 - bit_pointer; data[byte_pointer] = data[byte_pointer] | ukaz[0]; uint32_t j = 1; while (bites_left > 0) { data[byte_pointer + j] = data[byte_pointer + j] | ukaz[j]; bites_left -= 8; j++; } bit_position += values[i].second; } bit_position = 0; for (uint32_t i = 0; i < values.size(); i++) { assert(GetValueAt(bit_position, values[i].second) == values[i].first); bit_position += values[i].second; } } SP_DEF(BitArray); } // namespace korektor } // namespace ufal
23.283333
76
0.654617
[ "vector" ]
3aa8a2ed71dfe9fd9c6b3761c82ce718e921293d
4,019
cc
C++
iree/modules/strings/strings_module_test.cc
rsuderman/iree
fa5faf0a254db3311dafacc70c383a7469376095
[ "Apache-2.0" ]
1
2021-08-02T15:41:24.000Z
2021-08-02T15:41:24.000Z
iree/modules/strings/strings_module_test.cc
rsuderman/iree
fa5faf0a254db3311dafacc70c383a7469376095
[ "Apache-2.0" ]
null
null
null
iree/modules/strings/strings_module_test.cc
rsuderman/iree
fa5faf0a254db3311dafacc70c383a7469376095
[ "Apache-2.0" ]
1
2020-03-06T06:22:26.000Z
2020-03-06T06:22:26.000Z
// Copyright 2020 Google LLC // // 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 // // https://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 "iree/modules/strings/strings_module.h" #include "absl/container/inlined_vector.h" #include "absl/strings/string_view.h" #include "iree/base/api.h" #include "iree/base/logging.h" #include "iree/modules/strings/strings_module_test_module.h" #include "iree/testing/gtest.h" #include "iree/vm/bytecode_module.h" #include "iree/vm/context.h" #include "iree/vm/instance.h" #include "iree/vm/module.h" #include "iree/vm/ref.h" #include "iree/vm/stack.h" #include "iree/vm/types.h" using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; namespace { class StringsModuleTest : public ::testing::Test { protected: virtual void SetUp() { IREE_CHECK_OK(iree_vm_instance_create(IREE_ALLOCATOR_SYSTEM, &instance_)); IREE_CHECK_OK(strings_module_register_types()); IREE_CHECK_OK( strings_module_create(IREE_ALLOCATOR_SYSTEM, &strings_module_)) << "Native module failed to init"; const auto* module_file_toc = iree::strings_module_test::strings_module_test_module_create(); IREE_CHECK_OK(iree_vm_bytecode_module_create( iree_const_byte_span_t{ reinterpret_cast<const uint8_t*>(module_file_toc->data), module_file_toc->size}, IREE_ALLOCATOR_NULL, IREE_ALLOCATOR_SYSTEM, &bytecode_module_)) << "Bytecode module failed to load"; std::vector<iree_vm_module_t*> modules = {strings_module_, bytecode_module_}; IREE_CHECK_OK(iree_vm_context_create_with_modules( instance_, modules.data(), modules.size(), IREE_ALLOCATOR_SYSTEM, &context_)); } virtual void TearDown() { iree_vm_module_release(strings_module_); iree_vm_module_release(bytecode_module_); iree_vm_context_release(context_); iree_vm_instance_release(instance_); } iree_vm_function_t LookupFunction(absl::string_view function_name) { iree_vm_function_t function; IREE_CHECK_OK(bytecode_module_->lookup_function( bytecode_module_->self, IREE_VM_FUNCTION_LINKAGE_EXPORT, iree_string_view_t{function_name.data(), function_name.size()}, &function)) << "Exported function '" << function_name << "' not found"; return function; } iree_vm_instance_t* instance_ = nullptr; iree_vm_context_t* context_ = nullptr; iree_vm_module_t* bytecode_module_ = nullptr; iree_vm_module_t* strings_module_ = nullptr; }; TEST_F(StringsModuleTest, Run) { const int input = 42; std::string expected_output = "42\n"; // Construct the input list for execution. iree_vm_variant_list_t* inputs = nullptr; IREE_ASSERT_OK(iree_vm_variant_list_alloc(1, IREE_ALLOCATOR_SYSTEM, &inputs)); // Add the value parameter. iree_vm_value_t value = IREE_VM_VALUE_MAKE_I32(input); IREE_ASSERT_OK(iree_vm_variant_list_append_value(inputs, value)); // Prepare outputs list to accept the results from the invocation. iree_vm_variant_list_t* outputs = nullptr; IREE_ASSERT_OK( iree_vm_variant_list_alloc(0, IREE_ALLOCATOR_SYSTEM, &outputs)); CaptureStdout(); IREE_ASSERT_OK(iree_vm_invoke(context_, LookupFunction("print_example_func"), /*policy=*/nullptr, inputs, outputs, IREE_ALLOCATOR_SYSTEM)); EXPECT_EQ(GetCapturedStdout(), expected_output); iree_vm_variant_list_free(inputs); iree_vm_variant_list_free(outputs); } } // namespace
35.254386
80
0.731276
[ "vector" ]
3aaaf1375f7d313a5d073cb4c18ec250c75d8fb7
8,550
cc
C++
src/storage/volume_image/ftl/ftl_volume_extractor.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/storage/volume_image/ftl/ftl_volume_extractor.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
5
2019-12-04T15:13:37.000Z
2020-02-19T08:11:38.000Z
src/storage/volume_image/ftl/ftl_volume_extractor.cc
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <getopt.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string> #include <vector> #include "src/storage/volume_image/ftl/ftl_test_helper.h" #include "zircon/system/ulib/ftl/include/lib/ftl/volume.h" using namespace storage::volume_image; class FakeFtl : public ftl::FtlInstance { public: FakeFtl() = default; ~FakeFtl() override = default; bool OnVolumeAdded(uint32_t page_size, uint32_t num_pages) override { return true; } }; // Loads data from the data and spare files into the nand data members. Reads // complete pages spare chunks sized based on the nand options provided. If an // incomplete page or spare chunk is read this will return false, or if the // number of data pages is mismatched with the spare chunk count. Returns true // on success. bool LoadData(InMemoryRawNand* nand, FILE* data, FILE* spare) { uint32_t page_count = 0; std::vector<uint8_t> data_buf; while (!feof(data)) { data_buf.resize(nand->options.page_size); size_t actual_read = fread(&data_buf[0], 1, nand->options.page_size, data); if (actual_read == 0 && feof(data)) { break; } else if (actual_read != nand->options.page_size) { fprintf(stderr, "Failed to read, or read partial page for page number: %u\n", page_count); return false; } nand->page_data[page_count++] = std::move(data_buf); } uint32_t spare_count = 0; std::vector<uint8_t> spare_buf; while (!feof(spare)) { spare_buf.resize(nand->options.oob_bytes_size); size_t actual_read = fread(&spare_buf[0], 1, nand->options.oob_bytes_size, spare); if (actual_read == 0 && feof(spare)) { break; } else if (actual_read != nand->options.oob_bytes_size) { fprintf(stderr, "Failed to read, or read partial spare for page number: %u\n", spare_count); return false; } nand->page_oob[spare_count++] = std::move(spare_buf); } if (page_count != spare_count) { fprintf(stderr, "Found a mismatch of data pages (%u) vs spare blocks (%u)\n", page_count, spare_count); return false; } nand->options.page_count = page_count; return true; } // Loads the nand up with the bad_blocks information and attempts to read out // pages from the start until one fails, possibly due to hitting the end of the // volume. Returns false on failing to init the volume or failing to write out // to the file. Returns true on success. bool WriteVolume(InMemoryRawNand* nand, uint32_t bad_blocks, FILE* out) { FakeFtl ftl; ftl::VolumeImpl volume(&ftl); auto ndm = std::make_unique<InMemoryNdm>(nand, nand->options.page_size, nand->options.oob_bytes_size, bad_blocks); const char* err = volume.Init(std::move(ndm)); if (err != nullptr) { fprintf(stderr, "Failed to init volume: %s\n", err); return false; } std::vector<uint8_t> buf(nand->options.page_size); uint32_t page; for (page = 0; volume.Read(page, 1, &buf[0]) == ZX_OK; ++page) { if (fwrite(&buf[0], 1, nand->options.page_size, out) != nand->options.page_size) { fprintf(stderr, "Failed to write out page number: %u\n", page); return false; } } fprintf(stderr, "Successfully recovered %u pages from volume.\n", page); return true; } void PrintUsage(char* arg) { fprintf(stderr, "Usage: %s <options>*\n", arg); fprintf(stderr, "options: --data_input Input file for volume data (required) \n" " --spare_input Input file for spare data (required) \n" " --page_size Page size for volume data (required) \n" " --spare_size Size of spare data per page (required) \n" " --block_pages Number of pages per block (required) \n" " --output_file File to write resulting volume image. (required) \n" " --max_bad_blocks Maximum number of bad blocks. (required) \n" "\n" "This tool takes two files, one for volume data and one for spare data along\n" "with the sizes of chunks (--page_size & --spare_size) for a single page.\n" "This is loaded into the FTL where it attempts to linearly dump the\n" "resulting image that it would normally expose out to --output_file\n"); } std::optional<uint32_t> ParseUint32(const char* str) { char* pend; uint64_t ret = strtoul(str, &pend, 10); if (*pend != '\0') { return std::nullopt; } if (ret > std::numeric_limits<uint32_t>::max()) { return std::nullopt; } return static_cast<uint32_t>(ret); } int main(int argc, char** argv) { char* arg_data_input = nullptr; char* arg_spare_input = nullptr; char* arg_output_file = nullptr; char* arg_page_size = nullptr; char* arg_spare_size = nullptr; char* arg_block_pages = nullptr; char* arg_bad_blocks = nullptr; while (1) { static struct option opts[] = { {"data_input", required_argument, nullptr, 'd'}, {"spare_input", required_argument, nullptr, 's'}, {"page_size", required_argument, nullptr, 'p'}, {"spare_size", required_argument, nullptr, 'q'}, {"block_pages", required_argument, nullptr, 'b'}, {"max_bad_blocks", required_argument, nullptr, 'm'}, {"output_file", required_argument, nullptr, 'o'}, }; int opt_index; int c = getopt_long(argc, argv, "b:d:m:o:p:q:s:", opts, &opt_index); if (c < 0) { break; } switch (c) { case 'd': arg_data_input = optarg; break; case 's': arg_spare_input = optarg; break; case 'p': arg_page_size = optarg; break; case 'q': arg_spare_size = optarg; break; case 'b': arg_block_pages = optarg; break; case 'm': arg_bad_blocks = optarg; break; case 'o': arg_output_file = optarg; break; default: PrintUsage(argv[0]); return 1; } } if (arg_data_input == nullptr || arg_spare_input == nullptr || arg_page_size == nullptr || arg_spare_size == nullptr || arg_block_pages == nullptr || arg_bad_blocks == nullptr || arg_output_file == nullptr) { fprintf(stderr, "Missing required argument.\n"); PrintUsage(argv[0]); return 1; } std::optional<uint32_t> parsed = ParseUint32(arg_page_size); if (!parsed || *parsed == 0) { fprintf(stderr, "Expected positive integer for page_size but got: %s\n", arg_page_size); return 2; } uint32_t page_size = *parsed; parsed = ParseUint32(arg_spare_size); if (!parsed || *parsed == 0 || *parsed > 255) { fprintf(stderr, "Expected positive 8 bit integer for spare_size but got: %s\n", arg_spare_size); return 2; } uint32_t spare_size = *parsed; parsed = ParseUint32(arg_block_pages); if (!parsed || *parsed == 0) { fprintf(stderr, "Expected positive integer for block_pages but got: %s\n", arg_block_pages); return 2; } uint32_t block_pages = *parsed; parsed = ParseUint32(arg_bad_blocks); if (!parsed || *parsed == 0) { fprintf(stderr, "Expected positive integer for max_bad_blocks but got: %s\n", arg_bad_blocks); return 2; } uint32_t bad_blocks = *parsed; FILE* data_input = fopen(arg_data_input, "r"); if (!data_input) { fprintf(stderr, "Failed to open volume data file: %s\n", arg_data_input); return 2; } FILE* spare_input = fopen(arg_spare_input, "r"); if (!spare_input) { fprintf(stderr, "Failed to open volume spare file: %s\n", arg_spare_input); return 2; } FILE* output_file = fopen(arg_output_file, "w"); if (!data_input) { fprintf(stderr, "Failed to open output file: %s\n", arg_output_file); return 2; } InMemoryRawNand nand; nand.options.page_size = page_size; nand.options.oob_bytes_size = static_cast<uint8_t>(spare_size); nand.options.pages_per_block = block_pages; if (!LoadData(&nand, data_input, spare_input)) { fprintf(stderr, "Failed to load nand data from input files based on given options.\n"); return 3; } fclose(data_input); data_input = nullptr; fclose(spare_input); spare_input = nullptr; if (!WriteVolume(&nand, bad_blocks, output_file)) { fprintf(stderr, "Failed to parse and write out image.\n"); return 4; } fclose(output_file); output_file = nullptr; return 0; }
33.529412
100
0.648421
[ "vector" ]
3aab2340c09295a7d4b50c2b3fa906616476a999
873
hpp
C++
impl/support_for_with_xxx_stm.hpp
alf-p-steinbach/Expressive-Cpp
2d3fb7653a4eccf85cf3077b165f91999ad5f1dc
[ "Unlicense" ]
8
2017-03-31T12:27:10.000Z
2019-09-04T20:18:34.000Z
impl/support_for_with_xxx_stm.hpp
alf-p-steinbach/Expressive-Cpp
2d3fb7653a4eccf85cf3077b165f91999ad5f1dc
[ "Unlicense" ]
null
null
null
impl/support_for_with_xxx_stm.hpp
alf-p-steinbach/Expressive-Cpp
2d3fb7653a4eccf85cf3077b165f91999ad5f1dc
[ "Unlicense" ]
null
null
null
#pragma once // Source encoding: utf-8 ∩ // #include <p/expressive/impl/support_for_with_xxx_stm_.hpp> // Copyright © 2017 Alf P. Steinbach, distributed under Boost license 1.0. #include <p/expressive/core_language/basic_type_builders.hpp> // ref_ namespace progrock{ namespace expressive{ #include <p/expressive/pseudo_keywords/impl/push_macro_definitions.hpp> # include <p/expressive/pseudo_keywords/impl/macro_definitions.hpp> namespace impl { template< class Type > struct Object_holder_for_with_ { Type object; bool is_first_iteration; $func begin() -> Type* { return &object; } $func end() -> Type* { return begin() + 1; } }; } // namespace impl #include <p/expressive/pseudo_keywords/impl/pop_macro_definitions.hpp> }} // namespace progrock::expressive
34.92
74
0.671249
[ "object" ]
3aae424f8753014aab6e5fb067ea432fbc69197f
2,600
cc
C++
cartographer/sensor/internal/voxel_filter.cc
tu-darmstadt-ros-pkg/cartographer
ddbc9464cfc80e7d0b3bd32c068d6e14443cabf4
[ "Apache-2.0" ]
9
2017-05-04T06:57:07.000Z
2021-07-18T17:59:46.000Z
cartographer/sensor/internal/voxel_filter.cc
tu-darmstadt-ros-pkg/hectorgrapher
f04b15b2dbd31004d99d5e5584519416d11ac420
[ "Apache-2.0" ]
1
2020-09-23T10:41:32.000Z
2020-09-23T10:41:32.000Z
cartographer/sensor/internal/voxel_filter.cc
tu-darmstadt-ros-pkg/cartographer
ddbc9464cfc80e7d0b3bd32c068d6e14443cabf4
[ "Apache-2.0" ]
3
2019-09-01T05:47:22.000Z
2021-05-27T07:03:44.000Z
/* * Copyright 2016 The Cartographer Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cartographer/sensor/internal/voxel_filter.h" #include <cmath> #include "cartographer/common/math.h" namespace cartographer { namespace sensor { PointCloud VoxelFilter::Filter(const PointCloud& point_cloud) { PointCloud results; for (const RangefinderPoint& point : point_cloud) { auto it_inserted = voxel_set_.insert(IndexToKey(GetCellIndex(point.position))); if (it_inserted.second) { results.push_back(point); } } return results; } TimedPointCloud VoxelFilter::Filter(const TimedPointCloud& timed_point_cloud) { TimedPointCloud results; for (const TimedRangefinderPoint& point : timed_point_cloud) { auto it_inserted = voxel_set_.insert(IndexToKey(GetCellIndex(point.position))); if (it_inserted.second) { results.push_back(point); } } return results; } std::vector<TimedPointCloudOriginData::RangeMeasurement> VoxelFilter::Filter( const std::vector<TimedPointCloudOriginData::RangeMeasurement>& range_measurements) { std::vector<TimedPointCloudOriginData::RangeMeasurement> results; for (const auto& range_measurement : range_measurements) { auto it_inserted = voxel_set_.insert( IndexToKey(GetCellIndex(range_measurement.point_time.position))); if (it_inserted.second) { results.push_back(range_measurement); } } return results; } VoxelFilter::KeyType VoxelFilter::IndexToKey(const Eigen::Array3i& index) { KeyType k_0(static_cast<uint32>(index[0])); KeyType k_1(static_cast<uint32>(index[1])); KeyType k_2(static_cast<uint32>(index[2])); return (k_0 << 2 * 32) | (k_1 << 1 * 32) | k_2; } Eigen::Array3i VoxelFilter::GetCellIndex(const Eigen::Vector3f& point) const { Eigen::Array3f index = point.array() / resolution_; return Eigen::Array3i(common::RoundToInt(index.x()), common::RoundToInt(index.y()), common::RoundToInt(index.z())); } } // namespace sensor } // namespace cartographer
31.325301
79
0.716923
[ "vector" ]
3aaf11cef6948b4003bfdbedbb95014835c268d8
3,474
hpp
C++
src/ControlSystem/PiecewisePolynomial.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
src/ControlSystem/PiecewisePolynomial.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
src/ControlSystem/PiecewisePolynomial.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <array> #include <cstddef> #include <vector> #include "ControlSystem/FunctionOfTime.hpp" #include "DataStructures/DataVector.hpp" // IWYU pragma: keep /// \ingroup ControlSystemGroup /// Contains functions of time to support the dual frame system. namespace FunctionsOfTime { /// \ingroup ControlSystemGroup /// A function that has a piecewise-constant `MaxDeriv`th derivative. template <size_t MaxDeriv> class PiecewisePolynomial : public FunctionOfTime { public: PiecewisePolynomial( double t, std::array<DataVector, MaxDeriv + 1> initial_func_and_derivs) noexcept; ~PiecewisePolynomial() override = default; PiecewisePolynomial(PiecewisePolynomial&&) noexcept = default; PiecewisePolynomial& operator=(PiecewisePolynomial&&) noexcept = default; PiecewisePolynomial(const PiecewisePolynomial&) = delete; PiecewisePolynomial& operator=(const PiecewisePolynomial&) = delete; /// Returns the function at an arbitrary time `t`. std::array<DataVector, 1> func(double t) const noexcept override { return func_and_derivs<0>(t); } /// Returns the function and its first derivative at an arbitrary time `t`. std::array<DataVector, 2> func_and_deriv(double t) const noexcept override { return func_and_derivs<1>(t); } /// Returns the function and the first two derivatives at an arbitrary time /// `t`. std::array<DataVector, 3> func_and_2_derivs(double t) const noexcept override { return func_and_derivs<2>(t); } /// Updates the `MaxDeriv`th derivative of the function at the given time. /// `updated_max_deriv` is a vector of the `MaxDeriv`ths for each component void update(double time_of_update, DataVector updated_max_deriv) noexcept; /// Returns the domain of validity of the function. std::array<double, 2> time_bounds() const noexcept override { return {{deriv_info_at_update_times_.front().time, deriv_info_at_update_times_.back().time}}; } private: /// Returns the function and `MaxDerivReturned` derivatives at /// an arbitrary time `t`. /// The function has multiple components. template <size_t MaxDerivReturned = MaxDeriv> std::array<DataVector, MaxDerivReturned + 1> func_and_derivs(double t) const noexcept; // There exists a DataVector for each deriv order that contains // the values of that deriv order for all components. using value_type = std::array<DataVector, MaxDeriv + 1>; // Holds information at single time at which the `MaxDeriv`th // derivative has been updated. struct DerivInfo { double time; value_type derivs_coefs; // Constructor is needed for use of emplace_back of a vector // (additionally, the constructor converts the supplied derivs to // coefficients for simplified polynomial evaluation.) DerivInfo(double t, value_type deriv) noexcept; }; /// Returns a DerivInfo corresponding to the closest element in the range of /// DerivInfos with an update time that is less than or equal to `t`. /// The function throws an error if `t` is less than all DerivInfo update /// times. (unless `t` is just less than the earliest update time by roundoff, /// in which case it returns the DerivInfo at the earliest update time.) const DerivInfo& deriv_info_from_upper_bound(double t) const noexcept; std::vector<DerivInfo> deriv_info_at_update_times_; }; } // namespace FunctionsOfTime
39.033708
80
0.74122
[ "vector" ]
3ab6e56b01502f22f50c402dabdd19b2d95ea3c7
32,841
cpp
C++
c/src/dsig/DSIGSignature.cpp
douglascrp/xmlsec-mityc-sinadura
cf63024481914be33ae3a06ef1cc7629dd59aa0f
[ "Apache-2.0" ]
null
null
null
c/src/dsig/DSIGSignature.cpp
douglascrp/xmlsec-mityc-sinadura
cf63024481914be33ae3a06ef1cc7629dd59aa0f
[ "Apache-2.0" ]
null
null
null
c/src/dsig/DSIGSignature.cpp
douglascrp/xmlsec-mityc-sinadura
cf63024481914be33ae3a06ef1cc7629dd59aa0f
[ "Apache-2.0" ]
2
2018-08-10T18:54:23.000Z
2018-08-10T18:56:27.000Z
/* * Copyright 2002-2005 The Apache Software Foundation. * * 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. */ /* * XSEC * * DSIGSignature := Class for checking and setting up signature nodes in a DSIG signature * * Author(s): Berin Lautenbach * * $Id: DSIGSignature.cpp 566299 2007-08-15 18:51:47Z scantor $ * */ // XSEC Includes #include <xsec/dsig/DSIGSignature.hpp> #include <xsec/dsig/DSIGConstants.hpp> #include <xsec/dsig/DSIGKeyInfoX509.hpp> #include <xsec/dsig/DSIGObject.hpp> #include <xsec/dsig/DSIGReference.hpp> #include <xsec/dsig/DSIGTransformList.hpp> #include <xsec/transformers/TXFMDocObject.hpp> #include <xsec/transformers/TXFMOutputFile.hpp> #include <xsec/transformers/TXFMSHA1.hpp> #include <xsec/transformers/TXFMBase64.hpp> #include <xsec/transformers/TXFMC14n.hpp> #include <xsec/transformers/TXFMChain.hpp> #include <xsec/framework/XSECError.hpp> #include <xsec/framework/XSECAlgorithmHandler.hpp> #include <xsec/framework/XSECAlgorithmMapper.hpp> #include <xsec/enc/XSECCryptoKeyDSA.hpp> #include <xsec/enc/XSECCryptoKeyRSA.hpp> #include <xsec/utils/XSECDOMUtils.hpp> #include <xsec/utils/XSECBinTXFMInputStream.hpp> #include <xsec/framework/XSECURIResolver.hpp> #include <xsec/enc/XSECKeyInfoResolver.hpp> #include <xsec/dsig/DSIGKeyInfoValue.hpp> #include <xsec/dsig/DSIGKeyInfoX509.hpp> #include <xsec/dsig/DSIGKeyInfoName.hpp> #include <xsec/dsig/DSIGKeyInfoPGPData.hpp> #include <xsec/dsig/DSIGKeyInfoSPKIData.hpp> #include <xsec/dsig/DSIGKeyInfoMgmtData.hpp> #include <xsec/dsig/DSIGAlgorithmHandlerDefault.hpp> #include <xsec/framework/XSECEnv.hpp> // Xerces includes #include <xercesc/dom/DOMNamedNodeMap.hpp> #include <xercesc/util/Janitor.hpp> XERCES_CPP_NAMESPACE_USE // -------------------------------------------------------------------------------- // Init // -------------------------------------------------------------------------------- void DSIGSignature::Initialise(void) { DSIGAlgorithmHandlerDefault def; // Register default signature algorithm handlers XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_SHA1, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_MD5, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_SHA224, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_SHA256, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_SHA384, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_SHA512, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIDSA_SHA1, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIHMAC_SHA1, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIHMAC_SHA224, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIHMAC_SHA256, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIHMAC_SHA384, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIHMAC_SHA512, def); // Register default hashing algorithm handlers XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURISHA1, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURISHA224, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURISHA256, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURISHA384, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURISHA512, def); XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIMD5, def); } // -------------------------------------------------------------------------------- // Some useful utility functions // -------------------------------------------------------------------------------- #if 0 bool compareBase64StringToRaw(safeBuffer &b64SB, unsigned char * raw, unsigned int rawLen, unsigned int maxCompare = 0) { // Decode a base64 buffer and then compare the result to a raw buffer // Compare at most maxCompare bits (if maxComare > 0) // Note - whilst the other parameters are bytes, maxCompare is bits unsigned char outputStr[1024]; unsigned char b64Str[1024]; unsigned int outputLen = 0; XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64(); if (!b64) { throw XSECException(XSECException::CryptoProviderError, "Error requesting Base64 object from Crypto Provider"); } Janitor<XSECCryptoBase64> j_b64(b64); strncpy((char *) b64Str, (char *) b64SB.rawBuffer(), 1023); b64Str[1023] = '\0'; // Just in case b64->decodeInit(); outputLen = b64->decode((unsigned char *) b64Str, (unsigned int) strlen((char *) b64Str), outputStr, 1024); outputLen += b64->decodeFinish(&outputStr[outputLen], 1024 - outputLen); // Compare div_t d; unsigned int maxCompareBytes, maxCompareBits; maxCompareBits = 0; unsigned int size; if (maxCompare > 0) { d = div(maxCompare, 8); maxCompareBytes = d.quot; if (d.rem != 0) maxCompareBytes++; if (rawLen < maxCompareBytes && outputLen < maxCompareBytes) { if (rawLen != outputLen) return false; size = rawLen; } else if (rawLen < maxCompareBytes || outputLen < maxCompareBytes) { return false; } else size = maxCompareBytes; } else { if (rawLen != outputLen) return false; size = rawLen; } // Compare bytes unsigned int i, j; for (i = 0; i < size; ++ i) { if (raw[i] != outputStr[i]) return false; } // Compare bits char mask = 0x01; if (maxCompare != 0) { for (j = 0 ; j < (unsigned int) d.rem; ++i) { if ((raw[i] & mask) != (outputStr[i] & mask)) return false; mask = mask << 1; } } return true; } void convertRawToBase64String(safeBuffer &b64SB, unsigned char * raw, unsigned int rawLen, unsigned int maxBits = 0) { // Translate the rawbuffer (at most maxBits or rawLen - whichever is smaller) // to a base64 string unsigned char b64Str[1024]; unsigned int outputLen = 0; XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64(); if (!b64) { throw XSECException(XSECException::CryptoProviderError, "Error requesting Base64 object from Crypto Provider"); } Janitor<XSECCryptoBase64> j_b64(b64); // Determine length to translate unsigned int size; if (maxBits > 0) { div_t d = div(maxBits, 8); size = d.quot; if (d.rem != 0) ++size; if (size > rawLen) size = rawLen; } else size = rawLen; b64->encodeInit(); outputLen = b64->encode((unsigned char *) raw, rawLen, b64Str, 1024); outputLen += b64->encodeFinish(&b64Str[outputLen], 1024 - outputLen); b64Str[outputLen] = '\0'; // Copy out b64SB.sbStrcpyIn((char *) b64Str); } #endif /* 0 */ // -------------------------------------------------------------------------------- // Get the Canonicalised BYTE_STREAM of the SignedInfo // -------------------------------------------------------------------------------- XSECBinTXFMInputStream * DSIGSignature::makeBinInputStream(void) const { TXFMBase * txfm; // Create the starting point for the transform list XSECnew(txfm, TXFMDocObject(mp_doc)); TXFMChain * chain; XSECnew(chain, TXFMChain(txfm)); Janitor<TXFMChain> j_chain(chain); ((TXFMDocObject *) txfm)->setInput(mp_doc, mp_signedInfo->getDOMNode()); // canonicalise the SignedInfo content switch (mp_signedInfo->getCanonicalizationMethod()) { case CANON_C14N_NOC : XSECnew(txfm, TXFMC14n(mp_doc)); chain->appendTxfm(txfm); txfm->stripComments(); break; case CANON_C14N_COM : XSECnew(txfm, TXFMC14n(mp_doc)); chain->appendTxfm(txfm); txfm->activateComments(); break; case CANON_C14NE_NOC : XSECnew(txfm, TXFMC14n(mp_doc)); chain->appendTxfm(txfm); ((TXFMC14n *) txfm)->setExclusive(); txfm->stripComments(); break; case CANON_C14NE_COM : XSECnew(txfm, TXFMC14n(mp_doc)); chain->appendTxfm(txfm); ((TXFMC14n *) txfm)->setExclusive(); txfm->activateComments(); break; default : throw XSECException(XSECException::SigVfyError, "Canonicalisation method unknown in DSIGSignature::makeBinInputStream()"); } // Now create the InputStream XSECBinTXFMInputStream * ret; ret = new XSECBinTXFMInputStream(chain); j_chain.release(); return ret; } // -------------------------------------------------------------------------------- // Get the list of references // -------------------------------------------------------------------------------- DSIGReferenceList * DSIGSignature::getReferenceList(void) { return mp_signedInfo->getReferenceList(); } const DSIGReferenceList * DSIGSignature::getReferenceList(void) const { return mp_signedInfo->getReferenceList(); } // -------------------------------------------------------------------------------- // Set and Get Resolvers // -------------------------------------------------------------------------------- void DSIGSignature::setURIResolver(XSECURIResolver * resolver) { mp_env->setURIResolver(resolver); } XSECURIResolver * DSIGSignature::getURIResolver(void) const { return mp_env->getURIResolver(); } void DSIGSignature::setKeyInfoResolver(XSECKeyInfoResolver * resolver) { if (mp_KeyInfoResolver != 0) delete mp_KeyInfoResolver; mp_KeyInfoResolver = resolver->clone(); } XSECKeyInfoResolver * DSIGSignature::getKeyInfoResolver(void) const { return mp_KeyInfoResolver; } // -------------------------------------------------------------------------------- // Object Handling // -------------------------------------------------------------------------------- DSIGObject * DSIGSignature::appendObject(void) { DSIGObject * ret; XSECnew(ret, DSIGObject(mp_env)); DOMElement * elt = ret->createBlankObject(); mp_sigNode->appendChild(elt); mp_env->doPrettyPrint(mp_sigNode); m_objects.push_back(ret); return ret; } int DSIGSignature::getObjectLength(void) const { return (unsigned int) m_objects.size(); } DSIGObject * DSIGSignature::getObjectItem(int i) { if ( i < 0 || i >= ((int) m_objects.size())) { throw XSECException(XSECException::ObjectError, "DSIGSignature::getObjectItem - index out of range"); } return m_objects[i]; } const DSIGObject * DSIGSignature::getObjectItem(int i) const { if ( i < 0 || i >= ((int) m_objects.size())) { throw XSECException(XSECException::ObjectError, "DSIGSignature::getObjectItem - index out of range"); } return m_objects[i]; } // -------------------------------------------------------------------------------- // Signature // -------------------------------------------------------------------------------- // Constructors and Destructors DSIGSignature::DSIGSignature(DOMDocument *doc, DOMNode *sigNode) : m_keyInfoList(0), m_errStr("") { mp_doc = doc; mp_sigNode = sigNode; mp_signingKey = NULL; mp_signedInfo = NULL; mp_KeyInfoResolver = NULL; mp_KeyInfoNode = NULL; m_loaded = false; m_interlockingReferences = false; // Set up our formatter XSECnew(mp_formatter, XSECSafeBufferFormatter("UTF-8",XMLFormatter::NoEscapes, XMLFormatter::UnRep_CharRef)); // Set up the environment XSECnew(mp_env, XSECEnv(doc)); m_keyInfoList.setEnvironment(mp_env); } DSIGSignature::DSIGSignature(void) : m_keyInfoList(0), m_errStr("") { mp_doc = NULL; mp_sigNode = NULL; mp_signingKey = NULL; mp_signedInfo = NULL; mp_KeyInfoResolver = NULL; mp_KeyInfoNode = NULL; m_loaded = false; m_interlockingReferences = false; // Set up our formatter XSECnew(mp_formatter, XSECSafeBufferFormatter("UTF-8",XMLFormatter::NoEscapes, XMLFormatter::UnRep_CharRef)); XSECnew(mp_env, XSECEnv(NULL)); m_keyInfoList.setEnvironment(mp_env); } DSIGSignature::~DSIGSignature() { if (mp_env != NULL) delete mp_env; if (mp_signingKey != NULL) { delete mp_signingKey; mp_signingKey = NULL; } if (mp_signedInfo != NULL) { delete mp_signedInfo; mp_signedInfo = NULL; } if (mp_formatter != NULL) { delete mp_formatter; mp_formatter = NULL; } if (mp_KeyInfoResolver != NULL) { delete mp_KeyInfoResolver; mp_KeyInfoResolver = NULL; } // Delete any object items for (int i = 0; i < ((int) m_objects.size()); ++i) { delete (m_objects[i]); } } // Actions const XMLCh * DSIGSignature::getErrMsgs() const { return m_errStr.rawXMLChBuffer(); } // -------------------------------------------------------------------------------- // Pretty Printing // -------------------------------------------------------------------------------- void DSIGSignature::setPrettyPrint(bool flag) { mp_env->setPrettyPrintFlag(flag); } bool DSIGSignature::getPrettyPrint(void) const { return mp_env->getPrettyPrintFlag(); } // -------------------------------------------------------------------------------- // Creating signatures from blank // -------------------------------------------------------------------------------- void DSIGSignature::setDSIGNSPrefix(const XMLCh * prefix) { mp_env->setDSIGNSPrefix(prefix); } void DSIGSignature::setECNSPrefix(const XMLCh * prefix) { mp_env->setECNSPrefix(prefix); } void DSIGSignature::setXPFNSPrefix(const XMLCh * prefix) { mp_env->setXPFNSPrefix(prefix); } // get const XMLCh * DSIGSignature::getDSIGNSPrefix() const { return mp_env->getDSIGNSPrefix(); } const XMLCh * DSIGSignature::getECNSPrefix() const { return mp_env->getECNSPrefix(); } const XMLCh * DSIGSignature::getXPFNSPrefix() const { return mp_env->getXPFNSPrefix(); } // -------------------------------------------------------------------------------- // Creating Blank Signature // -------------------------------------------------------------------------------- DOMElement *DSIGSignature::createBlankSignature(DOMDocument *doc, canonicalizationMethod cm, signatureMethod sm, hashMethod hm) { // This is now deprecated. Because this is so, we go the long way - translate // to URI and then call the "standard" method, which will translate back to // internal enums if possible const XMLCh * cURI; safeBuffer sURI; if ((cURI = canonicalizationMethod2UNICODEURI(cm)) == NULL) { throw XSECException(XSECException::UnknownCanonicalization, "DSIGSignature::createBlankSignature - Canonicalisation method unknown"); } if (signatureHashMethod2URI(sURI, sm, hm) == false) { throw XSECException(XSECException::UnknownSignatureAlgorithm, "DSIGSignature::createBlankSignature - Signature/Hash method unknown"); } return createBlankSignature(doc, cURI, sURI.sbStrToXMLCh()); } DOMElement *DSIGSignature::createBlankSignature( DOMDocument *doc, const XMLCh * canonicalizationAlgorithmURI, const XMLCh * signatureAlgorithmURI) { // "New" method to create a blank signature, based on URIs. mp_doc = doc; mp_env->setParentDocument(doc); const XMLCh * prefixNS = mp_env->getDSIGNSPrefix(); safeBuffer str; makeQName(str, prefixNS, "Signature"); DOMElement *sigNode = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer()); if (prefixNS[0] == '\0') { str.sbTranscodeIn("xmlns"); } else { str.sbTranscodeIn("xmlns:"); str.sbXMLChCat(prefixNS); } sigNode->setAttributeNS(DSIGConstants::s_unicodeStrURIXMLNS, str.rawXMLChBuffer(), DSIGConstants::s_unicodeStrURIDSIG); mp_sigNode = sigNode; mp_env->doPrettyPrint(mp_sigNode); // Create the skeleton SignedInfo XSECnew(mp_signedInfo, DSIGSignedInfo(mp_doc, mp_formatter, mp_env)); mp_sigNode->appendChild(mp_signedInfo->createBlankSignedInfo( canonicalizationAlgorithmURI, signatureAlgorithmURI)); mp_env->doPrettyPrint(mp_sigNode); // Create a dummy signature value (dummy until signed) makeQName(str, mp_env->getDSIGNSPrefix(), "SignatureValue"); DOMElement *sigValNode = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer()); mp_signatureValueNode = sigValNode; mp_sigNode->appendChild(sigValNode); mp_env->doPrettyPrint(mp_sigNode); // Some text to mark this as a template only sigValNode->appendChild(doc->createTextNode(MAKE_UNICODE_STRING("Not yet signed"))); m_loaded = true; return sigNode; } // -------------------------------------------------------------------------------- // Creating References // -------------------------------------------------------------------------------- DSIGReference * DSIGSignature::createReference(const XMLCh * URI, hashMethod hm, char * type) { return mp_signedInfo->createReference(URI, hm, type); } DSIGReference * DSIGSignature::createReference( const XMLCh * URI, const XMLCh * hashAlgorithmURI, const XMLCh * type) { return mp_signedInfo->createReference(URI, hashAlgorithmURI, type); } // -------------------------------------------------------------------------------- // Manipulation of KeyInfo elements // -------------------------------------------------------------------------------- void DSIGSignature::clearKeyInfo(void) { if (mp_KeyInfoNode == 0) return; if (mp_sigNode->removeChild(mp_KeyInfoNode) != mp_KeyInfoNode) { throw XSECException(XSECException::ExpectedDSIGChildNotFound, "Attempted to remove KeyInfo node but it is no longer a child of <Signature>"); } mp_KeyInfoNode->release(); // No longer required mp_KeyInfoNode = NULL; // Clear out the list m_keyInfoList.empty(); } void DSIGSignature::createKeyInfoElement(void) { if (mp_KeyInfoNode != NULL) return; safeBuffer str; makeQName(str, mp_env->getDSIGNSPrefix(), "KeyInfo"); mp_KeyInfoNode = m_keyInfoList.createKeyInfo(); // Append the node to the end of the signature DOMNode * afterSignatureValue = mp_signatureValueNode->getNextSibling(); while (afterSignatureValue != 0 && afterSignatureValue->getNodeType() != DOMNode::ELEMENT_NODE) afterSignatureValue = afterSignatureValue->getNextSibling(); if (afterSignatureValue == 0) { mp_sigNode->appendChild(mp_KeyInfoNode); mp_env->doPrettyPrint(mp_sigNode); } else { mp_sigNode->insertBefore(mp_KeyInfoNode, afterSignatureValue); if (mp_env->getPrettyPrintFlag() == true) mp_sigNode->insertBefore(mp_doc->createTextNode(DSIGConstants::s_unicodeStrNL), afterSignatureValue); } } DSIGKeyInfoValue * DSIGSignature::appendDSAKeyValue(const XMLCh * P, const XMLCh * Q, const XMLCh * G, const XMLCh * Y) { createKeyInfoElement(); return m_keyInfoList.appendDSAKeyValue(P, Q, G, Y); } DSIGKeyInfoValue * DSIGSignature::appendRSAKeyValue(const XMLCh * modulus, const XMLCh * exponent) { createKeyInfoElement(); return m_keyInfoList.appendRSAKeyValue(modulus, exponent); } DSIGKeyInfoX509 * DSIGSignature::appendX509Data(void) { createKeyInfoElement(); return m_keyInfoList.appendX509Data(); } DSIGKeyInfoName * DSIGSignature::appendKeyName(const XMLCh * name, bool isDName) { createKeyInfoElement(); return m_keyInfoList.appendKeyName(name, isDName); } DSIGKeyInfoPGPData * DSIGSignature::appendPGPData(const XMLCh * id, const XMLCh * packet) { createKeyInfoElement(); return m_keyInfoList.appendPGPData(id, packet); } DSIGKeyInfoSPKIData * DSIGSignature::appendSPKIData(const XMLCh * sexp) { createKeyInfoElement(); return m_keyInfoList.appendSPKIData(sexp); } DSIGKeyInfoMgmtData * DSIGSignature::appendMgmtData(const XMLCh * data) { createKeyInfoElement(); return m_keyInfoList.appendMgmtData(data); } // -------------------------------------------------------------------------------- // Working on Existing templates // -------------------------------------------------------------------------------- void DSIGSignature::load(void) { // Load all the information from the source document into local variables for easier // manipulation by the other functions in the class if (mp_sigNode == NULL) { // Attempt to load an empty signature element throw XSECException(XSECException::LoadEmptySignature); } if (!strEquals(getDSIGLocalName(mp_sigNode), "Signature")) { throw XSECException(XSECException::LoadNonSignature); } m_loaded = true; // Find the prefix being used so that we can later use it to manipulate the signature mp_env->setDSIGNSPrefix(mp_sigNode->getPrefix()); // Now check for SignedInfo DOMNode *tmpElt = mp_sigNode->getFirstChild(); while (tmpElt != 0 && (tmpElt->getNodeType() != DOMNode::ELEMENT_NODE)) // Skip text and comments tmpElt = tmpElt->getNextSibling(); if (tmpElt == 0 || !strEquals(getDSIGLocalName(tmpElt), "SignedInfo")) { throw XSECException(XSECException::ExpectedDSIGChildNotFound, "Expected <SignedInfo> as first child of <Signature>"); } // Have a signed info XSECnew(mp_signedInfo, DSIGSignedInfo(mp_doc, mp_formatter, tmpElt, mp_env)); mp_signedInfo->load(); // Look at Signature Value tmpElt = tmpElt->getNextSibling(); while (tmpElt != 0 && tmpElt->getNodeType() != DOMNode::ELEMENT_NODE) tmpElt = tmpElt->getNextSibling(); if (tmpElt == 0 || !strEquals(getDSIGLocalName(tmpElt), "SignatureValue")) { throw XSECException(XSECException::ExpectedDSIGChildNotFound, "Expected <SignatureValue> node"); } DOMNode *tmpSV = tmpElt->getFirstChild(); while (tmpSV != 0 && tmpSV->getNodeType() != DOMNode::TEXT_NODE) tmpSV = tmpSV->getNextSibling(); if (tmpSV == 0) throw XSECException(XSECException::ExpectedDSIGChildNotFound, "Expected TEXT child of <SignatureValue>"); mp_signatureValueNode = tmpElt; // The signature value is transcoded to local code page, as it is easier // to work with, and should be low ASCII in any case (Base64) m_signatureValueSB.sbTranscodeIn(tmpSV->getNodeValue()); // Now look at KeyInfo tmpElt = tmpElt->getNextSibling(); while (tmpElt != 0 && !((tmpElt->getNodeType() == DOMNode::ELEMENT_NODE) && strEquals(getDSIGLocalName(tmpElt), "KeyInfo"))) tmpElt = tmpElt->getNextSibling(); if (tmpElt != 0 && strEquals(getDSIGLocalName(tmpElt), "KeyInfo")) { // Have a keyInfo mp_KeyInfoNode = tmpElt; // In case we later want to manipulate it m_keyInfoList.loadListFromXML(tmpElt); tmpElt = findNextElementChild(tmpElt); } while (tmpElt != 0 && strEquals(getDSIGLocalName(tmpElt), "Object")) { DSIGObject * obj; XSECnew(obj, DSIGObject(mp_env, tmpElt)); obj->load(); m_objects.push_back(obj); tmpElt = findNextElementChild(tmpElt); } /* * Strictly speaking, this should remain, but it causes too many problems with non * conforming signatures if (tmpElt != 0) { throw XSECException(XSECException::ExpectedDSIGChildNotFound, "DSIGSignature::load - Unexpected (non Object) Element found at end of signature"); } */ } TXFMChain * DSIGSignature::getSignedInfoInput(void) { TXFMBase * txfm; TXFMChain * chain; // First we calculate the hash. Start off by creating a starting point XSECnew(txfm, TXFMDocObject(mp_doc)); XSECnew(chain, TXFMChain(txfm)); Janitor<TXFMChain> j_chain(chain); ((TXFMDocObject *) txfm)->setInput(mp_doc, mp_signedInfo->getDOMNode()); // canonicalise the SignedInfo content switch (mp_signedInfo->getCanonicalizationMethod()) { case CANON_C14N_NOC : XSECnew(txfm, TXFMC14n(mp_doc)); chain->appendTxfm(txfm); txfm->stripComments(); break; case CANON_C14N_COM : XSECnew(txfm, TXFMC14n(mp_doc)); chain->appendTxfm(txfm); txfm->activateComments(); break; case CANON_C14NE_NOC : XSECnew(txfm, TXFMC14n(mp_doc)); chain->appendTxfm(txfm); ((TXFMC14n *) txfm)->setExclusive(); txfm->stripComments(); break; case CANON_C14NE_COM : XSECnew(txfm, TXFMC14n(mp_doc)); chain->appendTxfm(txfm); ((TXFMC14n *) txfm)->setExclusive(); txfm->activateComments(); break; default : throw XSECException(XSECException::SigVfyError, "Canonicalisation method unknown in DSIGSignature::calculateSignedInfoHash()"); } j_chain.release(); return chain; } unsigned int DSIGSignature::calculateSignedInfoHash(unsigned char * hashBuf, unsigned int hashBufLen) { // Get the SignedInfo input bytes TXFMChain * chain = getSignedInfoInput(); Janitor<TXFMChain> j_chain(chain); // Setup Hash // First find the appropriate handler for the URI XSECAlgorithmHandler * handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler( mp_signedInfo->getAlgorithmURI()); if (handler == NULL) { throw XSECException(XSECException::SigVfyError, "Hash method unknown in DSIGSignature::calculateSignedInfoHash()"); } if (!handler->appendSignatureHashTxfm(chain, mp_signedInfo->getAlgorithmURI(), mp_signingKey)) { throw XSECException(XSECException::SigVfyError, "Unexpected error in handler whilst appending Signature Hash transform"); } #if 0 TXFMOutputFile * of = new TXFMOutputFile(mp_doc); of->setFile("Output"); of->setInput(hashVal); hashVal=of; #endif // Write hash to the buffer int hashLen; hashLen = chain->getLastTxfm()->readBytes((XMLByte *) hashBuf, hashBufLen); return hashLen; } unsigned int DSIGSignature::calculateSignedInfoAndReferenceHash(unsigned char * hashBuf, unsigned int hashBufLen) { // Set up the reference list hashes - including any manifests mp_signedInfo->hash(m_interlockingReferences); // calculaet signed InfoHash return calculateSignedInfoHash(hashBuf,hashBufLen); } // -------------------------------------------------------------------------------- // Verify a signature // -------------------------------------------------------------------------------- bool DSIGSignature::verifySignatureOnlyInternal(void) { unsigned char hash[4096]; int hashLen; if (!m_loaded) { // Need to call "load" prior to checking a signature throw XSECException(XSECException::SigVfyError, "DSIGSignature::verify() called prior to DSIGSignature::load()"); } // Try to find a key if (mp_signingKey == NULL) { // // Try to load a key from the KeyInfo list // if ((mp_signingKey = m_keyInfoList.findKey()) == NULL) { // throw XSECException(XSECException::SigVfyError, // "DSIGSignature::verify() - no verification key loaded and cannot determine from KeyInfo list"); // } if (mp_KeyInfoResolver == NULL) { throw XSECException(XSECException::SigVfyError, "DSIGSignature::verify() - no verification key loaded and no KeyInfoResolver loaded"); } if ((mp_signingKey = mp_KeyInfoResolver->resolveKey(&m_keyInfoList)) == NULL) { throw XSECException(XSECException::SigVfyError, "DSIGSignature::verify() - no verification key loaded and cannot determine from KeyInfoResolver"); } } // Get the SignedInfo input bytes TXFMChain * chain = getSignedInfoInput(); Janitor<TXFMChain> j_chain(chain); hashLen = calculateSignedInfoHash(hash, 4096); // Now set up to verify // First find the appropriate handler for the URI XSECAlgorithmHandler * handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler( mp_signedInfo->getAlgorithmURI()); if (handler == NULL) { throw XSECException(XSECException::SigVfyError, "Hash method unknown in DSIGSignature::verifySignatureOnlyInternal()"); } bool sigVfyRet = handler->verifyBase64Signature(chain, mp_signedInfo->getAlgorithmURI(), m_signatureValueSB.rawCharBuffer(), mp_signedInfo->getHMACOutputLength(), mp_signingKey); if (!sigVfyRet) m_errStr.sbXMLChCat("Validation of <SignedInfo> failed"); return sigVfyRet; } bool DSIGSignature::verifySignatureOnly(void) { m_errStr.sbTranscodeIn(""); return verifySignatureOnlyInternal(); } bool DSIGSignature::verify(void) { // We have a (hopefully) fully loaded signature. Need to // verify bool referenceCheckResult; if (!m_loaded) { // Need to call "load" prior to checking a signature throw XSECException(XSECException::SigVfyError, "DSIGSignature::verify() called prior to DSIGSignature::load()"); } // Reset m_errStr.sbXMLChIn(DSIGConstants::s_unicodeStrEmpty); // First thing to do is check the references referenceCheckResult = mp_signedInfo->verify(m_errStr); // Check the signature bool sigVfyResult = verifySignatureOnlyInternal(); return sigVfyResult & referenceCheckResult; } // -------------------------------------------------------------------------------- // Sign the XML document that has been previously loaded // -------------------------------------------------------------------------------- void DSIGSignature::sign(void) { // We have a (hopefully) fully loaded signature. Need to // sign if (!m_loaded) { // Need to call "load" prior to checking a signature throw XSECException(XSECException::SigVfyError, "DSIGSignature::sign() called prior to DSIGSignature::load()"); } // Check we have a key if (mp_signingKey == NULL) { throw XSECException(XSECException::SigVfyError, "DSIGSignature::sign() - no signing key loaded"); } // Reset error string in case we have any reference problems. m_errStr.sbXMLChIn(DSIGConstants::s_unicodeStrEmpty); // Set up the reference list hashes - including any manifests mp_signedInfo->hash(m_interlockingReferences); // Get the SignedInfo input bytes TXFMChain * chain = getSignedInfoInput(); Janitor<TXFMChain> j_chain(chain); // Calculate the hash to be signed safeBuffer b64Buf; XSECAlgorithmHandler * handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler( mp_signedInfo->getAlgorithmURI()); if (handler == NULL) { throw XSECException(XSECException::SigVfyError, "Hash method unknown in DSIGSignature::sign()"); } if (!handler->signToSafeBuffer(chain, mp_signedInfo->getAlgorithmURI(), mp_signingKey, mp_signedInfo->getHMACOutputLength(), b64Buf)) { throw XSECException(XSECException::SigVfyError, "Unexpected error in handler whilst appending Signature Hash transform"); } // Now we have the signature - place it in the DOM structures DOMNode *tmpElt = mp_signatureValueNode->getFirstChild(); while (tmpElt != NULL && tmpElt->getNodeType() != DOMNode::TEXT_NODE) tmpElt = tmpElt->getNextSibling(); if (tmpElt == NULL) { // Need to create the underlying TEXT_NODE DOMDocument * doc = mp_signatureValueNode->getOwnerDocument(); tmpElt = doc->createTextNode(b64Buf.sbStrToXMLCh()); mp_signatureValueNode->appendChild(tmpElt); } else { tmpElt->setNodeValue(b64Buf.sbStrToXMLCh()); } // And copy to the local buffer m_signatureValueSB = b64Buf; } // -------------------------------------------------------------------------------- // Key Management // -------------------------------------------------------------------------------- void DSIGSignature::setSigningKey(XSECCryptoKey *k) { if (mp_signingKey != NULL) delete mp_signingKey; mp_signingKey = k; } // -------------------------------------------------------------------------------- // ID Handling // -------------------------------------------------------------------------------- /* * ID handling is really all done within the environment object - just pass the * calls straight through */ void DSIGSignature::setIdByAttributeName(bool flag) { mp_env->setIdByAttributeName(flag); } bool DSIGSignature::getIdByAttributeName(void) const { return mp_env->getIdByAttributeName(); } void DSIGSignature::registerIdAttributeName(const XMLCh * name) { mp_env->registerIdAttributeName(name); } bool DSIGSignature::deregisterIdAttributeName(const XMLCh * name) { return mp_env->deregisterIdAttributeName(name); } void DSIGSignature::registerIdAttributeNameNS(const XMLCh * ns, const XMLCh * name) { mp_env->registerIdAttributeNameNS(ns, name); } bool DSIGSignature::deregisterIdAttributeNameNS(const XMLCh * ns, const XMLCh * name) { return mp_env->deregisterIdAttributeNameNS(ns, name); } // -------------------------------------------------------------------------------- // Other functions // -------------------------------------------------------------------------------- const XMLCh * DSIGSignature::getSignatureValue(void) const { if (mp_signatureValueNode == NULL) return NULL; return findFirstChildOfType(mp_signatureValueNode, DOMNode::TEXT_NODE)->getNodeValue(); }
25.418731
108
0.665753
[ "object", "transform" ]
3abab7b5660372915b0996b21f75b01e088ff908
23,666
cpp
C++
src/nn.cpp
JakobWyatt/MachineLearning
a52bc5b352e122e44ea7d29d8565b405cc915b54
[ "Apache-2.0" ]
1
2017-12-30T05:10:02.000Z
2017-12-30T05:10:02.000Z
src/nn.cpp
JakobWyatt/MachineLearning
a52bc5b352e122e44ea7d29d8565b405cc915b54
[ "Apache-2.0" ]
null
null
null
src/nn.cpp
JakobWyatt/MachineLearning
a52bc5b352e122e44ea7d29d8565b405cc915b54
[ "Apache-2.0" ]
null
null
null
//Copyright 2017 Jakob Wyatt // //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 "nn.h" #include <stdexcept> #include <vector> #include <utility> #include <fstream> #include <iterator> #include <memory> #include <functional> #include <algorithm> #include "math.h" //we will only error-check if the project is in debug mode //we use the _DEBUG macro to check for this namespace nn { data::data(int flag) : _data(0) { switch (flag) { case mnisttest: { _data = mnisttestload(); break; } case mnisttrain: { _data = mnisttrainload(); break; } case XOR: { _data = generateXOR(); break; } default: { throw std::invalid_argument("invalid flag"); break; } } } data::data(std::vector<std::pair<math::matrix, math::matrix>> data) : _data(data) { //empty function //no need to error check as function is private } data::size_type data::size() const { return this->_data.size(); } math::matrix::size_type data::inputheight() const { return this->_data[0].first.height(); } math::matrix::size_type data::inputwidth() const { return this->_data[0].first.width(); } math::matrix::size_type data::outputheight() const { return this->_data[0].second.height(); } math::matrix::size_type data::outputwidth() const { return this->_data[0].second.width(); } data data::shuffle() const { data result(*this); std::shuffle(result._data.begin(), result._data.end(), math::default_random_engine()); return result; } data data::trim(size_type size) const { return data(std::vector<std::pair<math::matrix, math::matrix>>(this->_data.begin(), this->_data.begin() + size)); } const std::pair<math::matrix, math::matrix>& data::operator[](data::size_type element) const { #ifdef _DEBUG if (element < 0 || element >= this->size()) { throw std::out_of_range("out of range"); } #endif return this->_data[element]; } std::vector<std::pair<math::matrix, math::matrix>> data::mnisttestload() { std::ifstream images("./../data/mnist/t10k-images.idx3-ubyte", std::ios::binary); std::ifstream labels("./../data/mnist/t10k-labels.idx1-ubyte", std::ios::binary); #ifdef _DEBUG if (!images.is_open() || !labels.is_open()) { throw std::runtime_error("could not open file"); } #endif std::vector<unsigned char> imagesvec((std::istreambuf_iterator<char>(images)), std::istreambuf_iterator<char>()); std::vector<unsigned char> labelsvec((std::istreambuf_iterator<char>(labels)), std::istreambuf_iterator<char>()); std::vector<std::pair<math::matrix, math::matrix>> result(10000); std::vector<math::num> image(784); for (std::vector<std::pair<math::matrix, math::matrix>>::size_type i = 0; i != 10000; ++i) { result[i].second = math::matrix::onehotmatrix(10, 1, static_cast<math::matrix::size_type>(labelsvec[i + 8]), 0); for (std::vector<math::num>::size_type j = 0; j != 784; ++j) { image[j] = static_cast<math::num>(imagesvec[784 * i + 16 + j]) / 256; } result[i].first = math::matrix(image, 1); } return result; } std::vector<std::pair<math::matrix, math::matrix>> data::mnisttrainload() { std::ifstream images("./../data/mnist/train-images.idx3-ubyte", std::ios::binary); std::ifstream labels("./../data/mnist/train-labels.idx1-ubyte", std::ios::binary); #ifdef _DEBUG if (!images.is_open() || !labels.is_open()) { throw std::runtime_error("could not open file"); } #endif std::vector<unsigned char> imagesvec((std::istreambuf_iterator<char>(images)), std::istreambuf_iterator<char>()); std::vector<unsigned char> labelsvec((std::istreambuf_iterator<char>(labels)), std::istreambuf_iterator<char>()); std::vector<std::pair<math::matrix, math::matrix>> result(60000); std::vector<math::num> image(784); for (std::vector<std::pair<math::matrix, math::matrix>>::size_type i = 0; i != 60000; ++i) { result[i].second = math::matrix::onehotmatrix(10, 1, static_cast<math::matrix::size_type>(labelsvec[i + 8]), 0); for (std::vector<math::num>::size_type j = 0; j != 784; ++j) { image[j] = static_cast<math::num>(imagesvec[784 * i + 16 + j]) / 256; } result[i].first = math::matrix(image, 1); } return result; } nn::nn(std::initializer_list<layer*> layers) : _data(0) { std::initializer_list<layer*>::const_iterator end = layers.end(); for (std::initializer_list<layer*>::const_iterator i = layers.begin(); i != end; ++i) { _data.push_back(std::move((*i)->clone())); } #ifdef _DEBUG std::vector<std::unique_ptr<layer>>::size_type size = _data.size(); if (size == 0) { throw std::invalid_argument("no layers were given"); } for (std::vector<std::unique_ptr<layer>>::size_type i = 0; i != size - 1; ++i) { layer::size_type currentoutputwidth = _data[i]->outputwidth(); layer::size_type nextinputwidth = _data[i + 1]->inputwidth(); layer::size_type currentoutputheight = _data[i]->outputheight(); layer::size_type nextinputheight = _data[i + 1]->inputheight(); if (currentoutputwidth != nextinputwidth || currentoutputheight != nextinputheight) { throw std::invalid_argument("layer sizes do not match"); } } #endif } std::vector<std::pair<math::matrix, math::matrix>> data::generateXOR() { std::vector<std::pair<math::matrix, math::matrix>> result(5000); for (data::size_type i = 0; i != 5000; ++i) { result[i].first = math::matrix(2, 1, math::bernoullidist); //evaluate logical XOR if (result[i].first[0] == 1) { if (result[i].first[1] == 1) { result[i].second = math::matrix(1, 1, { 0 }); } else { result[i].second = math::matrix(1, 1, { 1 }); } } else { if (result[i].first[1] == 1) { result[i].second = math::matrix(1, 1, { 1 }); } else { result[i].second = math::matrix(1, 1, { 0 }); } } } return result; } nn::size_type nn::size() const { return this->_data.size(); } //preallocation is not used, as in this function, the output is only evaluated once math::matrix nn::evaluate(const math::matrix& input) const { #ifdef _DEBUG if (input.width() != this->_data[0]->inputwidth() || input.height() != this->_data[0]->inputheight()) { throw std::invalid_argument("input size is incompatible"); } #endif size_type size = this->size(); math::matrix result(input); for (size_type i = 0; i != size; ++i) { result = this->_data[i]->evaluate(result); } return result; } void nn::train(const data& learningdata, math::num learningrate, data::size_type batchsize) { data::size_type batchnum = learningdata.size()/batchsize; nn::size_type nnsize = this->size(); #ifdef _DEBUG if (this->_data[0]->inputheight() != learningdata.inputheight() || this->_data[0]->inputwidth() != learningdata.inputwidth()) { throw std::invalid_argument("input data is incompatible"); } if (this->_data[nnsize - 1]->outputheight() != learningdata.outputheight() || this->_data[nnsize - 1]->outputwidth() != learningdata.outputwidth()) { throw std::invalid_argument("output data is incompatible"); } #endif //get our minibatch pointers std::vector<void*> minibatchptr(this->allocateminibatch()); //get our iteration pointers std::vector<void*> iterationptr(this->allocateiteration()); //preallocate buffers math::matrix resultbuffer(this->_data[nnsize - 1]->outputheight(), this->_data[nnsize - 1]->outputwidth()); math::matrix inputerrorbuffer(this->_data[0]->inputheight(), this->_data[0]->inputwidth()); std::vector<math::matrix> buffervec; for (nn::size_type i = 0; i != nnsize; ++i) { math::matrix buffer(this->_data[i]->outputheight(), this->_data[i]->outputwidth()); buffervec.push_back(buffer); } //iterate across our batches for (data::size_type i = 0; i != batchnum; ++i) { //iterate over a minibatch for (data::size_type j = 0; j != batchsize; ++j) { //feedforward this->_data[0]->feedforward(learningdata[i * batchsize + j].first, buffervec[0], iterationptr[0], minibatchptr[0]); for (nn::size_type k = 1; k != nnsize; ++k) { this->_data[k]->feedforward(buffervec[k - 1], buffervec[k], iterationptr[k], minibatchptr[k]); } //calculate difference between output and desired (aL - y) math::matrix::subtract(buffervec[nnsize - 1], learningdata[i * batchsize + j].second, resultbuffer); //backpropagate the error this->_data[nnsize - 1]->backprop(resultbuffer, buffervec[nnsize - 1], iterationptr[nnsize - 1], minibatchptr[nnsize - 1]); for (nn::size_type k = nnsize - 2; k != 0; --k) { this->_data[k]->backprop(buffervec[k], buffervec[k - 1], iterationptr[k], minibatchptr[k]); } this->_data[0]->backprop(buffervec[0], inputerrorbuffer, iterationptr[0], minibatchptr[0]); } this->update(minibatchptr, learningrate); } //deallocate our memory this->deallocateiteration(iterationptr); this->deallocateminibatch(minibatchptr); } data::size_type nn::test(const data& input, std::function<bool(const math::matrix&, const math::matrix&, math::matrix&)> compare) const { nn::size_type nnsize = this->size(); data::size_type datasize = input.size(); #ifdef _DEBUG if (this->_data[0]->inputheight() != input.inputheight() || this->_data[0]->inputwidth() != input.inputwidth()) { throw std::invalid_argument("input data is incompatible"); } if (this->_data[nnsize - 1]->outputheight() != input.outputheight() || this->_data[nnsize - 1]->outputwidth() != input.outputwidth()) { throw std::invalid_argument("output data is incompatible"); } #endif //preallocate buffers data::size_type numcorrect = 0; std::vector<math::matrix> buffervec; math::matrix resultbuffer(this->_data[nnsize - 1]->outputheight(), this->_data[nnsize - 1]->outputwidth()); for (nn::size_type i = 0; i != nnsize; ++i) { math::matrix buffer(this->_data[i]->outputheight(), this->_data[i]->outputwidth()); buffervec.push_back(buffer); } for (data::size_type i = 0; i != datasize; ++i) { this->_data[0]->evaluate(input[i].first, buffervec[0]); for (nn::size_type j = 1; j != nnsize; ++j) { this->_data[j]->evaluate(buffervec[j - 1], buffervec[j]); } if (compare(input[i].second, buffervec[nnsize - 1], resultbuffer)) { ++numcorrect; } } return numcorrect; } math::num nn::cost(const data& input, std::function<math::num(const math::matrix& correct, const math::matrix& output)> cost) { nn::size_type nnsize = this->size(); data::size_type datasize = input.size(); #ifdef _DEBUG if (this->_data[0]->inputheight() != input.inputheight() || this->_data[0]->inputwidth() != input.inputwidth()) { throw std::invalid_argument("input data is incompatible"); } if (this->_data[nnsize - 1]->outputheight() != input.outputheight() || this->_data[nnsize - 1]->outputwidth() != input.outputwidth()) { throw std::invalid_argument("output data is incompatible"); } #endif //preallocate buffers math::num costsum = 0; std::vector<math::matrix> buffervec; for (nn::size_type i = 0; i != nnsize; ++i) { math::matrix buffer(this->_data[i]->outputheight(), this->_data[i]->outputwidth()); buffervec.push_back(buffer); } for (data::size_type i = 0; i != datasize; ++i) { this->_data[0]->evaluate(input[i].first, buffervec[0]); for (nn::size_type j = 1; j != nnsize; ++j) { this->_data[j]->evaluate(buffervec[j - 1], buffervec[j]); } costsum += cost(input[i].second, buffervec[nnsize - 1]); } //reconsider this cost value, as it could be too small for a ML algorithm to pick up return costsum / datasize; } void nn::update(const std::vector<void*>& minibatch, math::num learningrate) { nn::size_type nnsize = this->size(); #ifdef _DEBUG if (nnsize != minibatch.size()) { throw std::invalid_argument("vec of minibatch ptr has incompatible size"); } #endif for (nn::size_type i = 0; i != nnsize; ++i) { this->_data[i]->update(minibatch[i], learningrate); } } std::vector<void*> nn::allocateminibatch() const { std::vector<void*> minibatchptr; nn::size_type nnsize = this->size(); for (nn::size_type i = 0; i != nnsize; ++i) { minibatchptr.push_back(this->_data[i]->allocateminibatch()); } return minibatchptr; } void nn::deallocateminibatch(const std::vector<void*>& minibatchptr) const { nn::size_type nnsize = this->size(); #ifdef _DEBUG if (nnsize != minibatchptr.size()) { throw std::invalid_argument("vec of minibatch ptr has incompatible size"); } #endif for (nn::size_type i = 0; i != nnsize; ++i) { this->_data[i]->deallocateminibatch(minibatchptr[i]); } } std::vector<void*> nn::allocateiteration() const { std::vector<void*> iterationptr; nn::size_type nnsize = this->size(); for (nn::size_type i = 0; i != nnsize; ++i) { iterationptr.push_back(this->_data[i]->allocateiteration()); } return iterationptr; } void nn::deallocateiteration(const std::vector<void*>& iterationptr) const { nn::size_type nnsize = this->size(); #ifdef _DEBUG if (nnsize != iterationptr.size()) { throw std::invalid_argument("vec of iteration ptr has incompatible size"); } #endif for (nn::size_type i = 0; i != nnsize; ++i) { this->_data[i]->deallocateiteration(iterationptr[i]); } } sigmoid::sigmoid(size_type height, size_type width) : _height(height), _width(width) { #ifdef _DEBUG if (height <= 0 || width <= 0) { throw std::invalid_argument("empty layer initialization"); } #endif } sigmoid::size_type sigmoid::inputwidth() const { return this->_width; } sigmoid::size_type sigmoid::inputheight() const { return this->_height; } sigmoid::size_type sigmoid::outputwidth() const { return this->_width; } sigmoid::size_type sigmoid::outputheight() const { return this->_height; } math::matrix sigmoid::evaluate(const math::matrix& input) const { #ifdef _DEBUG if (this->inputheight() != input.height() || this->inputwidth() != input.width()) { throw std::invalid_argument("input matrix is incompatible"); } #endif return input(math::sigmoid); } std::unique_ptr<layer> sigmoid::clone() const { std::unique_ptr<layer> ptr(new sigmoid(*this)); return std::move(ptr); } void* sigmoid::allocateminibatch() const { return nullptr; } void sigmoid::deallocateminibatch(void* minibatchptr) const { //empty virtual function } void* sigmoid::allocateiteration() const { return new math::matrix(this->inputheight(), this->inputwidth()); } void sigmoid::deallocateiteration(void* iterationptr) const { delete static_cast<math::matrix*>(iterationptr); } void sigmoid::update(void* minibatchptr, math::num learningrate) { //empty virtual function } void sigmoid::feedforward(const math::matrix& input, math::matrix& output, void* iterationptr, void* minibatchptr) const { #ifdef _DEBUG if (this->inputheight() != input.height() || this->inputwidth() != input.width()) { throw std::invalid_argument("input matrix is incompatible"); } if (this->outputheight() != output.height() || this->outputwidth() != output.width()) { throw std::invalid_argument("output matrix is incompatible"); } #endif math::matrix* itptr = static_cast<math::matrix*>(iterationptr); *itptr = input; math::matrix::function(math::sigmoid, input, output); } void sigmoid::backprop(const math::matrix& errorin, math::matrix& errorout, void* iterationptr, void* minibatchptr) const { #ifdef _DEBUG if (this->inputheight() != errorout.height() || this->inputwidth() != errorout.width()) { throw std::invalid_argument("error out has incompatible size"); } if (this->outputheight() != errorin.height() || this->outputwidth() != errorin.width()) { throw std::invalid_argument("error in has incompatible size"); } #endif math::matrix* itptr = static_cast<math::matrix*>(iterationptr); math::matrix::function(math::sigmoidprime, *itptr, *itptr); math::matrix::hadamard(errorin, *itptr, errorout); } void sigmoid::evaluate(const math::matrix& input, math::matrix& output) const { #ifdef _DEBUG if (this->inputheight() != input.height() || this->inputwidth() != input.width()) { throw std::invalid_argument("input matrix is incompatible"); } if (this->outputheight() != output.height() || this->outputwidth() != output.width()) { throw std::invalid_argument("output matrix is incompatible"); } #endif math::matrix::function(math::sigmoid, input, output); } weights::weights(size_type inputheight, size_type outputheight, std::function<math::num()> func) : _data(outputheight, inputheight, func) { #ifdef _DEBUG if (inputheight <= 0 || outputheight <= 0) { throw std::invalid_argument("empty weights initalization"); } #endif } weights::size_type weights::inputwidth() const { return 1; } weights::size_type weights::inputheight() const { return this->_data.width(); } weights::size_type weights::outputwidth() const { return 1; } weights::size_type weights::outputheight() const { return this->_data.height(); } math::matrix weights::evaluate(const math::matrix& input) const { #ifdef _DEBUG if (this->inputheight() != input.height() || this->inputwidth() != input.width()) { throw std::invalid_argument("input matrix is incompatible"); } #endif return this->_data * input; } std::unique_ptr<layer> weights::clone() const { std::unique_ptr<layer> ptr(new weights(*this)); return std::move(ptr); } //the first pair member holds the accumalated derivatives, //while the second is a buffer for backprop void* weights::allocateminibatch() const { return new std::pair<math::matrix, math::matrix> (math::matrix(this->_data.height(), this->_data.width()), math::matrix(this->_data.height(), this->_data.width())); } void weights::deallocateminibatch(void* minibatchptr) const { delete static_cast<std::pair<math::matrix, math::matrix>*>(minibatchptr); } void* weights::allocateiteration() const { return new math::matrix(this->inputheight(), 1); } void weights::deallocateiteration(void* iterationptr) const { delete static_cast<math::matrix*>(iterationptr); } void weights::update(void* minibatchptr, math::num learningrate) { std::pair<math::matrix, math::matrix>* ptr = static_cast<std::pair<math::matrix, math::matrix>*>(minibatchptr); math::matrix::multiply(ptr->first, -learningrate, ptr->first); math::matrix::add(this->_data, ptr->first, this->_data); ptr->first = math::matrix(this->_data.height(), this->_data.width()); } void weights::feedforward(const math::matrix& input, math::matrix& output, void* iterationptr, void* minibatchptr) const { #ifdef _DEBUG if (this->inputheight() != input.height() || this->inputwidth() != input.width()) { throw std::invalid_argument("input matrix is incompatible"); } if (this->outputheight() != output.height() || this->outputwidth() != output.width()) { throw std::invalid_argument("output matrix is incompatible"); } #endif math::matrix* itptr = static_cast<math::matrix*>(iterationptr); *itptr = input; math::matrix::multiply(this->_data, input, output); } void weights::backprop(const math::matrix& errorin, math::matrix& errorout, void* iterationptr, void* minibatchptr) const { #ifdef _DEBUG if (this->inputheight() != errorout.height() || this->inputwidth() != errorout.width()) { throw std::invalid_argument("errorout has incompatible size"); } if (this->outputheight() != errorin.height() || this->outputwidth() != errorin.width()) { throw std::invalid_argument("errorin has incompatible size"); } #endif //get our pointers math::matrix* itptr = static_cast<math::matrix*>(iterationptr); std::pair<math::matrix, math::matrix>* batchptr = static_cast<std::pair<math::matrix, math::matrix>*>(minibatchptr); //calculate the derivatives math::matrix::righttransposedmultiply(errorin, *itptr, batchptr->second); math::matrix::add(batchptr->second, batchptr->first, batchptr->first); //backprop the error math::matrix::lefttransposedmultiply(this->_data, errorin, errorout); } void weights::evaluate(const math::matrix& input, math::matrix& output) const { #ifdef _DEBUG if (this->inputheight() != input.height() || this->inputwidth() != input.width()) { throw std::invalid_argument("input matrix is incompatible"); } if (this->outputheight() != output.height() || this->outputwidth() != output.width()) { throw std::invalid_argument("output matrix is incompatible"); } #endif math::matrix::multiply(this->_data, input, output); } biases::biases(size_type height, size_type width) : _data(height, width) { #ifdef _DEBUG if (height <= 0 || width <= 0) { throw std::invalid_argument("empty biases initalization"); } #endif } biases::size_type biases::inputwidth() const { return this->_data.width(); } biases::size_type biases::inputheight() const { return this->_data.height(); } biases::size_type biases::outputwidth() const { return this->_data.width(); } biases::size_type biases::outputheight() const { return this->_data.height(); } math::matrix biases::evaluate(const math::matrix& input) const { #ifdef _DEBUG if (input.width() != this->inputwidth() || input.height() != this->inputheight()) { throw std::invalid_argument("input has incompatible size"); } #endif return input + this->_data; } std::unique_ptr<layer> biases::clone() const { std::unique_ptr<layer> ptr(new biases(*this)); return std::move(ptr); } void* biases::allocateminibatch() const { return new math::matrix(this->_data.height(), this->_data.width()); } void biases::deallocateminibatch(void* minibatchptr) const { delete static_cast<math::matrix*>(minibatchptr); } void* biases::allocateiteration() const { return nullptr; } void biases::deallocateiteration(void* iterationptr) const { //empty virtual function } void biases::update(void* minibatchptr, math::num learningrate) { math::matrix* batchptr = static_cast<math::matrix*>(minibatchptr); math::matrix::multiply(*batchptr, -learningrate, *batchptr); math::matrix::add(*batchptr, this->_data, this->_data); *batchptr = math::matrix(this->_data.height(), this->_data.width()); } void biases::feedforward(const math::matrix& input, math::matrix& output, void* iterationptr, void* minibatchptr) const { #ifdef _DEBUG if (this->inputheight() != input.height() || this->inputwidth() != input.width()) { throw std::invalid_argument("input matrix is incompatible"); } if (this->outputheight() != output.height() || this->outputwidth() != output.width()) { throw std::invalid_argument("output matrix is incompatible"); } #endif math::matrix::add(input, this->_data, output); } void biases::backprop(const math::matrix& errorin, math::matrix& errorout, void* iterationptr, void* minibatchptr) const { #ifdef _DEBUG if (this->inputheight() != errorout.height() || this->inputwidth() != errorout.width()) { throw std::invalid_argument("error out has incompatible size"); } if (this->outputheight() != errorin.height() || this->outputwidth() != errorin.width()) { throw std::invalid_argument("error in has incompatible size"); } #endif math::matrix* batchptr = static_cast<math::matrix*>(minibatchptr); math::matrix::add(*batchptr, errorin, *batchptr); errorout = errorin; } void biases::evaluate(const math::matrix& input, math::matrix& output) const { #ifdef _DEBUG if (this->inputheight() != input.height() || this->inputwidth() != input.width()) { throw std::invalid_argument("input matrix is incompatible"); } if (this->outputheight() != output.height() || this->outputwidth() != output.width()) { throw std::invalid_argument("output matrix is incompatible"); } #endif math::matrix::add(input, this->_data, output); } }
32.198639
150
0.691034
[ "vector" ]
3abdf63812b83919da91a32fb95b50c30ae2f3a3
1,382
cpp
C++
src/RigidBody/GeneralizedCoordinates.cpp
Amedeo123/biorbd
ac4a2bba2662342243d7df60b3afff59253e64e8
[ "MIT" ]
1
2021-09-13T08:55:28.000Z
2021-09-13T08:55:28.000Z
src/RigidBody/GeneralizedCoordinates.cpp
Amedeo123/biorbd
ac4a2bba2662342243d7df60b3afff59253e64e8
[ "MIT" ]
2
2018-04-18T19:31:23.000Z
2018-04-18T19:40:17.000Z
src/RigidBody/GeneralizedCoordinates.cpp
pyomeca/rbdl_interface
238065f9267816b987b49955c97c9d14ff04ffa7
[ "MIT" ]
1
2020-02-27T15:35:04.000Z
2020-02-27T15:35:04.000Z
#define BIORBD_API_EXPORTS #include "RigidBody/GeneralizedCoordinates.h" #include "RigidBody/Joints.h" using namespace BIORBD_NAMESPACE; rigidbody::GeneralizedCoordinates::GeneralizedCoordinates() { } rigidbody::GeneralizedCoordinates::GeneralizedCoordinates( unsigned int nbQ) : utils::Vector(nbQ) { } rigidbody::GeneralizedCoordinates::GeneralizedCoordinates( const rigidbody::Joints &j) : utils::Vector(j.nbQ()) { } rigidbody::GeneralizedCoordinates::GeneralizedCoordinates( const rigidbody::GeneralizedCoordinates &Q) : utils::Vector(Q) { } rigidbody::GeneralizedCoordinates::GeneralizedCoordinates( const RigidBodyDynamics::Math::VectorNd &v) : utils::Vector (v) { } #ifdef BIORBD_USE_CASADI_MATH rigidbody::GeneralizedCoordinates::GeneralizedCoordinates( const casadi::MX &v) : utils::Vector(v) { } #endif rigidbody::GeneralizedCoordinates::~GeneralizedCoordinates() { } void rigidbody::GeneralizedCoordinates::operator=( const utils::Vector &other) { this->utils::Vector::operator=(other); } #ifdef BIORBD_USE_CASADI_MATH void rigidbody::GeneralizedCoordinates::operator=( const RBDLCasadiMath::MX_Xd_SubMatrix &other) { this->utils::Vector::operator=(other); } void rigidbody::GeneralizedCoordinates::operator=( const casadi::MX &other) { this->utils::Vector::operator=(other); } #endif
17.717949
60
0.743849
[ "vector" ]
3ac4e9626dbe73403fa9c0556bc9fb48c2cd2385
7,441
cpp
C++
examples/spla_sssp.cpp
mfkiwl/spla
9a7515f6ff5176bc0250734a09aac0fcafbfd3da
[ "MIT" ]
null
null
null
examples/spla_sssp.cpp
mfkiwl/spla
9a7515f6ff5176bc0250734a09aac0fcafbfd3da
[ "MIT" ]
null
null
null
examples/spla_sssp.cpp
mfkiwl/spla
9a7515f6ff5176bc0250734a09aac0fcafbfd3da
[ "MIT" ]
null
null
null
/**********************************************************************************/ /* This file is part of spla project */ /* https://github.com/JetBrains-Research/spla */ /**********************************************************************************/ /* MIT License */ /* */ /* Copyright (c) 2021 JetBrains-Research */ /* */ /* 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 <cxxopts.hpp> #include <spla-algo/SplaAlgo.hpp> #include <spla-cpp/Spla.hpp> int main(int argc, const char *const *argv) { cxxopts::Options options("spla-sssp", "SSSP (single source shortest paths) algorithm with spla library"); options.add_option("", cxxopts::Option("h,help", "display help info", cxxopts::value<bool>()->default_value("false"))); options.add_option("", cxxopts::Option("mtxpath", "path to matrix file", cxxopts::value<std::string>())); options.add_option("", cxxopts::Option("niters", "number of iterations to run", cxxopts::value<int>()->default_value("4"))); options.add_option("", cxxopts::Option("source", "source vertex to run bfs", cxxopts::value<int>()->default_value("0"))); options.add_option("", cxxopts::Option("bsize", "size of block to store matrix/vector", cxxopts::value<int>()->default_value("10000000"))); options.add_option("", cxxopts::Option("devices-count", "amount of devices for execution", cxxopts::value<int>()->default_value("1"))); options.add_option("", cxxopts::Option("undirected", "force graph to be undirected", cxxopts::value<bool>()->default_value("false"))); options.add_option("", cxxopts::Option("verbose", "verbose std output", cxxopts::value<bool>()->default_value("true"))); options.add_option("", cxxopts::Option("platform", "opencl platform to select", cxxopts::value<std::string>()->default_value(""))); options.add_option("", cxxopts::Option("dense-factor", "factor used to dense transition", cxxopts::value<float>()->default_value("0.1f"))); options.add_option("", cxxopts::Option("debug-timing", "timing for each iteration of algorithm", cxxopts::value<bool>()->default_value("false"))); cxxopts::ParseResult args; try { args = options.parse(argc, argv); } catch (const std::exception &e) { std::cerr << "Failed parse input arguments: " << e.what(); return 1; } if (args["help"].as<bool>()) { std::cout << options.help(); return 0; } std::string mtxpath; int niters; int source; int bsize; int devicesCount; bool undirected; bool removeLoops = true; bool ignoreValues = true; bool verbose; bool debugTiming; float denseFactor; std::string platform; try { mtxpath = args["mtxpath"].as<std::string>(); niters = args["niters"].as<int>(); source = args["source"].as<int>(); bsize = args["bsize"].as<int>(); devicesCount = args["devices-count"].as<int>(); undirected = args["undirected"].as<bool>(); verbose = args["verbose"].as<bool>(); debugTiming = args["debug-timing"].as<bool>(); denseFactor = args["dense-factor"].as<float>(); platform = args["platform"].as<std::string>(); } catch (const std::exception &e) { std::cerr << "Invalid input arguments: " << e.what(); return 1; } assert(niters > 0); assert(source >= 0); assert(bsize > 1); assert(devicesCount >= 1); // Load data spla::MatrixLoader<float> loader; try { loader.Load(mtxpath, undirected, removeLoops, ignoreValues, verbose); } catch (const std::exception &e) { std::cerr << "Failed load matrix: " << e.what(); return 1; } assert(loader.GetNrows() == loader.GetNcols()); // Fill matrix uniformly with 1 loader.Fill(1.0f); spla::Library::Config config; config.SetBlockSize(bsize); config.SetWorkersCount(devicesCount * devicesCount); config.LimitAmount(devicesCount); config.SetPlatform(platform); spla::Library library(config); // Output info about devices for evaluation if (verbose) std::cout << library.PrintContextConfig() << std::endl; // v and M bfs args spla::RefPtr<spla::Vector> v; spla::RefPtr<spla::Matrix> A = spla::Matrix::Make(loader.GetNrows(), loader.GetNcols(), spla::Types::Float32(library), library); // Data is sorted without duplicated values spla::RefPtr<spla::Descriptor> dataDesc = spla::Descriptor::Make(library); dataDesc->SetParam(spla::Descriptor::Param::ValuesSorted); dataDesc->SetParam(spla::Descriptor::Param::NoDuplicates); // Prepare data and fill A spla::RefPtr<spla::Expression> prepareData = spla::Expression::Make(library); prepareData->MakeDataWrite(A, spla::DataMatrix::Make(loader.GetRowIndices().data(), loader.GetColIndices().data(), loader.GetValues().data(), loader.GetNvals(), library), dataDesc); prepareData->SubmitWait(); SPLA_ALGO_CHECK(prepareData); spla::RefPtr<spla::Descriptor> desc = spla::Descriptor::Make(library); desc->SetParam(spla::Descriptor::Param::ProfileTime, debugTiming); desc->SetParam(spla::Descriptor::Param::DenseFactor, std::to_string(denseFactor)); // Warm up phase spla::CpuTimer tWarmUp; tWarmUp.Start(); spla::Sssp(v, A, source, desc); tWarmUp.Stop(); // Main phase, measure iterations std::vector<spla::CpuTimer> tIters(niters); for (int i = 0; i < niters; i++) { tIters[i].Start(); spla::Sssp(v, A, source, desc); tIters[i].Stop(); } spla::OutputMeasurements(tWarmUp, tIters); return 0; }
47.698718
185
0.578014
[ "vector" ]
3ac5b5d641c0747c33dbb9cac7dfa24401a85d01
733
cpp
C++
form_greatest_no_in_array.cpp
ujjaldas1997/Competitive-programming
f8526161b3b14056633ec290b0c65ba762e8552e
[ "MIT" ]
null
null
null
form_greatest_no_in_array.cpp
ujjaldas1997/Competitive-programming
f8526161b3b14056633ec290b0c65ba762e8552e
[ "MIT" ]
null
null
null
form_greatest_no_in_array.cpp
ujjaldas1997/Competitive-programming
f8526161b3b14056633ec290b0c65ba762e8552e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool comp(string a, string b){ return (a + b < b + a) ? 1 : 0; } void show(vector<string> box){ for(string i : box) cout << i << " "; cout << endl; return; } void fetch_greatest_no(vector<string> box){ sort(box.begin(), box.end(), comp); //show(box); string res = ""; for(string i : box) res = i + res; cout << res << endl; return; } int main() { //code int T = 0; cin >> T; for(int i = 0; i < T; ++i){ int n = 0; cin >> n; vector<string> box(n, ""); for(int j = 0; j < n; ++j){ int temp; cin >> temp; box[j] = to_string(temp); } fetch_greatest_no(box); } return 0; }
19.289474
43
0.488404
[ "vector" ]