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
bf5d1473322ba7f4af2bf09c6f19d695915a5c2c
3,485
cpp
C++
source/VulkanDebug.cpp
RobertBeckebans/CVCT_Vulkan
edd8e9865f126ffbdf474a6e419d46efc4c7f267
[ "MIT" ]
null
null
null
source/VulkanDebug.cpp
RobertBeckebans/CVCT_Vulkan
edd8e9865f126ffbdf474a6e419d46efc4c7f267
[ "MIT" ]
null
null
null
source/VulkanDebug.cpp
RobertBeckebans/CVCT_Vulkan
edd8e9865f126ffbdf474a6e419d46efc4c7f267
[ "MIT" ]
1
2021-04-09T09:20:20.000Z
2021-04-09T09:20:20.000Z
#include "VulkanDebug.h" #include <windows.h> #include <math.h> #include <stdlib.h> #include <string> #include <cstring> #include <fstream> #include <assert.h> #include <stdio.h> #include <vector> #include <fcntl.h> #include <io.h> #include <iostream> #include <vulkan.h> namespace VKDebug { int validationLayerCount = 1; const char *validationLayerNames[] = { // This is a meta layer that enables all of the standard // validation layers in the correct order : // threading, parameter_validation, device_limits, object_tracker, image, core_validation, swapchain, and unique_objects "VK_LAYER_LUNARG_standard_validation" }; PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback; PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback; PFN_vkDebugReportMessageEXT dbgBreakCallback; VkDebugReportCallbackEXT msgCallback; VkBool32 MessageCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void* pUserData) { char *message = (char *)malloc(strlen(pMsg) + 100); assert(message); if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { std::cout << "ERROR: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n"; } else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { // Uncomment to see warnings std::cout << "WARNING: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n"; } else { return false; } fflush(stdout); free(message); return false; } void SetupDebugging(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportCallbackEXT callBack) { CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); dbgBreakCallback = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT"); VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {}; dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; dbgCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)MessageCallback; dbgCreateInfo.flags = flags; VkResult err = CreateDebugReportCallback( instance, &dbgCreateInfo, nullptr, (callBack != nullptr) ? &callBack : &msgCallback); assert(!err); } void freeDebugCallback(VkInstance instance) { if (msgCallback != VK_NULL_HANDLE) { DestroyDebugReportCallback(instance, msgCallback, nullptr); } } /*PFN_vkDebugMarkerSetObjectNameEXT DebugMarkerSetObjectName = VK_NULL_HANDLE; PFN_vkCmdDebugMarkerBeginEXT CmdDebugMarkerBegin = VK_NULL_HANDLE; PFN_vkCmdDebugMarkerEndEXT CmdDebugMarkerEnd = VK_NULL_HANDLE; PFN_vkCmdDebugMarkerInsertEXT CmdDebugMarkerInsert = VK_NULL_HANDLE; // Set up the debug marker function pointers void SetupDebugMarkers(VkDevice device) { DebugMarkerSetObjectName = (PFN_vkDebugMarkerSetObjectNameEXT)vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectNameEXT"); CmdDebugMarkerBegin = (PFN_vkCmdDebugMarkerBeginEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerBeginEXT"); CmdDebugMarkerEnd = (PFN_vkCmdDebugMarkerEndEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerEndEXT"); CmdDebugMarkerInsert = (PFN_vkCmdDebugMarkerInsertEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerInsertEXT"); }*/ }
31.972477
135
0.773888
[ "vector" ]
bf669f2acfef228b4d5bbb72fcd5c9c13e9a91f4
4,255
cpp
C++
Codejam/2015/1C/main.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
1
2017-10-01T00:51:39.000Z
2017-10-01T00:51:39.000Z
Codejam/2015/1C/main.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
Codejam/2015/1C/main.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define M_PI 3.14159265358979323846 /* pi */ #define ff(i,s,n) for(int i=(s);i<(n);i++) #define fr(i,s,n) for(int i=(n-1);i>=(s);i--) #define FF(i,s,n) for(int i=(s);i<=(n);i++) #define Fr(i,s,n) for(int i=(n);i>=(s);i--) #define FR(i,s,n) for(int i=(n);i>=(s);i--) #define all(a) a.begin(),a.end() #define tnm typename #define invd inline void #define templ1 template<tnm T> #define btempl templ1 invd #define ln prln() #define sp prsp() invd init(int n){ char buff[100]; sprintf(buff,"xx/%d.txt",n); #ifndef ONLINE_JUDGE freopen(buff,"r",stdin); #endif } using namespace std;typedef int64_t ll;typedef unsigned int uint; invd scan(char&s){int c;while((c=getchar())=='\n'||c==' '||c=='\r');s=c;}; invd pr(ll i){printf("%" PRId64 ,i);} invd scan(int&i){scanf("%d",&i);}invd scan(double&i){scanf("%lf",&i);}invd scan(ll&i){scanf("%" PRId64 ,&i);}invd pr(string&s){cout<<s;} template<typename T, typename V> invd scan(pair<T,V>&a){scan(a.first),scan(a.second);} invd scan(string&s){int c;while((c=getchar())=='\n'||c==' '||c=='\r');do{switch(c){case'\n':case'\r':return;default:s+=c;}}while((c=getchar())!=EOF);}; invd pr(char c){putchar(c);};invd pr(const char*c){while(*c!=0)putchar(*c++);} invd pr(int i){printf("%d",i);}invd pr(bool b){pr((int)b);}invd pr(double d){printf("%.9lf",d);}invd prln(){putchar('\n');}invd prsp(){putchar(' ');} btempl scan(char*s){int c;while((c=getchar())){switch(c){case'\n':case'\r':case' ':break;default:*s++=c;}}*s=0;}; template<typename T, typename... Args>invd scan(T&first, Args (&... args)) {scan(first),scan(args...);} template<typename T>invd pr(T arg) {arg.print();} template<class A, class B> invd pr(pair<A,B> a){pr(a.first),sp,pr(a.second);} btempl prsp(vector<T>&v){for(const T&t:v)pr(t),sp;}btempl prsp(T*a,int n){while(n--)pr(*a++),sp;}btempl prln(vector<T>&v){for(const T&t:v)pr(t),ln;} btempl pr(vector<T>&v){prsp(v);} invd pr(size_t i){pr((ll)i);}btempl scan(vector<T>&v){for(T&t:v)scan(t);}btempl scan(T*a,int n){while(n--)scan(*a++);} btempl prln(T*a,int n){while(n--)pr(*a++),ln;}btempl prln(vector<vector<T> >&v){for(vector<T>&t:v)prsp(t),ln;} template<typename T, typename... Args>invd pr(T first, Args... args) {pr(first),sp,pr(args...);} templ1 vector<T>& operator+=(vector<T>& v,T x) {v.push_back(x);return v;} templ1 vector<T>& operator--(vector<T>& v) {v.pop_back();return v;}templ1 vector<T>& operator--(vector<T>& v,int) {v.pop_back();return v;} templ1 bool operator!(stack<T>&q) {return !q.empty();}templ1 stack<T>& operator+=(stack<T>& v,T x) {v.push(x);return v;} templ1 T operator--(stack<T>& v) {v.pop();return v.top();}templ1 T operator--(stack<T>& v,int) {T t=v.top();v.pop();return t;} templ1 bool operator!(queue<T>&q) {return !q.empty();}templ1 queue<T>& operator+=(queue<T>& v,T x) {v.push(x);return v;} templ1 T operator--(queue<T>& v) {v.pop();return v.front();}templ1 T operator--(queue<T>& v,int) {T t=v.front();v.pop();return t;} template<tnm T,tnm U>invd smax(T&a,U b){if(b>a)a=b;}template<tnm T,tnm U>invd smin(T&a,U b){if(b<a)a=b;} template<tnm T,tnm U>inline T gcd(T a, U b){return __gcd(a,b);}typedef vector<int> vi;typedef vector<vi > vvi;typedef pair<int, int> pii;typedef pair<ll,ll> pll; typedef vector<pii > vpii; const ll MOD = 1E9+7; const ll linf=~(1ll<<63); const int inf=~(1<<31); const int sk = 1E9; int solve(){ int k, l, s; scan(k,l,s); vi keyprob(255,0); { string keys; scan(keys); for(char c:keys) keyprob[c]++; } string target; scan(target); int overlap = 1; ff(i,1,target.size()){ bool ok = 1; ff(j,i,target.size()){ if(target[j]!=target[j-i]){ ok = 0; break; } } if(ok){ break; } overlap++; } int bstart = 1 + (s-l)/overlap; double prob = 1; for(char c:target){ prob = prob*keyprob[c]/k; } if(prob == 0){ pr(0.); return 0; } prob = prob*(s-l+1); pr(bstart-prob); } init(){ freopen("e:/users/johan/downloads/B-large.in","r",stdin); freopen("output.txt","w",stdout); } int main(){ init(); int t; scan(t); ff(i,0,t){ printf("Case #%d: ",i+1); solve(); ln; } }
39.766355
162
0.591304
[ "vector" ]
bf6dfc914ef8a0b43b4f232b0dd452363c1e638e
3,458
cpp
C++
12-smart-pointers/1-musician/main.cpp
tehilabk/cpp-5781
736ed05dddb2a7270bbcdbb04a3ffb4b9046e358
[ "MIT" ]
6
2020-03-19T13:49:17.000Z
2020-05-27T16:04:37.000Z
12-smart-pointers/1-musician/main.cpp
erelsgl-at-ariel/cpp-5780
181ae712a05031f85fe3f9f7b16c5e60350e1577
[ "MIT" ]
null
null
null
12-smart-pointers/1-musician/main.cpp
erelsgl-at-ariel/cpp-5780
181ae712a05031f85fe3f9f7b16c5e60350e1577
[ "MIT" ]
23
2020-03-12T13:21:29.000Z
2021-02-22T21:29:48.000Z
/** * A demo of C pointers vs. smart pointers. * * Authors: Eran Kaufmann, Erel Segal-Halevi * Since: 2020-06 */ #include <iostream> #include <vector> #include <cstdlib> #include "musician.hpp" #include "AutoPointer.hpp" #include "UniquePointer.hpp" #include "SharedPointer.hpp" using namespace std; // Play music with C-style pointers void playMusic1 (int numMusicians) { vector<Musician*> band (numMusicians); for (int i = 0; i < numMusicians; ++i) band[i] = new Musician(to_string(i)); for (int i = 0; i < numMusicians; ++i) band[i]->play(); cout << endl << endl << "All musicians in band are playing!" << endl << endl; for (int i = 0; i < numMusicians; ++i) delete band[i]; } // Play music with Java-style finally block - does not work in C++ #if Java void playMusic2 (int numMusicians) { vector<Musician*> band (numMusicians); for (int i = 0; i < numMusicians; ++i) band[i] = new Musician(to_string(i)); try { for (int i = 0; i < numMusicians; ++i) band[i]->play(); cout << endl << endl << "All musicians in band are playing!" << endl << endl; } finally { for (int i = 0; i < numMusicians; ++i) delete band[i]; } } #endif // Play music with smart auto-pointers void playMusic3 (int numMusicians) { vector<AutoPointer<Musician>> band (numMusicians); for (int i = 0; i < numMusicians; ++i) band[i] = new Musician(to_string(i)); for (int i = 0; i < numMusicians; ++i) band[i]->play(); cout << endl << endl << "All musicians in band are playing!" << endl << endl; // AutoPointer<Musician> other1 = band[0]; // Does not compile // AutoPointer<Musician> other2; other2 = band[0]; // Does not compile } UniquePointer<Musician> musician_with_a_random_name(int i) { UniquePointer<Musician> new_musician = new Musician("m_"+to_string(i)+"_"+to_string(rand())); return new_musician; } UniquePointer<Musician> champion1; // Play music with smart unique-pointers void playMusic4 (int numMusicians) { vector<UniquePointer<Musician>> band (numMusicians); for (int i = 0; i < numMusicians; ++i) band[i] = musician_with_a_random_name(i); delete &(*band[0]); UniquePointer<Musician> other2 = move(band[2]); UniquePointer<Musician> other3; other3 = move(band[3]); champion1 = move(band[4]); for (int i = 0; i < numMusicians; ++i) band[i]->play(); cout << endl << endl << "All musicians in band are playing!" << endl << endl; } SharedPointer<Musician> shared_musician_with_a_random_name(int i) { SharedPointer<Musician> new_musician = new Musician("m_"+to_string(i)+"_"+to_string(rand())); return new_musician; } SharedPointer<Musician> champion2; // Play music with smart shared-pointers void playMusic5 (int numMusicians) { vector<SharedPointer<Musician>> band (numMusicians); for (int i = 0; i < numMusicians; ++i) band[i] = new Musician(to_string(i)); //shared_musician_with_a_random_name(i); SharedPointer<Musician> other2 = band[2]; SharedPointer<Musician> other3; other3 = band[3]; champion2 = band[4]; for (int i = 0; i < numMusicians; ++i) band[i]->play(); cout << endl << endl << "All musicians in band are playing!" << endl << endl; } int main () { int numMusicans = 7; try { playMusic1(numMusicans); } catch (TooNoisy& noisy) { cout << endl << endl << "It is too noisy here! " << noisy.getNumMusicians() << " musicians are playing concurrently! Stop Playing!" << endl << endl; } }
25.614815
150
0.659051
[ "vector" ]
bf71e9bbd964bb33bd8d224ef5f4128fb165ee4c
2,617
cpp
C++
ClassesAttackOfOzones/AppDelegate.cpp
conorH22/AttackOfOzones
4290a759fede6e3ba041a0fc145cc309378f9b2d
[ "MIT" ]
1
2018-12-24T16:52:03.000Z
2018-12-24T16:52:03.000Z
ClassesAttackOfOzones/AppDelegate.cpp
conorH22/AttackOfOzones
4290a759fede6e3ba041a0fc145cc309378f9b2d
[ "MIT" ]
2
2018-05-21T09:27:18.000Z
2019-02-06T15:03:58.000Z
ClassesAttackOfOzones/AppDelegate.cpp
conorH22/AttackOfOzones
4290a759fede6e3ba041a0fc145cc309378f9b2d
[ "MIT" ]
null
null
null
#include "AppDelegate.h" #include "Level1.h" #include "MainMenu.h" //cocos2d namespace used to make code more readable and less clutter in cpp files USING_NS_CC; // the multiple device resolutions than can be enable // In this Game Attack of Ozones , full screen is enabled. the exit icon is plaed in both levels, ther player can leave application safely static cocos2d::Size designResolution = cocos2d::Size(1350, 768);// resolution size for application static cocos2d::Size smallResolution = cocos2d::Size(480, 320); static cocos2d::Size mediumResolution = cocos2d::Size(1024, 768); static cocos2d::Size largeResolution = cocos2d::Size(2048, 1536); //appdelgate constructor AppDelegate::AppDelegate() { } //appdelgate deconstructor AppDelegate::~AppDelegate() { } // boolean appdidfinishlaunching checks screen size and launches My game which is called from main method //Game/app is created with full screen using glview bool AppDelegate::applicationDidFinishLaunching() { /*sdkBox::PlugGPG::init();*/ // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { //#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)||(CC_TARGET_PLATFORM == CC_PLATFORM_MAC)|| ( CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)||(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) // // glview = GLViewImpl::createWithRect("My Game", Rect(0, 0, designResolution.width, designResolution.height)); //#else glview = GLViewImpl::createWithFullScreen("My Game"); //#endif director->setOpenGLView(glview); } // turn on display FPS for testing debugging reasons director->setDisplayStats(false); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); // create a scene. it's an autorelease object auto scene = MainMenu ::createScene(); // run director->runWithScene(scene); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); // if you use SimpleAudioEngine, it must be pause // SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); }
37.385714
179
0.717998
[ "object" ]
bf72c485b19d5d937f2169906c5cd29cfc2e5bce
15,819
hpp
C++
inc/series/types.hpp
davidson16807/libtectonics
aa0ae2b8a4a1d2a9a346bbdeb334be876ad75646
[ "CC-BY-4.0" ]
7
2020-06-09T19:56:55.000Z
2021-02-17T01:53:30.000Z
inc/series/types.hpp
davidson16807/tectonics.cpp
c40278dba14260c598764467c7abf23b190e676b
[ "CC-BY-4.0" ]
null
null
null
inc/series/types.hpp
davidson16807/tectonics.cpp
c40278dba14260c598764467c7abf23b190e676b
[ "CC-BY-4.0" ]
null
null
null
#pragma once // C libraries #include <cmath> /* assert */ #include <assert.h> /* assert */ // std libraries #include <initializer_list> // initializer_list #include <iterator> // std::distance #include <vector> // std::distance namespace series { class AbstractSeries {}; /* This template represents a statically-sized contiguous block of heap memory occupied by primitive data of the same arbitrary type. It is a thin wrapper for a std::vector and shares most of the same method signatures. However, it can also be used with a set of functions and operator overloads that allow it to be handled as if it were a primitive data type. See README.md for more details */ template <typename T> class Series : public AbstractSeries { protected: std::vector<T> values; public: // initializer list constructor template <typename T2> Series(std::initializer_list<T2> list) : values(list.begin(), list.end()) { } // std container style constructor template<typename TIterator> Series(TIterator first, TIterator last) : values(std::distance(first, last)) { std::size_t id = 0; while (first!=last) { this->values[id] = *first; ++first; ++id; } } // copy constructor Series(const Series<T>& a) : values(a.values) {} // convenience constructor for vectors explicit Series(std::vector<T> vector) : values(vector) { } explicit Series(const std::size_t N) : values(N) {} explicit Series(const std::size_t N, const T a) : values(N, a) {} template <typename T2> explicit Series(const Series<T2>& a) : values(a.size()) { for (std::size_t i = 0; i < a.size(); ++i) { values[i] = a[i]; } } // NOTE: all wrapper functions should to be marked inline inline std::size_t size() const { return values.size(); } inline std::size_t max_size() const { return values.size(); } inline std::size_t capacity() const { return values.capacity(); } inline std::size_t empty() const { return values.empty(); } inline typename std::vector<T>::reference front() { return values.front(); } inline typename std::vector<T>::const_reference front() const { return values.front(); } inline typename std::vector<T>::reference back() { return values.back(); } inline typename std::vector<T>::const_reference back() const { return values.back(); } inline typename std::vector<T>::const_iterator begin() const { return values.begin(); } inline typename std::vector<T>::const_iterator end() const { return values.end(); } inline typename std::vector<T>::iterator begin() { return values.begin(); } inline typename std::vector<T>::iterator end() { return values.end(); } using size_type = std::size_t; using value_type = T; inline typename std::vector<T>::const_reference operator[](const unsigned int id ) const { return values.operator[](id); } inline typename std::vector<T>::reference operator[](const unsigned int id ) { return values[id]; // reference return } inline Series<T> operator[](const Series<bool>& mask ) { Series<T> out = Series<T>(mask.size()); get(*this, mask, out); return out; } template<typename Tid> inline Series<T> operator[](const Series<Tid>& ids ) { Series<T> out = Series<T>(ids.size()); get(*this, ids, out); return out; } inline Series<T>& operator=(const Series<T>& other ) { values.resize(other.size()); copy(*this, other); return *this; } inline Series<T>& operator=(const T& other ) { values.resize(other.size()); fill(*this, other); return *this; } inline std::vector<T>& vector() { return values; } /* `store(...)` methods modify the state of the object to store the output of a computation. The computation is defined by applying a function `f` over any combination of `Series` objects and singletons. We then curry the `store()` function to create derived functions outside the class, e.g. add() or dot() Q: Why aren't derived functions (like add() or dot()) implemented as methods? A: There are too many of them. Consider all the functions we'd need for trigonometry, statistics, morphology, vector calculus, etc. We want the API user to selectively include this functionality using `#include` statements, and since we don't want to change the behavior of the class depending on which include statements are present, we decide this functionality is best defined using regular functions outside the class. Q: Why is store() a method and not just a function outside the class? A: The `store()` method by default only allows element-wise comparison between Series and singletons, however we want to extend this behavior when a Series has a particular interpretation (for instance when multiplying a rank 2 tensor by a rank 1 tensor). We would like to allow this extension to be done outside the `series` namespace, since we want to prevent the `series` namespace from growing past the limits of our comprehension. To implement this extended behavior outside the namespace would mean that derived functions could not use this extended functionality (unless the API user added a `using` statement, which is unwise), so we would have to reimplement the same large library of derived functions for each behavioral extension. We instead use derived classes to represent instances of `Series` that carry extended meaning. Q: Why do we implement methods that modify state? Why don't we implement methods that use the object as input? A: We want it to be trivial to create derived functions like add() or dot(). Derived functions are always declared outside the class with a standardized method signature, like `add(const T1& input1, const T2& input2, T3& output)` We cannot guarantee whether `T1` and `T2` are singletons, so relying on a method that treats a `Series` as input would require special consideration for each overload, but we can be certain that `T3` will be a `Series` in all cases where we want to use output references. This excludes functions that "condense" down into singletons, like `sum(Series)`, however we want to pass output by value in those cases anyways, and they're few enough to handle on a case-by-case basis. Creating a `store()` function that modifies state also enables encapsulation of `Series` objects, so that only the object itself can modify its own state, though we admit this concern is secondary. Despite modifying state, the `store()` methods can be considered regular functions (as defined by Stepanov), in the sense that the state of the `Series` object afterwards can be determined strictly from method input. */ // UNARY TRANSFORM template <typename T1, typename F> inline void store(const F f, const Series<T1>& a) { assert(a.size() == values.size()); for (std::size_t i = 0; i < a.size(); ++i) { values[i] = f(a[i]); } } template <typename T1, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T1>::value, int> = 0> inline void store(const F f, const T1 a) { for (std::size_t i = 0; i < a.size(); ++i) { values[i] = f(a); } } // BINARY TRANSFORM template <typename T1, typename T2, typename F> inline void store(const F f, const Series<T1>& a, const Series<T2>& b) { assert(a.size() == values.size()); assert(a.size() == b.size()); for (std::size_t i = 0; i < a.size(); ++i) { values[i] = f(a[i], b[i]); } } template <typename T1, typename T2, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T2>::value, int> = 0> inline void store(const F f, const Series<T1>& a, const T2 b) { assert(a.size() == values.size()); for (std::size_t i = 0; i < a.size(); ++i) { values[i] = f(a[i], b); } } template <typename T1, typename T2, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T1>::value, int> = 0> inline void store(const F f, const T1 a, const Series<T2>& b) { assert(b.size() == values.size()); for (std::size_t i = 0; i < b.size(); ++i) { values[i] = f(a, b[i]); } } // TRINARY TRANSFORM template <typename T1, typename T2, typename T3, typename F> inline void store(const F f, const Series<T1>& a, const Series<T2>& b, const Series<T3>& c) { assert(a.size() == values.size()); assert(b.size() == values.size()); assert(c.size() == values.size()); for (std::size_t i = 0; i < a.size(); ++i) { values[i] = f(a[i], b[i], c[i]); } } template <typename T1, typename T2, typename T3, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T3>::value, int> = 0> inline void store(const F f, const Series<T1>& a, const Series<T2>& b, const T3 c) { assert(a.size() == values.size()); assert(b.size() == values.size()); for (std::size_t i = 0; i < a.size(); ++i) { values[i] = f(a[i], b[i], c); } } template <typename T1, typename T2, typename T3, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T2>::value, int> = 0> inline void store(const F f, const Series<T1>& a, const T2 b, const Series<T3>& c) { assert(a.size() == values.size()); assert(c.size() == values.size()); for (std::size_t i = 0; i < a.size(); ++i) { values[i] = f(a[i], b, c[i]); } } template <typename T1, typename T2, typename T3, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T2>::value && !std::is_base_of<AbstractSeries, T2>::value, int> = 0> inline void store(const F f, const Series<T1>& a, const T2 b, const T3 c) { assert(a.size() == values.size()); for (std::size_t i = 0; i < a.size(); ++i) { values[i] = f(a[i], b, c); } } template <typename T1, typename T2, typename T3, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T1>::value, int> = 0> inline void store(const F f, const T1 a, const Series<T2>& b, const Series<T3>& c) { assert(b.size() == values.size()); assert(c.size() == values.size()); for (std::size_t i = 0; i < b.size(); ++i) { values[i] = f(a, b[i], c[i]); } } template <typename T1, typename T2, typename T3, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T1>::value && !std::is_base_of<AbstractSeries, T3>::value, int> = 0> inline void store(const F f, const T1 a, const Series<T2>& b, const T3 c) { assert(b.size() == values.size()); for (std::size_t i = 0; i < b.size(); ++i) { values[i] = f(a, b[i], c); } } template <typename T1, typename T2, typename T3, typename F, std::enable_if_t<!std::is_base_of<AbstractSeries, T1>::value && !std::is_base_of<AbstractSeries, T2>::value, int> = 0> inline void store(const F f, const T1 a, const T2 b, const Series<T3>& c) { assert(c.size() == values.size()); for (std::size_t i = 0; i < c.size(); ++i) { values[i] = f(a, b, c[i]); } } }; template <typename T, typename Tid> inline T get(const Series<T>& a, const Tid id ) { return a[id]; } template <typename T, typename Tid> inline Series<T> get(const Series<T>& a, const Series<Tid>& ids ) { Series<T> out = Series<T>(ids.size()); get(a, ids, out); return out; } /* template <typename T, typename Tid> inline Series<T> get(const Series<T>& a, const Series<bool>& mask ) { Series<T> out = Series<T>(sum(mask)); get(a, ids, out); return out; } */ template <typename T, typename Tid> void get(const Series<T>& a, const Series<Tid>& ids, Series<T>& out ) { assert(ids.size() == out.size()); for (std::size_t i = 0; i < ids.size(); ++i) { assert(0u <= std::size_t(ids[i])); assert(std::size_t(ids[i]) < a.size()); assert(!std::isinf(ids[i])); assert(!std::isnan(ids[i])); out[i] = a[ids[i]]; } } template <typename T> void get(const Series<T>& a, const Series<bool>& mask, Series<T>& out ) { assert(a.size() == mask.size()); int out_i = 0; for (std::size_t i = 0; i < a.size(); ++i) { if (mask[i]) { out[out_i] = a[i]; out_i++; } } } template <typename T> void fill(Series<T>& out, const T a ) { for (std::size_t i = 0; i < out.size(); ++i) { out[i] = a; } } template <typename T, typename Tid> void fill(Series<T>& out, const Series<Tid>& ids, const T a ) { for (std::size_t i = 0; i < ids.size(); ++i) { assert(0 <= ids[i]); assert(ids[i] < a.size()); assert(!std::isinf(ids[i])); assert(!std::isnan(ids[i])); out[ids[i]] = a; } } template <typename T> void fill(Series<T>& out, const Series<bool>& mask, const T a ) { assert(out.size() == mask.size()); for (std::size_t i = 0; i < out.size(); ++i) { out[i] = mask[i]? a : out[i]; } } template<typename T, typename TIterator> void copy_iterators(Series<T>& out, TIterator first, TIterator last) { unsigned int id = 0; while (first!=last) { out[id] = *first; ++first; ++id; } } template <typename T, typename T2> void copy(Series<T>& out, const Series<T2>& a ) { for (std::size_t i = 0; i < out.size(); ++i) { out[i] = a[i]; } } template <typename T> inline void copy(Series<T>& out, unsigned int id, const Series<T>& a ) { out[id] = a[id]; } template <typename T, typename Tid> void copy(Series<T>& out, const Series<Tid>& ids, const Series<T>& a ) { assert(ids.size() == a.size()); for (std::size_t i = 0; i < ids.size(); ++i) { assert(0 <= ids[i]); assert(ids[i] < a.size()); assert(!std::isinf(ids[i])); assert(!std::isnan(ids[i])); out[ids[i]] = a[ids[i]]; } } template <typename T> void copy(Series<T>& out, const Series<bool>& mask, const Series<T>& a ) { assert(out.size() == mask.size()); assert(out.size() == a.size()); for (std::size_t i = 0; i < out.size(); ++i) { out[i] = mask[i]? a[i] : out[i]; } } template <typename T, typename Tid> inline void set(Series<T>& out, unsigned int id, const T a ) { out[id] = a; } template <typename T, typename Tid> void set(Series<T>& out, const Series<Tid>& ids, const Series<T>& a ) { assert(ids.size() == a.size()); for (std::size_t i = 0; i < ids.size(); ++i) { assert(0 <= ids[i]); assert(ids[i] < a.size()); assert(!std::isinf(ids[i])); assert(!std::isnan(ids[i])); out[ids[i]] = a[i]; } } template<typename T, typename Tid, typename Taggregator> void aggregate_into(const Series<T>& a, const Series<Tid>& group_ids, Taggregator aggregator, Series<T>& group_out) { assert(a.size() == group_ids.size()); for (std::size_t i = 0; i < group_ids.size(); ++i) { assert(0 <= group_ids[i]); assert(std::size_t(group_ids[i]) < group_out.size()); assert(!std::isinf(group_ids[i])); assert(!std::isnan(group_ids[i])); group_out[group_ids[i]] = aggregator(group_out[group_ids[i]], a[i]); } } template<typename T, typename Tid, typename Taggregator> void aggregate_into(const Series<Tid>& group_ids, Taggregator aggregator, Series<T>& group_out) { for (std::size_t i = 0; i < group_ids.size(); ++i) { assert(0u <= std::size_t(group_ids[i]) && std::size_t(group_ids[i]) < group_out.size() && !std::isinf(group_ids[i]) && !std::isnan(group_ids[i])); group_out[group_ids[i]] = aggregator(group_out[group_ids[i]]); } } // NOTE: all wrappers are suggested to be inline because they are thin wrappers of functions typedef Series<bool> bools; typedef Series<int> ints; typedef Series<unsigned int> uints; typedef Series<float> floats; typedef Series<double> doubles; }
31.078585
149
0.628232
[ "object", "vector", "transform" ]
bf7d33f9df9c4ae66a40d250db8e75e5c392e7b9
2,226
cc
C++
components/payments/content/android_app_communication_test_support_stub.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/payments/content/android_app_communication_test_support_stub.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/payments/content/android_app_communication_test_support_stub.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 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 "components/payments/content/android_app_communication_test_support.h" #include <utility> #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" namespace payments { namespace { class AndroidAppCommunicationTestSupportStub : public AndroidAppCommunicationTestSupport { public: AndroidAppCommunicationTestSupportStub() = default; ~AndroidAppCommunicationTestSupportStub() override = default; AndroidAppCommunicationTestSupportStub( const AndroidAppCommunicationTestSupportStub& other) = delete; AndroidAppCommunicationTestSupportStub& operator=( const AndroidAppCommunicationTestSupportStub& other) = delete; bool AreAndroidAppsSupportedOnThisPlatform() const override { return false; } std::unique_ptr<ScopedInitialization> CreateScopedInitialization() override { return std::make_unique<ScopedInitialization>(); } void ExpectNoListOfPaymentAppsQuery() override {} void ExpectNoIsReadyToPayQuery() override {} void ExpectNoPaymentAppInvoke() override {} void ExpectQueryListOfPaymentAppsAndRespond( std::vector<std::unique_ptr<AndroidAppDescription>> apps) override {} void ExpectQueryIsReadyToPayAndRespond(bool is_ready_to_pay) override {} void ExpectInvokePaymentAppAndRespond( bool is_activity_result_ok, const std::string& payment_method_identifier, const std::string& stringified_details) override {} void ExpectInvokeAndAbortPaymentApp() override {} void ExpectNoAbortPaymentApp() override {} content::BrowserContext* context() override { return &context_; } private: content::BrowserTaskEnvironment environment_; content::TestBrowserContext context_; }; } // namespace // Declared in cross-platform file // //components/payments/content/android_app_communication_test_support.h // static std::unique_ptr<AndroidAppCommunicationTestSupport> AndroidAppCommunicationTestSupport::Create() { return std::make_unique<AndroidAppCommunicationTestSupportStub>(); } } // namespace payments
31.8
79
0.796945
[ "vector" ]
bf81b60aadbfe6b38fe0277e7e309130b5b09b0e
1,811
hpp
C++
include/exces/entity_key_set.hpp
matus-chochlik/exces
50b57ce4c9f6c41ab2eacfae054529cbbe6164c0
[ "BSL-1.0" ]
1
2018-03-26T20:51:36.000Z
2018-03-26T20:51:36.000Z
include/exces/entity_key_set.hpp
matus-chochlik/exces
50b57ce4c9f6c41ab2eacfae054529cbbe6164c0
[ "BSL-1.0" ]
null
null
null
include/exces/entity_key_set.hpp
matus-chochlik/exces
50b57ce4c9f6c41ab2eacfae054529cbbe6164c0
[ "BSL-1.0" ]
null
null
null
/** * @file exces/entity_key_set.hpp * @brief Implements entity key set * * Copyright 2012-2014 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef EXCES_ENTITY_KEY_SET_1212101511_HPP #define EXCES_ENTITY_KEY_SET_1212101511_HPP #include <exces/entity.hpp> #include <algorithm> #include <vector> namespace exces { template <typename Group> class manager; // Log(n) insert/removal set of unique entity keys template <typename Group> class entity_key_set { private: typedef typename manager<Group>::entity_key entity_key; std::vector<entity_key> _keys; static bool _ek_less(entity_key a, entity_key b) { return a->first < b->first; } public: entity_key_set(void) = default; entity_key_set(entity_key_set&&) = default; entity_key_set(entity_key key) : _keys(1, key) { } std::size_t size(void) const { return _keys.size(); } bool contains(entity_key key) { auto p = std::lower_bound( _keys.begin(), _keys.end(), key, _ek_less ); return ((p != _keys.end()) && (key == *p)); } void insert(entity_key key) { auto p = std::lower_bound( _keys.begin(), _keys.end(), key, _ek_less ); if((p == _keys.end()) || _ek_less(key, *p)) { _keys.insert(p, key); } } void erase(entity_key key) { auto p = std::lower_bound( _keys.begin(), _keys.end(), key, _ek_less ); if(!(p == _keys.end()) && !(_ek_less(key, *p))) { _keys.erase(p); } } typedef typename std::vector<entity_key>::const_iterator const_iterator; const_iterator begin(void) const { return _keys.begin(); } const_iterator end(void) const { return _keys.end(); } }; } // namespace exces #endif //include guard
17.582524
68
0.6709
[ "vector" ]
bf83241cc95f443e1109f8b1d26ac129c5e4115c
4,611
cpp
C++
src/internal_api_error/internal_api_error.cpp
cjhurani/txssa
473bb4ec650cb7164d80fc531ac38a6c28226dd8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-06-04T01:00:14.000Z
2022-03-25T23:40:57.000Z
src/internal_api_error/internal_api_error.cpp
cjhurani/txssa
473bb4ec650cb7164d80fc531ac38a6c28226dd8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2017-08-28T09:08:53.000Z
2021-06-08T14:17:48.000Z
src/internal_api_error/internal_api_error.cpp
cjhurani/txssa
473bb4ec650cb7164d80fc531ac38a6c28226dd8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* TxSSA: Tech-X Sparse Spectral Approximation Copyright (C) 2012 Tech-X Corporation, 5621 Arapahoe Ave, Boulder CO 80303 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Tech-X Corporation 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. */ /* Authors: 1. Chetan Jhurani (chetan.jhurani@gmail.com, jhurani@txcorp.com) For more information and relevant publications, visit http://www.ices.utexas.edu/~chetan/ 2. Travis M. Austin (austin@txcorp.com) Contact address: Tech-X Corporation 5621 Arapahoe Ave Boulder, CO 80303 http://www.txcorp.com */ // ----------------------------------------------------------------------------- #include "internal_api_error/internal_api_error.h" #include <vector> #include <string> #include <limits> #include <iostream> #include <cstddef> // ----------------------------------------------------------------------------- #ifdef _MSC_VER #pragma warning( disable : 4514 ) // unreferenced inline function has been removed #pragma warning( disable : 4710 ) // function not inlined #endif // ----------------------------------------------------------------------------- // anonymous namespace { std::vector<std::string> errors; } // ----------------------------------------------------------------------------- extern "C" { void internal_api_error_set_last(const char* str) { try { errors.push_back(str); } catch(const std::exception& exc) { std::cerr << "internal_api_error_set_last: Exception. " << exc.what() << std::endl; } catch(...) { std::cerr << "internal_api_error_set_last: Exception. " << "Unknown" << std::endl; } } int internal_api_error_size() { int ret = -1; const std::size_t size = errors.size(); if(size <= std::size_t(std::numeric_limits<int>::max())) ret = int(errors.size()); return ret; } int internal_api_error_string(int i, const char** ptr_to_error_string) { int ret = -1; try { if( 0 <= i && std::size_t(i) < errors.size() && ptr_to_error_string) { *ptr_to_error_string = errors[std::size_t(i)].c_str(); ret = 0; } } catch(const std::exception& exc) { std::cerr << "internal_api_error_string: Exception. " << exc.what() << std::endl; } catch(...) { std::cerr << "internal_api_error_string: Exception. " << "Unknown" << std::endl; } return ret; } int internal_api_error_clear() { int ret = -1; try { std::vector<std::string>().swap(errors); ret = 0; } catch(const std::exception& exc) { std::cerr << "internal_api_error_clear: Exception. " << exc.what() << std::endl; } catch(...) { std::cerr << "internal_api_error_clear: Exception. " << "Unknown" << std::endl; } return ret; } } // extern "C" void internal_api_error_set_last(const std::string& str) { internal_api_error_set_last(str.c_str()); } // -----------------------------------------------------------------------------
25.335165
82
0.592062
[ "vector" ]
bf84d2d60d5ca84f00fac217f22f3847a957acfc
17,623
cpp
C++
AeSys/OdBaseGripManager.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
1
2020-09-07T07:06:19.000Z
2020-09-07T07:06:19.000Z
AeSys/OdBaseGripManager.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
null
null
null
AeSys/OdBaseGripManager.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
2
2019-10-24T00:36:58.000Z
2020-09-30T16:45:56.000Z
// Extracted class from Examples\Editor\ExGripManager.cpp (last compare 20.5) #include "stdafx.h" #include "ExGripManager.h" #include <UInt32Array.h> #include "OdBaseGripManager.h" constexpr unsigned gc_GripManagerPageEachObject = 200; namespace { OdSelectionSetIteratorPtr SearchObjectSelectionSetIterator(OdSelectionSetPtr selectionSet, OdDbStub* id) { auto SelectionSetIterator {selectionSet->newIterator()}; while (!SelectionSetIterator->done()) { if (SelectionSetIterator->id() == id) { return SelectionSetIterator; } SelectionSetIterator->next(); } return OdSelectionSetIteratorPtr(); } } // namespace namespace { struct SortGripsAlongXAxis { bool operator()(const OdExGripDataPtr& grA, const OdExGripDataPtr& grB) { return OdPositive(grA->Point().x, grB->Point().x); } }; } // namespace OdBaseGripManager::OdBaseGripManager() noexcept { m_GripData.clear(); m_HoverGripsData.clear(); m_GripDrags.clear(); } OdBaseGripManager::~OdBaseGripManager() { EndHover(); } bool OdBaseGripManager::OnMouseDown(const int x, const int y, const bool shiftIsDown) { EndHover(); OdExGripDataPtrArray aKeys; LocateGripsAt(x, y, aKeys); if (aKeys.empty()) { return false; } if (shiftIsDown) { // Modify Grip status(). auto NewStatus {OdDbGripOperations::kHotGrip}; for (auto& Key : aKeys) { if (OdDbGripOperations::kHotGrip == Key->Status()) { NewStatus = OdDbGripOperations::kWarmGrip; break; } } for (auto& Key : aKeys) { auto CurrentStatus {NewStatus}; auto Grip {Key}; if (!Grip->GripData().isNull()) { if (Grip->GripData()->triggerGrip()) { CurrentStatus = OdDbGripOperations::kWarmGrip; } else { if (Grip->GripData()->hotGripFunc() != nullptr) { int Flags {OdDbGripOperations::kMultiHotGrip}; if (Grip->IsShared()) { Flags |= OdDbGripOperations::kSharedGrip; } const auto Result {(*Grip->GripData()->hotGripFunc())(Grip->GripData(), Grip->EntityId(), Flags)}; if (Result == eGripOpGripHotToWarm) { CurrentStatus = OdDbGripOperations::kWarmGrip; } } } } Key->SetStatus(CurrentStatus); } } else { // Launch Grip Edit. auto MakeHot {true}; { GripDataMap::const_iterator GripDataIterator {m_GripData.begin()}; while (GripDataIterator != m_GripData.end() && MakeHot) { const auto& Data {GripDataIterator->second.dataArray}; for (const auto& Datum : Data) { if (OdDbGripOperations::kHotGrip == Datum->Status()) { MakeHot = false; break; } } for (unsigned i = 0; i < GripDataIterator->second.gripDataSubEntity.size() && MakeHot; i++) { const auto& Data {GripDataIterator->second.gripDataSubEntity.at(i).subData}; for (const auto& Datum : Data) { if (OdDbGripOperations::kHotGrip == Datum->Status()) { MakeHot = false; break; } } } GripDataIterator++; } } auto GetNew {false}; OdDbObjectId EntityIdToUpdate; if (MakeHot) { for (auto Grip : aKeys) { auto New {OdDbGripOperations::kHotGrip}; if (!Grip->GripData().isNull() && Grip->GripData()->hotGripFunc() != nullptr) { auto Flags {0}; if (Grip->IsShared()) { Flags |= OdDbGripOperations::kSharedGrip; } if (Grip->GripData()->triggerGrip()) { if (!Grip->IsShared()) { const auto Result {(*Grip->GripData()->hotGripFunc())(Grip->GripData(), Grip->EntityId(), Flags)}; if (Result == eOk || Result == eGripOpGripHotToWarm) { New = OdDbGripOperations::kWarmGrip; } else if (Result == eGripOpGetNewGripPoints) { GetNew = true; EntityIdToUpdate = Grip->EntityId(); } } } else { const auto Result {(*Grip->GripData()->hotGripFunc())(Grip->GripData(), Grip->EntityId(), Flags)}; if (!Grip->IsShared()) { if (Result == eGripOpGripHotToWarm) { New = OdDbGripOperations::kWarmGrip; } else if (Result == eGripOpGetNewGripPoints) { GetNew = true; EntityIdToUpdate = Grip->EntityId(); } } } } Grip->SetStatus(New); } } if (GetNew) { UpdateEntityGrips(EntityIdToUpdate); } } return true; } OdResult OdBaseGripManager::StartHover(const int x, const int y, const bool shiftIsDown) { auto Result {eOk}; if (!EndHover()) { Result = eGripOpFailure; m_ClockStartHover = 0; } OdExGripDataPtrArray Keys; LocateGripsAt(x, y, Keys); if (!Keys.empty()) { m_HoverGripsData = Keys; for (unsigned i = 0; i < m_HoverGripsData.size(); i++) { auto Grip {m_HoverGripsData[i]}; if (Grip->Status() == OdDbGripOperations::kWarmGrip) { Grip->SetStatus(OdDbGripOperations::kHoverGrip); if (!Grip->GripData().isNull()) { if (Grip->GripData()->hoverFunc() != nullptr && !shiftIsDown) { if (m_ClockStartHover == 0) { m_ClockStartHover = clock(); } if ((clock() - m_ClockStartHover) * 1000 / CLOCKS_PER_SEC > 300) { // 300 ms delay before hover auto Flags {0}; if (Grip->IsShared()) { Flags = OdDbGripOperations::kSharedGrip; } Result = (*Grip->GripData()->hoverFunc())(Grip->GripData(), Grip->EntityId(), Flags); if (Result == eGripOpGetNewGripPoints) { m_ClockStartHover = 0; Keys[i]->SetStatus(OdDbGripOperations::kHotGrip); m_BasePoint = Keys.first()->Point(); m_LastPoint = m_BasePoint; auto FirstData {Keys.first()->GripData()}; if (FirstData.get() != nullptr && FirstData->alternateBasePoint() != nullptr) { // Use alternative point m_BasePoint = *FirstData->alternateBasePoint(); } } } } } OnModified(Grip); } } } return Result; } bool OdBaseGripManager::EndHover() { if (m_HoverGripsData.empty()) { return false; } for (auto HoverGripData : m_HoverGripsData) { if (HoverGripData->Status() == OdDbGripOperations::kHoverGrip) { HoverGripData->SetStatus(OdDbGripOperations::kWarmGrip); OnModified(HoverGripData); } } m_HoverGripsData.clear(); return true; } void OdBaseGripManager::SelectionSetChanged(OdSelectionSet* selectionSet) { auto RestoreOld {false}; if (selectionSet->numEntities() > static_cast<unsigned>(m_GripObjectLimit)) { Disable(true); } else { if (IsDisabled()) { RestoreOld = true; } Disable(false); } auto Database {OdDbDatabase::cast(selectionSet->baseDatabase()).get()}; { // Old Entities. OdDbStubPtrArray aOld; auto GripDataIterator {m_GripData.begin()}; while (GripDataIterator != m_GripData.end()) { if (IsDisabled()) { aOld.push_back(GripDataIterator->first); } else { if (!selectionSet->isMember(GripDataIterator->first)) { aOld.push_back(GripDataIterator->first); } else { // Remove if subentities changed auto Removed {false}; for (unsigned se = 0; se < GripDataIterator->second.gripDataSubEntity.size(); se++) { if (!selectionSet->isMember(GripDataIterator->second.gripDataSubEntity[se].subentPath)) { aOld.push_back(GripDataIterator->first); Removed = true; break; } } // Remove if new paths added also (workaround. technically new paths must be added on second step) if (!Removed) { auto SelectionSetIterator {SearchObjectSelectionSetIterator(selectionSet, GripDataIterator->first)}; for (unsigned SubEntityIndex = 0; SubEntityIndex < SelectionSetIterator->subentCount(); SubEntityIndex++) { OdDbBaseFullSubentPath FullSubEntityPath; SelectionSetIterator->getSubentity(SubEntityIndex, FullSubEntityPath); auto searchPath {0U}; auto Found {false}; for (; searchPath < GripDataIterator->second.gripDataSubEntity.size(); searchPath++) { if (GripDataIterator->second.gripDataSubEntity.at(searchPath).subentPath == FullSubEntityPath) { Found = true; break; } } if (!Found) { aOld.push_back(GripDataIterator->first); break; } } } } } GripDataIterator++; } const auto Size {aOld.size()}; for (unsigned i = 0; i < Size; i++) { RemoveEntityGrips(aOld[i], true); if (i % gc_GripManagerPageEachObject && Database != nullptr) { Database->pageObjects(); } } } { // New Entities. OdDbStubPtrArray aNew; auto SelectionSetIterator {selectionSet->newIterator()}; while (!SelectionSetIterator->done()) { if (!IsDisabled() && m_GripData.end() == m_GripData.find(SelectionSetIterator->id())) { aNew.push_back(SelectionSetIterator->id()); } SelectionSetIterator->next(); } const auto Size {aNew.size()}; for (unsigned i = 0; i < Size; i++) { UpdateEntityGrips(aNew[i]); if (i % gc_GripManagerPageEachObject && Database != nullptr) { Database->pageObjects(); } } } UpdateInvisibleGrips(); } void OdBaseGripManager::UpdateEntityGrips(OdDbStub* id) { RemoveEntityGrips(id, false); auto SelectionSet {WorkingSelectionSet()}; if (SelectionSet.isNull() || !SelectionSet->isMember(id)) { return; } auto Entity {OpenObject(id)}; if (Entity.isNull()) { return; } OdExGripDataPtrArray aExt; OdDbGripDataPtrArray aPts; auto SelectionSetIterator {SearchObjectSelectionSetIterator(SelectionSet, id)}; if (SelectionSetIterator->subentCount() > 0) { for (unsigned se = 0; se < SelectionSetIterator->subentCount(); se++) { OdDbBaseFullSubentPath subEntPath; SelectionSetIterator->getSubentity(se, subEntPath); aPts.clear(); if (GetGripPointsAtSubentPath(Entity, subEntPath, aPts, ActiveViewUnitSize(), m_GripSize, ActiveViewDirection(), 0) == eOk) { const auto PreviousSize {aExt.size()}; aExt.resize(PreviousSize + aPts.size()); for (unsigned i = 0; i < aPts.size(); i++) { aExt[i + PreviousSize] = OdExGripData::CreateObject(subEntPath, aPts[i], aPts[i]->gripPoint(), this); } } } } else { if (eOk == GetGripPoints(Entity, aPts, ActiveViewUnitSize(), m_GripSize, ActiveViewDirection(), 0)) { aExt.resize(aPts.size()); const auto Size {aExt.size()}; for (unsigned i = 0; i < Size; i++) { aExt[i] = OdExGripData::CreateObject(id, aPts[i], aPts[i]->gripPoint(), this); } } else { OdGePoint3dArray OldPoints; if (eOk == GetGripPoints(Entity, OldPoints)) { aExt.resize(OldPoints.size()); const auto Size {aExt.size()}; for (unsigned i = 0; i < Size; i++) { aExt[i] = OdExGripData::CreateObject(id, nullptr, OldPoints[i], this); } } } } const auto bModel {IsModel(Entity)}; if (!aExt.empty()) { const auto Size {aExt.size()}; OdExGripDataExt dExt; for (unsigned i = 0; i < Size; i++) { OdDbBaseFullSubentPath EntityPath; if (aExt[i]->EntityPath(&EntityPath)) { auto Found {false}; for (auto& GripDatum : dExt.gripDataSubEntity) { if (GripDatum.subentPath == EntityPath) { Found = true; GripDatum.subData.append(aExt[i]); break; } } if (!Found) { OdExGripDataSubent se; se.subentPath = EntityPath; se.subData.append(aExt[i]); dExt.gripDataSubEntity.append(se); } } else { dExt.dataArray.append(aExt[i]); } } m_GripData.insert(std::make_pair(id, dExt)); for (unsigned i = 0; i < Size; i++) { ShowGrip(aExt[i], bModel); } } } void OdBaseGripManager::RemoveEntityGrips(OdDbStub* id, const bool fireDone) { auto GripDataIterator {m_GripData.find(id)}; if (GripDataIterator != m_GripData.end()) { auto Entity {OpenObject(id)}; if (Entity.get() != nullptr) { GripStatus(Entity, OdDb::kGripsToBeDeleted); } const auto Model {IsModel(Entity)}; const auto Size = GripDataIterator->second.dataArray.size(); for (unsigned i = 0; i < Size; i++) { auto GripData {GripDataIterator->second.dataArray[i]}; HideGrip(GripData, Model); if (!GripDataIterator->second.dataArray[i]->GripData().isNull() && GripDataIterator->second.dataArray[i]->GripData()->gripOpStatFunc() != nullptr) { (*GripDataIterator->second.dataArray[i]->GripData()->gripOpStatFunc())(GripDataIterator->second.dataArray[i]->GripData(), id, OdDbGripOperations::kGripEnd); } GripDataIterator->second.dataArray[i] = nullptr; } for (auto& GripDataSubEntity : GripDataIterator->second.gripDataSubEntity) { for (auto& GripData : GripDataSubEntity.subData) { auto GripDataCopy {GripData}; HideGrip(GripDataCopy, Model); GripData = nullptr; } } if (fireDone) { if (Entity.get() != nullptr) { GripStatus(Entity, OdDb::kGripsDone); } } m_GripData.erase(GripDataIterator); } } void OdBaseGripManager::LocateGripsAt(const int x, const int y, OdExGripDataPtrArray& aResult) { aResult.clear(); const auto X {static_cast<double>(x)}; const auto Y {static_cast<double>(y)}; OdGePoint3d FirstPoint; GripDataMap::const_iterator GripDataIterator {m_GripData.begin()}; while (GripDataIterator != m_GripData.end()) { for (unsigned se = 0; se < GripDataIterator->second.gripDataSubEntity.size() + 1; se++) { const auto& aData = se == 0 ? GripDataIterator->second.dataArray : GripDataIterator->second.gripDataSubEntity[se - 1].subData; const auto DataSize {aData.size()}; for (unsigned i = 0; i < DataSize; i++) { const auto& CurrentPoint {aData[i]->Point()}; if (aResult.empty()) { // First grip is obtained by comparing grip point device position with cursor position. auto ptDC {CurrentPoint}; ptDC.transformBy(ActiveGsView()->worldToDeviceMatrix()); const auto DeltaX {fabs(X - ptDC.x)}; const auto DeltaY {fabs(Y - ptDC.y)}; const auto Ok {DeltaX <= m_GripSize && DeltaY <= m_GripSize}; if (Ok) { FirstPoint = CurrentPoint; aResult.push_back(aData[i]); } } else { // Other grips are obtained by comparing world coordinates. The approach here is quite raw. if (CurrentPoint.isEqualTo(FirstPoint, 1E-4)) { aResult.push_back(aData[i]); } } } } GripDataIterator++; } } void OdBaseGripManager::LocateGripsByStatus(const OdDbGripOperations::DrawType eStatus, OdExGripDataPtrArray& aResult) { aResult.clear(); GripDataMap::const_iterator GripDataIterator {m_GripData.begin()}; while (GripDataIterator != m_GripData.end()) { for (unsigned se = 0; se < GripDataIterator->second.gripDataSubEntity.size() + 1; se++) { const auto& aData {se == 0 ? GripDataIterator->second.dataArray : GripDataIterator->second.gripDataSubEntity[se - 1].subData}; const auto Size {aData.size()}; for (unsigned i = 0; i < Size; i++) { if (eStatus == aData[i]->Status()) { aResult.push_back(aData[i]); } } } GripDataIterator++; } } void OdBaseGripManager::UpdateInvisibleGrips() { OdExGripDataPtrArray Overall; GripDataMap::const_iterator GripDataIterator {m_GripData.begin()}; while (GripDataIterator != m_GripData.end()) { Overall.insert(Overall.end(), GripDataIterator->second.dataArray.begin(), GripDataIterator->second.dataArray.end()); for (const auto& GripDatum : GripDataIterator->second.gripDataSubEntity) { Overall.insert(Overall.end(), GripDatum.subData.begin(), GripDatum.subData.end()); } GripDataIterator++; } for (auto& Grip : Overall) { Grip->SetInvisible(false); Grip->SetShared(false); } std::sort(Overall.begin(), Overall.end(), SortGripsAlongXAxis()); const auto Size {Overall.size()}; for (unsigned i = 0; i < Size; i++) { if (Overall[i]->IsShared()) { continue; } OdUInt32Array aEq; aEq.push_back(i); const auto ptIni = Overall[i]->Point(); auto iNext = i + 1; while (iNext < Size) { const auto CurrentPoint {Overall[iNext]->Point()}; if (OdEqual(ptIni.x, CurrentPoint.x, 1E-6)) { if (ptIni.isEqualTo(CurrentPoint, 1E-6)) { aEq.push_back(iNext); } iNext++; } else { break; } } if (aEq.size() >= 2) { auto Visible {0U}; const auto jSize = aEq.size(); for (unsigned j = 0; j < jSize; j++) { auto Grip {Overall[aEq[j]]}; auto Ok {true}; if (!Grip->GripData().isNull()) { if (Grip->GripData()->skipWhenShared()) { Ok = false; } } else { Ok = false; } if (Ok) { Visible = j; break; } } for (unsigned j = 0; j < jSize; j++) { auto Grip {Overall[aEq[j]]}; Grip->SetShared(true); Grip->SetInvisible(j != Visible); } } } } void OdBaseGripManager::setValue(const OdGePoint3d& value) { const auto NewPoint {EyeToUcsPlane(value, m_BasePoint)}; const auto Size {m_GripDrags.size()}; for (unsigned GripDragIndex = 0; GripDragIndex < Size; GripDragIndex++) { m_GripDrags[GripDragIndex]->CloneEntity(NewPoint); } m_LastPoint = NewPoint; } double OdBaseGripManager::ActiveViewUnitSize() const { const auto ActiveView {ActiveGsView()}; // <tas="Duplicates function of inaccessible 'OdGiViewport::getNumPixelsInUnitSquare' here."/> OdGePoint2d LowerLeft; OdGePoint2d UpperRight; ActiveView->getViewport(LowerLeft, UpperRight); OdGsDCRect ScreenRectangle; ActiveView->getViewport(ScreenRectangle); OdGePoint2d PixelDensity; PixelDensity.x = fabs(double(ScreenRectangle.m_max.x - ScreenRectangle.m_min.x) / ActiveView->fieldWidth() * (UpperRight.x - LowerLeft.x)); PixelDensity.y = fabs(double(ScreenRectangle.m_max.y - ScreenRectangle.m_min.y) / ActiveView->fieldHeight() * (UpperRight.y - LowerLeft.y)); OdGeVector3d GripEdgeSize(m_GripSize / PixelDensity.x, 0, 0); GripEdgeSize.transformBy(ActiveView->viewingMatrix()); return GripEdgeSize.length() / m_GripSize; } OdGeVector3d OdBaseGripManager::ActiveViewDirection() const { const auto View {ActiveGsView()}; return (View->position() - View->target()).normal(); } void OdBaseGripManager::Disable(const bool disable) { m_Disabled = disable; }
33.001873
160
0.663792
[ "model" ]
bf8776636944aec364c0808401718320c4d7d109
9,914
cpp
C++
octree_test/main.cpp
TheLastingCurator/TrueVoxel
660db1aba4d736e451d9331469ba7160296576ac
[ "MIT" ]
null
null
null
octree_test/main.cpp
TheLastingCurator/TrueVoxel
660db1aba4d736e451d9331469ba7160296576ac
[ "MIT" ]
null
null
null
octree_test/main.cpp
TheLastingCurator/TrueVoxel
660db1aba4d736e451d9331469ba7160296576ac
[ "MIT" ]
null
null
null
// Copyright (c) <year> Your name #include "engine/easy.h" #include "engine/bitstream.h" #include <nmmintrin.h> using namespace arctic; // NOLINT using namespace arctic::easy; // NOLINT Si32 g_ser = 0; double g_prev_time; double g_cur_time; Font g_font; double g_displayed_dt = 1.0/60.0; double g_time_to_displayed_dt_change = 0.0; // Tight octree bitstream format: // Nodes start from root and then in depth-first order // arrays of child bit-records for each node follow: // 0 - void leaf // 1 - non-void entry // 0 - mixed node // 1 - solid leaf // node_0: flags for child nodes [01001011] // // child offset: node_1_000 // node_1_001 // node_1_011 // node_1_110 struct OctreeNode { Ui32 child_offset = 0; // 0 == leaf node, other offet indicates first non-empty child position Ui8 child_mask = 0; // 1 for n-th bit indicates that the n-th child is present Ui8 r = 0; Ui8 g = 0; Ui8 b = 0; Ui8 n_x = 0; Ui8 n_y = 0; Ui8 flags = 0; // bit 0 LOD_X: 0 for transparent LOD_X, 1 for opaque // bit 1 LOD_Y: 0 for transparent LOD_Y, 1 for opaque // bit 2 LOD_Z: 0 for transparent LOD_Z, 1 for opaque Ui8 reserved = 0; }; struct FatOctreeNode { enum Solidity { kUnknown = 0, kVoid = 1, kMixed = 2, kSolid = 3 }; Ui32 child_offset; float r; float g; float b; float a; // 0 == fully transparent, 1 == fully opaque FatOctreeNode* children[8]; bool is_serialized; Ui8 child_mask; // 1 for n-th bit indicates that the n-th child is present Solidity solidity; void FreeChildren(); void AddChild(Ui32 i, FatOctreeNode *c); void ProcessChildren(); }; union FatOctreeNodePoolItem { FatOctreeNodePoolItem *next; FatOctreeNode data; }; std::vector<FatOctreeNodePoolItem> g_fat_node_pool_data; FatOctreeNodePoolItem *g_fat_node_pool_head = nullptr; void InitFatNodePool(Ui32 size) { g_fat_node_pool_data.resize(size); g_fat_node_pool_head = &g_fat_node_pool_data[0]; for (size_t i = 1; i < size; ++i) { g_fat_node_pool_data[i-1].next = &g_fat_node_pool_data[i]; } g_fat_node_pool_data[size - 1].next = nullptr; } FatOctreeNode* AllocateFatNode() { Check(g_fat_node_pool_head, "Fat node pool exhausted!"); FatOctreeNodePoolItem* item = g_fat_node_pool_head; g_fat_node_pool_head = g_fat_node_pool_head->next; item->next = nullptr; return &(item->data); } void FreeFatNode(FatOctreeNode *node) { FatOctreeNodePoolItem *p = reinterpret_cast<FatOctreeNodePoolItem*>(node); Check(p != nullptr, "cast error"); p->next = g_fat_node_pool_head; g_fat_node_pool_head = p; } void FatOctreeNodeToOctreeNode(FatOctreeNode &n, OctreeNode *s) { s->child_offset = n.child_offset; s->child_mask = n.child_mask; s->r = n.r * 255.f; s->g = n.g * 255.f; s->b = n.b * 255.f; s->flags = 7; } void OutputOctreeNode(FatOctreeNode *n, std::deque<OctreeNode> *out_octree) { for (Ui32 i = 0; i < 8; ++i) { FatOctreeNode *c = n->children[i]; if (c && c->solidity != FatOctreeNode::kVoid) { n->child_mask |= (1 << i); if (n->child_offset == 0) { n->child_offset = (Ui32)out_octree->size(); } out_octree->emplace_back(); FatOctreeNodeToOctreeNode(*c, &out_octree->back()); } } } FatOctreeNode* FillNode(const Vec3Si32 pos, const Ui32 side, const Ui32 raw_side, const std::vector<Ui8> &raw, std::deque<OctreeNode> *out_octree) { //*(Log()) << "FillNode (" << pos.x << ", " << pos.y << ", " << pos.z << ") " << side; FatOctreeNode *n = AllocateFatNode(); memset(n, 0, sizeof(FatOctreeNode)); if (side == 1) { const Ui8 a = raw[pos.x + pos.y * raw_side + pos.z * raw_side * raw_side]; n->a = a / 255.f; n->solidity = a ? FatOctreeNode::kSolid : FatOctreeNode::kVoid; return n; } const Ui32 child_side = (side >> 1); for (Ui32 i = 0; i < 8; ++i) { const Ui32 xo = i & 1; const Ui32 yo = (i >> 1) & 1; const Ui32 zo = (i >> 2) & 1; const Vec3Si32 child_pos(pos.x + xo * child_side, pos.y + yo * child_side, pos.z + zo * child_side); FatOctreeNode *c = FillNode(child_pos, child_side, raw_side, raw, out_octree); n->AddChild(i, c); } n->ProcessChildren(); if (n->solidity == FatOctreeNode::kMixed) { OutputOctreeNode(n, out_octree); } n->FreeChildren(); return n; } void FatOctreeNode::FreeChildren() { for (Ui32 i = 0; i < 8; ++i) { if (children[i]) { FreeFatNode(children[i]); children[i] = nullptr; } } } void FatOctreeNode::AddChild(Ui32 i, FatOctreeNode *c) { children[i] = c; r += c->r * c->a; g += c->g * c->a; b += c->b * c->a; a += c->a; } void FatOctreeNode::ProcessChildren() { if (a > 0.f) { r /= a; g /= a; b /= a; } a /= 8.f; if (a == 1.f) { solidity = FatOctreeNode::kSolid; for (Ui32 i = 0; i < 7; ++i) { FatOctreeNode *c1 = children[i]; FatOctreeNode *c2 = children[i + 1]; if (!c1 || !c2 || c1->r != c2->r || c1->g != c2->g || c1->b != c2->b || c1->a != c2->a || c1->solidity != FatOctreeNode::kSolid || c2->solidity != FatOctreeNode::kSolid) { solidity = FatOctreeNode::kMixed; break; } } } else if (a == 0.f) { solidity = FatOctreeNode::kVoid; } else { solidity = FatOctreeNode::kMixed; } } void RawToOctree(const std::vector<Ui8> &raw, std::vector<OctreeNode> *out_octree) { std::deque<OctreeNode> octree; octree.emplace_back(); FatOctreeNode* c = FillNode(Vec3Si32(0, 0, 0), 512, 512, raw, &octree); FatOctreeNodeToOctreeNode(*c, &octree.front()); out_octree->resize(octree.size()); std::copy(octree.begin(), octree.end(), out_octree->begin()); } // each node record contains a solidity flag // 0 - mixed node // 1 - solid leaf // mixed nodes contain 8 bits of the child_mask // 0 - void leaf // 1 - non-void entry // then child node records follow for non-void entries void OctreeToTightOctree(std::vector<OctreeNode> &octree, Si32 node_offset, BitStream *out_tight_octree) { OctreeNode &cur = octree[node_offset]; out_tight_octree->PushBit(cur.child_offset ? 0 : 1); if (cur.child_offset) { for (Si32 i = 0; i < 8; ++i) { out_tight_octree->PushBit((cur.child_mask >> i) & 1); } for (Ui32 i = 0; i < 8; ++i) { if ((cur.child_mask >> i) & 1) { Ui32 idx = __builtin_popcount(Ui32(cur.child_mask) & (Ui32(0xff) >> (8 - i))); OctreeToTightOctree(octree, cur.child_offset + idx, out_tight_octree); } } } } FatOctreeNode* FillNodeFromTight(BitStream &tight_octree, std::deque<OctreeNode> *out_octree) { FatOctreeNode *n = AllocateFatNode(); memset(n, 0, sizeof(FatOctreeNode)); Ui8 is_leaf = (tight_octree.ReadBit() & 1); if (is_leaf) { n->a = 1.f; n->solidity = FatOctreeNode::kSolid; return n; } Ui8 child_mask = 0; for (Ui32 i = 0; i < 8; ++i) { child_mask |= ((tight_octree.ReadBit() & 1) << i); } Check(child_mask, "Unexpected empty child mask"); for (Ui32 i = 0; i < 8; ++i) { FatOctreeNode *c = nullptr; if ((child_mask >> i) & 1) { c = FillNodeFromTight(tight_octree, out_octree); } else { c = AllocateFatNode(); memset(c, 0, sizeof(FatOctreeNode)); c->a = 0.f; c->solidity = FatOctreeNode::kVoid; } n->AddChild(i, c); } n->ProcessChildren(); if (n->solidity == FatOctreeNode::kMixed) { OutputOctreeNode(n, out_octree); } n->FreeChildren(); return n; } void TightOctreeToOctree(BitStream &tight_octree, std::vector<OctreeNode> *out_octree) { std::deque<OctreeNode> octree; octree.emplace_back(); FatOctreeNode* c = FillNodeFromTight(tight_octree, &octree); FatOctreeNodeToOctreeNode(*c, &octree.front()); out_octree->resize(octree.size()); std::copy(octree.begin(), octree.end(), out_octree->begin()); } void EasyMain() { InitFatNodePool(1024); std::vector<Ui8> raw = ReadFile("data/bunny_512.raw"); Check(raw.size() == 512 * 512 * 512, "Unexpected raw size"); std::vector<OctreeNode> octree; RawToOctree(raw, &octree); WriteFile("data/bunny_512.svo", reinterpret_cast<const Ui8*>(octree.data()), sizeof(OctreeNode)*octree.size()); BitStream tight_octree; OctreeToTightOctree(octree, 0, &tight_octree); std::vector<Ui8> tight_vec(tight_octree.GetData().size()); std::copy(tight_octree.GetData().begin(), tight_octree.GetData().end(), tight_vec.begin()); WriteFile("data/bunny_512.tig", reinterpret_cast<const Ui8*>(tight_vec.data()), tight_vec.size()); std::vector<Ui8> tight_vec_2 = ReadFile("data/bunny_512.tig"); BitStream tight_octree_2(tight_vec_2); std::vector<OctreeNode> octree_2; TightOctreeToOctree(tight_octree_2, &octree_2); WriteFile("data/bunny_512_2.svo", reinterpret_cast<const Ui8*>(octree_2.data()), sizeof(OctreeNode)*octree_2.size()); ResizeScreen(1920, 1080); g_font.Load("data/arctic_one_bmf.fnt"); g_cur_time = Time(); while (!IsKeyDownward(kKeyEscape)) { g_prev_time = g_cur_time; g_cur_time = Time(); double dt = g_cur_time - g_prev_time; g_time_to_displayed_dt_change -= dt; if (g_time_to_displayed_dt_change <= 0.0) { g_time_to_displayed_dt_change = 0.2; g_displayed_dt = dt; } Clear(); char message[4096]; snprintf(message, 4096, "FPS: %2.1f (%2.2f msPF) octree: %zu nodes (%zu) %u", 1.f / std::max(1e-9, g_displayed_dt), g_displayed_dt*1000.f, octree.size(), octree_2.size(), g_ser ); g_font.Draw(message, 0, ScreenSize().y, kTextOriginTop); ShowFrame(); } }
30.693498
120
0.617712
[ "vector", "solid" ]
bf8d9d2b8a687c061ad3e49062ee76348c9a4fa8
25,296
cc
C++
src/libxtp/aomatrices/aokinetic.cc
mbarbry/xtp
e79828209d11ec25bf1750ab75499ecf50f584ef
[ "Apache-2.0" ]
null
null
null
src/libxtp/aomatrices/aokinetic.cc
mbarbry/xtp
e79828209d11ec25bf1750ab75499ecf50f584ef
[ "Apache-2.0" ]
null
null
null
src/libxtp/aomatrices/aokinetic.cc
mbarbry/xtp
e79828209d11ec25bf1750ab75499ecf50f584ef
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2018 The VOTCA Development Team * (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License") * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <votca/xtp/aomatrix.h> #include <votca/xtp/aobasis.h> #include <vector> namespace votca { namespace xtp { void AOKinetic::FillBlock( Eigen::Block<Eigen::MatrixXd> & matrix,const AOShell* shell_row,const AOShell* shell_col) { // shell info, only lmax tells how far to go int lmax_row = shell_row->getLmax(); int lmax_col = shell_col->getLmax(); if (lmax_col >4 || lmax_row >4){ std::cerr << "Orbitals higher than g are not yet implemented. This should not have happened!" << std::flush; exit(1); } // set size of internal block for recursion int nrows = this->getBlockSize( lmax_row ); int ncols = this->getBlockSize( lmax_col ); // get shell positions const tools::vec& pos_row = shell_row->getPos(); const tools::vec& _pos_col = shell_col->getPos(); const tools::vec diff = pos_row - _pos_col; double distsq = (diff*diff); int n_orbitals[] = {1, 4, 10, 20, 35, 56, 84}; int nx[] = { 0, 1, 0, 0, 2, 1, 1, 0, 0, 0, 3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0 }; int ny[] = { 0, 0, 1, 0, 0, 1, 0, 2, 1, 0, 0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0 }; int nz[] = { 0, 0, 0, 1, 0, 0, 1, 0, 1, 2, 0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4 }; int i_less_x[] = { 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 0, 0, 0, 0 }; int i_less_y[] = { 0, 0, 0, 0, 0, 1, 0, 2, 3, 0, 0, 4, 0, 5, 6, 0, 7, 8, 9, 0, 0, 10, 0, 11, 12, 0, 13, 14, 15, 0, 16, 17, 18, 19, 0 }; int i_less_z[] = { 0, 0, 0, 0, 0, 0, 1, 0, 2, 3, 0, 0, 4, 0, 5, 6, 0, 7, 8, 9, 0, 0, 10, 0, 11, 12, 0, 13, 14, 15, 0, 16, 17, 18, 19 }; // cout << "row shell is " << shell_row->getSize() << " -fold contracted!" << endl; //cout << "col shell is " << shell_col->getSize() << " -fold contracted!" << endl; // iterate over Gaussians in this shell_row for ( AOShell::GaussianIterator itr = shell_row->begin(); itr != shell_row->end(); ++itr){ // iterate over Gaussians in this shell_col const double decay_row = itr->getDecay(); for ( AOShell::GaussianIterator itc = shell_col->begin(); itc != shell_col->end(); ++itc){ // get decay constants const double decay_col = itc->getDecay(); // some helpers const double fak = 0.5/(decay_row + decay_col); const double rzeta = 2.0 * fak; const double xi=rzeta* decay_row * decay_col; // check if distance between postions is big, then skip step double exparg = xi *distsq; if ( exparg > 30.0 ) { continue; } const double PmA0 = rzeta*( decay_row * pos_row.getX() + decay_col * _pos_col.getX() ) - pos_row.getX(); const double PmA1 = rzeta*( decay_row * pos_row.getY() + decay_col * _pos_col.getY() ) - pos_row.getY(); const double PmA2 = rzeta*( decay_row * pos_row.getZ() + decay_col * _pos_col.getZ() ) - pos_row.getZ(); const double PmB0 = rzeta*( decay_row * pos_row.getX() + decay_col * _pos_col.getX() ) - _pos_col.getX(); const double PmB1 = rzeta*( decay_row * pos_row.getY() + decay_col * _pos_col.getY() ) - _pos_col.getY(); const double PmB2 = rzeta*( decay_row * pos_row.getZ() + decay_col * _pos_col.getZ() ) - _pos_col.getZ(); const double xi2 = 2.*xi; ////////////// const double fak_a = rzeta * decay_col; ///////////// const double fak_b = rzeta * decay_row; //////////// // matrix for kinetic energies Eigen::MatrixXd kin = Eigen::MatrixXd::Zero(nrows,ncols); //matrix for unnormalized overlap integrals Eigen::MatrixXd ol = Eigen::MatrixXd::Zero(nrows,ncols); // s-s overlap integral ol(Cart::s,Cart::s) = pow(rzeta,1.5)*pow(4.0*decay_row*decay_col,0.75) * exp(-exparg); // s-s- kinetic energy integral kin(Cart::s,Cart::s)= ol(Cart::s,Cart::s)*xi*(3-2*xi*distsq); //Integrals p - s if (lmax_row > 0) { ol(Cart::x,0) = PmA0*ol(0,0); ol(Cart::y,0) = PmA1*ol(0,0); ol(Cart::z,0) = PmA2*ol(0,0); } //------------------------------------------------------ //Integrals d - s if (lmax_row > 1) { double term = fak*ol(0,0); ol(Cart::xx,0) = PmA0*ol(Cart::x,0) + term; ol(Cart::xy,0) = PmA0*ol(Cart::y,0); ol(Cart::xz,0) = PmA0*ol(Cart::z,0); ol(Cart::yy,0) = PmA1*ol(Cart::y,0) + term; ol(Cart::yz,0) = PmA1*ol(Cart::z,0); ol(Cart::zz,0) = PmA2*ol(Cart::z,0) + term; } //------------------------------------------------------ //Integrals f - s if (lmax_row > 2) { ol(Cart::xxx,0) = PmA0*ol(Cart::xx,0) + 2*fak*ol(Cart::x,0); ol(Cart::xxy,0) = PmA1*ol(Cart::xx,0); ol(Cart::xxz,0) = PmA2*ol(Cart::xx,0); ol(Cart::xyy,0) = PmA0*ol(Cart::yy,0); ol(Cart::xyz,0) = PmA0*ol(Cart::yz,0); ol(Cart::xzz,0) = PmA0*ol(Cart::zz,0); ol(Cart::yyy,0) = PmA1*ol(Cart::yy,0) + 2*fak*ol(Cart::y,0); ol(Cart::yyz,0) = PmA2*ol(Cart::yy,0); ol(Cart::yzz,0) = PmA1*ol(Cart::zz,0); ol(Cart::zzz,0) = PmA2*ol(Cart::zz,0) + 2*fak*ol(Cart::z,0); } //------------------------------------------------------ //Integrals g - s if (lmax_row > 3) { double term_xx = fak*ol(Cart::xx,0); double term_yy = fak*ol(Cart::yy,0); double term_zz = fak*ol(Cart::zz,0); ol(Cart::xxxx,0) = PmA0*ol(Cart::xxx,0) + 3*term_xx; ol(Cart::xxxy,0) = PmA1*ol(Cart::xxx,0); ol(Cart::xxxz,0) = PmA2*ol(Cart::xxx,0); ol(Cart::xxyy,0) = PmA0*ol(Cart::xyy,0) + term_yy; ol(Cart::xxyz,0) = PmA1*ol(Cart::xxz,0); ol(Cart::xxzz,0) = PmA0*ol(Cart::xzz,0) + term_zz; ol(Cart::xyyy,0) = PmA0*ol(Cart::yyy,0); ol(Cart::xyyz,0) = PmA0*ol(Cart::yyz,0); ol(Cart::xyzz,0) = PmA0*ol(Cart::yzz,0); ol(Cart::xzzz,0) = PmA0*ol(Cart::zzz,0); ol(Cart::yyyy,0) = PmA1*ol(Cart::yyy,0) + 3*term_yy; ol(Cart::yyyz,0) = PmA2*ol(Cart::yyy,0); ol(Cart::yyzz,0) = PmA1*ol(Cart::yzz,0) + term_zz; ol(Cart::yzzz,0) = PmA1*ol(Cart::zzz,0); ol(Cart::zzzz,0) = PmA2*ol(Cart::zzz,0) + 3*term_zz; } //------------------------------------------------------ if (lmax_col > 0) { //Integrals s - p ol(0,Cart::x) = PmB0*ol(0,0); ol(0,Cart::y) = PmB1*ol(0,0); ol(0,Cart::z) = PmB2*ol(0,0); //------------------------------------------------------ //Integrals p - p d - p f - p g - p for (int i = 1; i < n_orbitals[lmax_row]; i++) { ol(i,Cart::x) = PmB0*ol(i,0) + nx[i]*fak*ol(i_less_x[i],0); ol(i,Cart::y) = PmB1*ol(i,0) + ny[i]*fak*ol(i_less_y[i],0); ol(i,Cart::z) = PmB2*ol(i,0) + nz[i]*fak*ol(i_less_z[i],0); } //------------------------------------------------------ } // end if (lmax_col > 0) if (lmax_col > 1) { //Integrals s - d double term = fak*ol(0,0); ol(0,Cart::xx) = PmB0*ol(0,Cart::x) + term; ol(0,Cart::xy) = PmB0*ol(0,Cart::y); ol(0,Cart::xz) = PmB0*ol(0,Cart::z); ol(0,Cart::yy) = PmB1*ol(0,Cart::y) + term; ol(0,Cart::yz) = PmB1*ol(0,Cart::z); ol(0,Cart::zz) = PmB2*ol(0,Cart::z) + term; //------------------------------------------------------ //Integrals p - d d - d f - d g - d for (int i = 1; i < n_orbitals[lmax_row]; i++) { double term = fak*ol(i,0); ol(i,Cart::xx) = PmB0*ol(i,Cart::x) + nx[i]*fak*ol(i_less_x[i],Cart::x) + term; ol(i,Cart::xy) = PmB0*ol(i,Cart::y) + nx[i]*fak*ol(i_less_x[i],Cart::y); ol(i,Cart::xz) = PmB0*ol(i,Cart::z) + nx[i]*fak*ol(i_less_x[i],Cart::z); ol(i,Cart::yy) = PmB1*ol(i,Cart::y) + ny[i]*fak*ol(i_less_y[i],Cart::y) + term; ol(i,Cart::yz) = PmB1*ol(i,Cart::z) + ny[i]*fak*ol(i_less_y[i],Cart::z); ol(i,Cart::zz) = PmB2*ol(i,Cart::z) + nz[i]*fak*ol(i_less_z[i],Cart::z) + term; } //------------------------------------------------------ } // end if (lmax_col > 1) if (lmax_col > 2) { //Integrals s - f ol(0,Cart::xxx) = PmB0*ol(0,Cart::xx) + 2*fak*ol(0,Cart::x); ol(0,Cart::xxy) = PmB1*ol(0,Cart::xx); ol(0,Cart::xxz) = PmB2*ol(0,Cart::xx); ol(0,Cart::xyy) = PmB0*ol(0,Cart::yy); ol(0,Cart::xyz) = PmB0*ol(0,Cart::yz); ol(0,Cart::xzz) = PmB0*ol(0,Cart::zz); ol(0,Cart::yyy) = PmB1*ol(0,Cart::yy) + 2*fak*ol(0,Cart::y); ol(0,Cart::yyz) = PmB2*ol(0,Cart::yy); ol(0,Cart::yzz) = PmB1*ol(0,Cart::zz); ol(0,Cart::zzz) = PmB2*ol(0,Cart::zz) + 2*fak*ol(0,Cart::z); //------------------------------------------------------ //Integrals p - f d - f f - f g - f for (int i = 1; i < n_orbitals[lmax_row]; i++) { double term_x = 2*fak*ol(i,Cart::x); double term_y = 2*fak*ol(i,Cart::y); double term_z = 2*fak*ol(i,Cart::z); ol(i,Cart::xxx) = PmB0*ol(i,Cart::xx) + nx[i]*fak*ol(i_less_x[i],Cart::xx) + term_x; ol(i,Cart::xxy) = PmB1*ol(i,Cart::xx) + ny[i]*fak*ol(i_less_y[i],Cart::xx); ol(i,Cart::xxz) = PmB2*ol(i,Cart::xx) + nz[i]*fak*ol(i_less_z[i],Cart::xx); ol(i,Cart::xyy) = PmB0*ol(i,Cart::yy) + nx[i]*fak*ol(i_less_x[i],Cart::yy); ol(i,Cart::xyz) = PmB0*ol(i,Cart::yz) + nx[i]*fak*ol(i_less_x[i],Cart::yz); ol(i,Cart::xzz) = PmB0*ol(i,Cart::zz) + nx[i]*fak*ol(i_less_x[i],Cart::zz); ol(i,Cart::yyy) = PmB1*ol(i,Cart::yy) + ny[i]*fak*ol(i_less_y[i],Cart::yy) + term_y; ol(i,Cart::yyz) = PmB2*ol(i,Cart::yy) + nz[i]*fak*ol(i_less_z[i],Cart::yy); ol(i,Cart::yzz) = PmB1*ol(i,Cart::zz) + ny[i]*fak*ol(i_less_y[i],Cart::zz); ol(i,Cart::zzz) = PmB2*ol(i,Cart::zz) + nz[i]*fak*ol(i_less_z[i],Cart::zz) + term_z; } //------------------------------------------------------ } // end if (lmax_col > 2) if (lmax_col > 3) { //Integrals s - g double term_xx = fak*ol(0,Cart::xx); double term_yy = fak*ol(0,Cart::yy); double term_zz = fak*ol(0,Cart::zz); ol(0,Cart::xxxx) = PmB0*ol(0,Cart::xxx) + 3*term_xx; ol(0,Cart::xxxy) = PmB1*ol(0,Cart::xxx); ol(0,Cart::xxxz) = PmB2*ol(0,Cart::xxx); ol(0,Cart::xxyy) = PmB0*ol(0,Cart::xyy) + term_yy; ol(0,Cart::xxyz) = PmB1*ol(0,Cart::xxz); ol(0,Cart::xxzz) = PmB0*ol(0,Cart::xzz) + term_zz; ol(0,Cart::xyyy) = PmB0*ol(0,Cart::yyy); ol(0,Cart::xyyz) = PmB0*ol(0,Cart::yyz); ol(0,Cart::xyzz) = PmB0*ol(0,Cart::yzz); ol(0,Cart::xzzz) = PmB0*ol(0,Cart::zzz); ol(0,Cart::yyyy) = PmB1*ol(0,Cart::yyy) + 3*term_yy; ol(0,Cart::yyyz) = PmB2*ol(0,Cart::yyy); ol(0,Cart::yyzz) = PmB1*ol(0,Cart::yzz) + term_zz; ol(0,Cart::yzzz) = PmB1*ol(0,Cart::zzz); ol(0,Cart::zzzz) = PmB2*ol(0,Cart::zzz) + 3*term_zz; //------------------------------------------------------ //Integrals p - g d - g f - g g - g for (int i = 1; i < n_orbitals[lmax_row]; i++) { double term_xx = fak*ol(i,Cart::xx); double term_yy = fak*ol(i,Cart::yy); double term_zz = fak*ol(i,Cart::zz); ol(i,Cart::xxxx) = PmB0*ol(i,Cart::xxx) + nx[i]*fak*ol(i_less_x[i],Cart::xxx) + 3*term_xx; ol(i,Cart::xxxy) = PmB1*ol(i,Cart::xxx) + ny[i]*fak*ol(i_less_y[i],Cart::xxx); ol(i,Cart::xxxz) = PmB2*ol(i,Cart::xxx) + nz[i]*fak*ol(i_less_z[i],Cart::xxx); ol(i,Cart::xxyy) = PmB0*ol(i,Cart::xyy) + nx[i]*fak*ol(i_less_x[i],Cart::xyy) + term_yy; ol(i,Cart::xxyz) = PmB1*ol(i,Cart::xxz) + ny[i]*fak*ol(i_less_y[i],Cart::xxz); ol(i,Cart::xxzz) = PmB0*ol(i,Cart::xzz) + nx[i]*fak*ol(i_less_x[i],Cart::xzz) + term_zz; ol(i,Cart::xyyy) = PmB0*ol(i,Cart::yyy) + nx[i]*fak*ol(i_less_x[i],Cart::yyy); ol(i,Cart::xyyz) = PmB0*ol(i,Cart::yyz) + nx[i]*fak*ol(i_less_x[i],Cart::yyz); ol(i,Cart::xyzz) = PmB0*ol(i,Cart::yzz) + nx[i]*fak*ol(i_less_x[i],Cart::yzz); ol(i,Cart::xzzz) = PmB0*ol(i,Cart::zzz) + nx[i]*fak*ol(i_less_x[i],Cart::zzz); ol(i,Cart::yyyy) = PmB1*ol(i,Cart::yyy) + ny[i]*fak*ol(i_less_y[i],Cart::yyy) + 3*term_yy; ol(i,Cart::yyyz) = PmB2*ol(i,Cart::yyy) + nz[i]*fak*ol(i_less_z[i],Cart::yyy); ol(i,Cart::yyzz) = PmB1*ol(i,Cart::yzz) + ny[i]*fak*ol(i_less_y[i],Cart::yzz) + term_zz; ol(i,Cart::yzzz) = PmB1*ol(i,Cart::zzz) + ny[i]*fak*ol(i_less_y[i],Cart::zzz); ol(i,Cart::zzzz) = PmB2*ol(i,Cart::zzz) + nz[i]*fak*ol(i_less_z[i],Cart::zzz) + 3*term_zz; } //------------------------------------------------------ } // end if (lmax_col > 3) //Integrals p - s if (lmax_row > 0) { kin(Cart::x,0) = xi2*ol(Cart::x,0) + PmA0*kin(0,0); kin(Cart::y,0) = xi2*ol(Cart::y,0) + PmA1*kin(0,0); kin(Cart::z,0) = xi2*ol(Cart::z,0) + PmA2*kin(0,0); } //------------------------------------------------------ //Integrals d - s if (lmax_row > 1) { double term = fak*kin(0,0)-fak_a*ol(0,0); kin(Cart::xx,0) = xi2*ol(Cart::xx,0) + PmA0*kin(Cart::x,0) + term; kin(Cart::xy,0) = xi2*ol(Cart::xy,0) + PmA0*kin(Cart::y,0); kin(Cart::xz,0) = xi2*ol(Cart::xz,0) + PmA0*kin(Cart::z,0); kin(Cart::yy,0) = xi2*ol(Cart::yy,0) + PmA1*kin(Cart::y,0) + term; kin(Cart::yz,0) = xi2*ol(Cart::yz,0) + PmA1*kin(Cart::z,0); kin(Cart::zz,0) = xi2*ol(Cart::zz,0) + PmA2*kin(Cart::z,0) + term; } //------------------------------------------------------ //Integrals f - s if (lmax_row > 2) { kin(Cart::xxx,0) = xi2*ol(Cart::xxx,0) + PmA0*kin(Cart::xx,0) + 2*(fak*kin(Cart::x,0)-fak_a*ol(Cart::x,0)); kin(Cart::xxy,0) = xi2*ol(Cart::xxy,0) + PmA1*kin(Cart::xx,0); kin(Cart::xxz,0) = xi2*ol(Cart::xxz,0) + PmA2*kin(Cart::xx,0); kin(Cart::xyy,0) = xi2*ol(Cart::xyy,0) + PmA0*kin(Cart::yy,0); kin(Cart::xyz,0) = xi2*ol(Cart::xyz,0) + PmA0*kin(Cart::yz,0); kin(Cart::xzz,0) = xi2*ol(Cart::xzz,0) + PmA0*kin(Cart::zz,0); kin(Cart::yyy,0) = xi2*ol(Cart::yyy,0) + PmA1*kin(Cart::yy,0) + 2*(fak*kin(Cart::y,0)-fak_a*ol(Cart::y,0)); kin(Cart::yyz,0) = xi2*ol(Cart::yyz,0) + PmA2*kin(Cart::yy,0); kin(Cart::yzz,0) = xi2*ol(Cart::yzz,0) + PmA1*kin(Cart::zz,0); kin(Cart::zzz,0) = xi2*ol(Cart::zzz,0) + PmA2*kin(Cart::zz,0) + 2*(fak*kin(Cart::z,0)-fak_a*ol(Cart::z,0)); } //------------------------------------------------------ //Integrals g - s if (lmax_row > 3) { double term_xx = fak*kin(Cart::xx,0)-fak_a*ol(Cart::xx,0); double term_yy = fak*kin(Cart::yy,0)-fak_a*ol(Cart::yy,0); double term_zz = fak*kin(Cart::zz,0)-fak_a*ol(Cart::zz,0); kin(Cart::xxxx,0) = xi2*ol(Cart::xxxx,0) + PmA0*kin(Cart::xxx,0) + 3*term_xx; kin(Cart::xxxy,0) = xi2*ol(Cart::xxxy,0) + PmA1*kin(Cart::xxx,0); kin(Cart::xxxz,0) = xi2*ol(Cart::xxxz,0) + PmA2*kin(Cart::xxx,0); kin(Cart::xxyy,0) = xi2*ol(Cart::xxyy,0) + PmA0*kin(Cart::xyy,0) + term_yy; kin(Cart::xxyz,0) = xi2*ol(Cart::xxyz,0) + PmA1*kin(Cart::xxz,0); kin(Cart::xxzz,0) = xi2*ol(Cart::xxzz,0) + PmA0*kin(Cart::xzz,0) + term_zz; kin(Cart::xyyy,0) = xi2*ol(Cart::xyyy,0) + PmA0*kin(Cart::yyy,0); kin(Cart::xyyz,0) = xi2*ol(Cart::xyyz,0) + PmA0*kin(Cart::yyz,0); kin(Cart::xyzz,0) = xi2*ol(Cart::xyzz,0) + PmA0*kin(Cart::yzz,0); kin(Cart::xzzz,0) = xi2*ol(Cart::xzzz,0) + PmA0*kin(Cart::zzz,0); kin(Cart::yyyy,0) = xi2*ol(Cart::yyyy,0) + PmA1*kin(Cart::yyy,0) + 3*term_yy; kin(Cart::yyyz,0) = xi2*ol(Cart::yyyz,0) + PmA2*kin(Cart::yyy,0); kin(Cart::yyzz,0) = xi2*ol(Cart::yyzz,0) + PmA1*kin(Cart::yzz,0) + term_zz; kin(Cart::yzzz,0) = xi2*ol(Cart::yzzz,0) + PmA1*kin(Cart::zzz,0); kin(Cart::zzzz,0) = xi2*ol(Cart::zzzz,0) + PmA2*kin(Cart::zzz,0) + 3*term_zz; } //------------------------------------------------------ if (lmax_col > 0) { //Integrals s - p kin(0,Cart::x) = xi2*ol(0,Cart::x) + PmB0*kin(0,0); kin(0,Cart::y) = xi2*ol(0,Cart::y) + PmB1*kin(0,0); kin(0,Cart::z) = xi2*ol(0,Cart::z) + PmB2*kin(0,0); //------------------------------------------------------ //Integrals p - p d - p f - p g - p for (int i = 1; i < n_orbitals[lmax_row]; i++) { kin(i,Cart::x) = xi2*ol(i,Cart::x) + PmB0*kin(i,0) + nx[i]*fak*kin(i_less_x[i],0); kin(i,Cart::y) = xi2*ol(i,Cart::y) + PmB1*kin(i,0) + ny[i]*fak*kin(i_less_y[i],0); kin(i,Cart::z) = xi2*ol(i,Cart::z) + PmB2*kin(i,0) + nz[i]*fak*kin(i_less_z[i],0); } //------------------------------------------------------ } // end if (lmax_col > 0) if (lmax_col > 1) { //Integrals s - d double term = fak*kin(0,0)-fak_b*ol(0,0); kin(0,Cart::xx) = xi2*ol(0,Cart::xx) + PmB0*kin(0,Cart::x) + term; kin(0,Cart::xy) = xi2*ol(0,Cart::xy) + PmB0*kin(0,Cart::y); kin(0,Cart::xz) = xi2*ol(0,Cart::xz) + PmB0*kin(0,Cart::z); kin(0,Cart::yy) = xi2*ol(0,Cart::yy) + PmB1*kin(0,Cart::y) + term; kin(0,Cart::yz) = xi2*ol(0,Cart::yz) + PmB1*kin(0,Cart::z); kin(0,Cart::zz) = xi2*ol(0,Cart::zz) + PmB2*kin(0,Cart::z) + term; //------------------------------------------------------ //Integrals p - d d - d f - d g - d for (int i = 1; i < n_orbitals[lmax_row]; i++) { double term = fak*kin(i,0)-fak_b*ol(i,0); kin(i,Cart::xx) = xi2*ol(i,Cart::xx) + PmB0*kin(i,Cart::x) + nx[i]*fak*kin(i_less_x[i],Cart::x) + term; kin(i,Cart::xy) = xi2*ol(i,Cart::xy) + PmB0*kin(i,Cart::y) + nx[i]*fak*kin(i_less_x[i],Cart::y); kin(i,Cart::xz) = xi2*ol(i,Cart::xz) + PmB0*kin(i,Cart::z) + nx[i]*fak*kin(i_less_x[i],Cart::z); kin(i,Cart::yy) = xi2*ol(i,Cart::yy) + PmB1*kin(i,Cart::y) + ny[i]*fak*kin(i_less_y[i],Cart::y) + term; kin(i,Cart::yz) = xi2*ol(i,Cart::yz) + PmB1*kin(i,Cart::z) + ny[i]*fak*kin(i_less_y[i],Cart::z); kin(i,Cart::zz) = xi2*ol(i,Cart::zz) + PmB2*kin(i,Cart::z) + nz[i]*fak*kin(i_less_z[i],Cart::z) + term; // } } //------------------------------------------------------ } // end if (lmax_col > 1) if (lmax_col > 2) { //Integrals s - f kin(0,Cart::xxx) = xi2*ol(0,Cart::xxx) + PmB0*kin(0,Cart::xx) + 2*(fak*kin(0,Cart::x)-fak_b*ol(0,Cart::x)); kin(0,Cart::xxy) = xi2*ol(0,Cart::xxy) + PmB1*kin(0,Cart::xx); kin(0,Cart::xxz) = xi2*ol(0,Cart::xxz) + PmB2*kin(0,Cart::xx); kin(0,Cart::xyy) = xi2*ol(0,Cart::xyy) + PmB0*kin(0,Cart::yy); kin(0,Cart::xyz) = xi2*ol(0,Cart::xyz) + PmB0*kin(0,Cart::yz); kin(0,Cart::xzz) = xi2*ol(0,Cart::xzz) + PmB0*kin(0,Cart::zz); kin(0,Cart::yyy) = xi2*ol(0,Cart::yyy) + PmB1*kin(0,Cart::yy) + 2*(fak*kin(0,Cart::y)-fak_b*ol(0,Cart::y)); kin(0,Cart::yyz) = xi2*ol(0,Cart::yyz) + PmB2*kin(0,Cart::yy); kin(0,Cart::yzz) = xi2*ol(0,Cart::yzz) + PmB1*kin(0,Cart::zz); kin(0,Cart::zzz) = xi2*ol(0,Cart::zzz) + PmB2*kin(0,Cart::zz) + 2*(fak*kin(0,Cart::z)-fak_b*ol(0,Cart::z)); //------------------------------------------------------ //Integrals p - f d - f f - f g - f for (int i = 1; i < n_orbitals[lmax_row]; i++) { double term_x = 2*(fak*kin(i,Cart::x)-fak_b*ol(i,Cart::x)); double term_y = 2*(fak*kin(i,Cart::y)-fak_b*ol(i,Cart::y)); double term_z = 2*(fak*kin(i,Cart::z)-fak_b*ol(i,Cart::z)); kin(i,Cart::xxx) = xi2*ol(i,Cart::xxx) + PmB0*kin(i,Cart::xx) + nx[i]*fak*kin(i_less_x[i],Cart::xx) + term_x; kin(i,Cart::xxy) = xi2*ol(i,Cart::xxy) + PmB1*kin(i,Cart::xx) + ny[i]*fak*kin(i_less_y[i],Cart::xx); kin(i,Cart::xxz) = xi2*ol(i,Cart::xxz) + PmB2*kin(i,Cart::xx) + nz[i]*fak*kin(i_less_z[i],Cart::xx); kin(i,Cart::xyy) = xi2*ol(i,Cart::xyy) + PmB0*kin(i,Cart::yy) + nx[i]*fak*kin(i_less_x[i],Cart::yy); kin(i,Cart::xyz) = xi2*ol(i,Cart::xyz) + PmB0*kin(i,Cart::yz) + nx[i]*fak*kin(i_less_x[i],Cart::yz); kin(i,Cart::xzz) = xi2*ol(i,Cart::xzz) + PmB0*kin(i,Cart::zz) + nx[i]*fak*kin(i_less_x[i],Cart::zz); kin(i,Cart::yyy) = xi2*ol(i,Cart::yyy) + PmB1*kin(i,Cart::yy) + ny[i]*fak*kin(i_less_y[i],Cart::yy) + term_y; kin(i,Cart::yyz) = xi2*ol(i,Cart::yyz) + PmB2*kin(i,Cart::yy) + nz[i]*fak*kin(i_less_z[i],Cart::yy); kin(i,Cart::yzz) = xi2*ol(i,Cart::yzz) + PmB1*kin(i,Cart::zz) + ny[i]*fak*kin(i_less_y[i],Cart::zz); kin(i,Cart::zzz) = xi2*ol(i,Cart::zzz) + PmB2*kin(i,Cart::zz) + nz[i]*fak*kin(i_less_z[i],Cart::zz) + term_z; } //------------------------------------------------------ } // end if (lmax_col > 2) if (lmax_col > 3) { //Integrals s - g double term_xx = fak*kin(0,Cart::xx)-fak_b*ol(0,Cart::xx); double term_yy = fak*kin(0,Cart::yy)-fak_b*ol(0,Cart::yy); double term_zz = fak*kin(0,Cart::zz)-fak_b*ol(0,Cart::zz); kin(0,Cart::xxxx) = xi2*ol(0,Cart::xxxx) + PmB0*kin(0,Cart::xxx) + 3*term_xx; kin(0,Cart::xxxy) = xi2*ol(0,Cart::xxxy) + PmB1*kin(0,Cart::xxx); kin(0,Cart::xxxz) = xi2*ol(0,Cart::xxxz) + PmB2*kin(0,Cart::xxx); kin(0,Cart::xxyy) = xi2*ol(0,Cart::xxyy) + PmB0*kin(0,Cart::xyy) + term_yy; kin(0,Cart::xxyz) = xi2*ol(0,Cart::xxyz) + PmB1*kin(0,Cart::xxz); kin(0,Cart::xxzz) = xi2*ol(0,Cart::xxzz) + PmB0*kin(0,Cart::xzz) + term_zz; kin(0,Cart::xyyy) = xi2*ol(0,Cart::xyyy) + PmB0*kin(0,Cart::yyy); kin(0,Cart::xyyz) = xi2*ol(0,Cart::xyyz) + PmB0*kin(0,Cart::yyz); kin(0,Cart::xyzz) = xi2*ol(0,Cart::xyzz) + PmB0*kin(0,Cart::yzz); kin(0,Cart::xzzz) = xi2*ol(0,Cart::xzzz) + PmB0*kin(0,Cart::zzz); kin(0,Cart::yyyy) = xi2*ol(0,Cart::yyyy) + PmB1*kin(0,Cart::yyy) + 3*term_yy; kin(0,Cart::yyyz) = xi2*ol(0,Cart::yyyz) + PmB2*kin(0,Cart::yyy); kin(0,Cart::yyzz) = xi2*ol(0,Cart::yyzz) + PmB1*kin(0,Cart::yzz) + term_zz; kin(0,Cart::yzzz) = xi2*ol(0,Cart::yzzz) + PmB1*kin(0,Cart::zzz); kin(0,Cart::zzzz) = xi2*ol(0,Cart::zzzz) + PmB2*kin(0,Cart::zzz) + 3*term_zz; //------------------------------------------------------ //Integrals p - g d - g f - g g - g for (int i = 1; i < n_orbitals[lmax_row]; i++) { double term_xx = fak*kin(i,Cart::xx)-fak_b*ol(i,Cart::xx); double term_yy = fak*kin(i,Cart::yy)-fak_b*ol(i,Cart::yy); double term_zz = fak*kin(i,Cart::zz)-fak_b*ol(i,Cart::zz); kin(i,Cart::xxxx) = xi2*ol(i,Cart::xxxx) + PmB0*kin(i,Cart::xxx) + nx[i]*fak*kin(i_less_x[i],Cart::xxx) + 3*term_xx; kin(i,Cart::xxxy) = xi2*ol(i,Cart::xxxy) + PmB1*kin(i,Cart::xxx) + ny[i]*fak*kin(i_less_y[i],Cart::xxx); kin(i,Cart::xxxz) = xi2*ol(i,Cart::xxxz) + PmB2*kin(i,Cart::xxx) + nz[i]*fak*kin(i_less_z[i],Cart::xxx); kin(i,Cart::xxyy) = xi2*ol(i,Cart::xxyy) + PmB0*kin(i,Cart::xyy) + nx[i]*fak*kin(i_less_x[i],Cart::xyy) + term_yy; kin(i,Cart::xxyz) = xi2*ol(i,Cart::xxyz) + PmB1*kin(i,Cart::xxz) + ny[i]*fak*kin(i_less_y[i],Cart::xxz); kin(i,Cart::xxzz) = xi2*ol(i,Cart::xxzz) + PmB0*kin(i,Cart::xzz) + nx[i]*fak*kin(i_less_x[i],Cart::xzz) + term_zz; kin(i,Cart::xyyy) = xi2*ol(i,Cart::xyyy) + PmB0*kin(i,Cart::yyy) + nx[i]*fak*kin(i_less_x[i],Cart::yyy); kin(i,Cart::xyyz) = xi2*ol(i,Cart::xyyz) + PmB0*kin(i,Cart::yyz) + nx[i]*fak*kin(i_less_x[i],Cart::yyz); kin(i,Cart::xyzz) = xi2*ol(i,Cart::xyzz) + PmB0*kin(i,Cart::yzz) + nx[i]*fak*kin(i_less_x[i],Cart::yzz); kin(i,Cart::xzzz) = xi2*ol(i,Cart::xzzz) + PmB0*kin(i,Cart::zzz) + nx[i]*fak*kin(i_less_x[i],Cart::zzz); kin(i,Cart::yyyy) = xi2*ol(i,Cart::yyyy) + PmB1*kin(i,Cart::yyy) + ny[i]*fak*kin(i_less_y[i],Cart::yyy) + 3*term_yy; kin(i,Cart::yyyz) = xi2*ol(i,Cart::yyyz) + PmB2*kin(i,Cart::yyy) + nz[i]*fak*kin(i_less_z[i],Cart::yyy); kin(i,Cart::yyzz) = xi2*ol(i,Cart::yyzz) + PmB1*kin(i,Cart::yzz) + ny[i]*fak*kin(i_less_y[i],Cart::yzz) + term_zz; kin(i,Cart::yzzz) = xi2*ol(i,Cart::yzzz) + PmB1*kin(i,Cart::zzz) + ny[i]*fak*kin(i_less_y[i],Cart::zzz); kin(i,Cart::zzzz) = xi2*ol(i,Cart::zzzz) + PmB2*kin(i,Cart::zzz) + nz[i]*fak*kin(i_less_z[i],Cart::zzz) + 3*term_zz; } //------------------------------------------------------ } // end if (lmax_col > 3) // normalization and cartesian -> spherical factors Eigen::MatrixXd kin_sph = getTrafo(*itr).transpose()*kin*getTrafo(*itc); // save to matrix for ( unsigned i = 0; i< matrix.rows(); i++ ) { for (unsigned j = 0; j < matrix.cols(); j++) { matrix(i,j) += kin_sph(i+shell_row->getOffset(),j+shell_col->getOffset()); } } }//col }//row return; } } }
45.826087
122
0.517552
[ "vector" ]
bf8da8dccbc6fdf8ea3aaf30be83b2a2cb0d79e7
3,814
cpp
C++
StrSTUN-synthesizer/strstunlib0/src/VisitorPretty.cpp
HALOCORE/SynGuar
8f7f9ba52e83091ad3def501169fd60d20b28321
[ "MIT" ]
1
2021-06-23T05:10:36.000Z
2021-06-23T05:10:36.000Z
StrSTUN-synthesizer/strstunlib0/src/VisitorPretty.cpp
HALOCORE/SynGuar
8f7f9ba52e83091ad3def501169fd60d20b28321
[ "MIT" ]
null
null
null
StrSTUN-synthesizer/strstunlib0/src/VisitorPretty.cpp
HALOCORE/SynGuar
8f7f9ba52e83091ad3def501169fd60d20b28321
[ "MIT" ]
null
null
null
#include "VisitorPretty.hpp" VisitorPretty* VisitorPretty::common; VisitorPretty::VisitorPretty() { this->indent = 0; VisitorPretty::common = this; } void VisitorPretty::indentOutput() { for (int i = 0; i < indent; i ++) { std::cerr << " "; } } void VisitorPretty::indentInc() { this->indent += 2; } void VisitorPretty::indentDec() { this->indent -= 2; } void VisitorPretty::visit(ValueVector* valvec) { indentOutput(); std::cerr << "[ValueVector "; valvec->accept(this); std::cerr << "]" << std::endl; return; } void VisitorPretty::visit(ValBool* val) { if (val->status == ValStatus::VALID) std::cerr << "(Bool " << val->value << ")"; else std::cerr << "(Bool " << ValStatusRepr[val->status] << ")"; return; } void VisitorPretty::visit(ValInt* val) { if (val->status == ValStatus::VALID) std::cerr << "(Int " << val->value << ")"; else std::cerr << "(Int " << ValStatusRepr[val->status] << ")"; return; } void VisitorPretty::visit(ValStr* val) { if (val->status == ValStatus::VALID) std::cerr << "(Str " << val->value << ")"; else std::cerr << "(Str " << ValStatusRepr[val->status] << ")"; return; } void VisitorPretty::visit(Program* prog) { indentOutput(); std::cerr << "visiting Program: " << "[ " << prog->componentId << " ] "; for(auto ty : prog->inputTypes) { std::cerr << ", " << ValTypeRepr[ty]; } std::cerr << " -> " << ValTypeRepr[prog->outputType] << std::endl; indentInc(); prog->accept(this); indentDec(); return; } void VisitorPretty::visit(ProgramManager* pmgr) { indentOutput(); std::cerr << "visiting ProgramManager: " << std::endl; indentInc(); pmgr->accept(this); indentDec(); return; } void VisitorPretty::visit(ComponentBuiltin* compbin) { indentOutput(); std::cerr << "visiting ComponentBuiltin: " << compbin->getComponentId() << ", " << std::endl; indentInc(); compbin->accept(this); indentDec(); return; } void VisitorPretty::visit(ComponentInput* compin) { indentOutput(); std::cerr << "visiting ComponentInput: " << compin->getComponentId() << ", " << compin->getParamIndex() << std::endl; indentInc(); compin->accept(this); indentDec(); return; } void VisitorPretty::visit(ComponentIfThenElse* compin) { indentOutput(); std::cerr << "visiting ComponentIfThenElse: " << compin->getComponentId() << std::endl; indentInc(); compin->accept(this); indentDec(); return; } void VisitorPretty::visit(ComponentSynthesized* compin) { indentOutput(); std::cerr << "visiting ComponentSynthesized: " << compin->getComponentId() << std::endl; indentInc(); compin->accept(this); indentDec(); return; } void VisitorPretty::visit(ComponentManager* cmgr) { indentOutput(); std::cerr << "visiting ComponentManager: " << std::endl; indentInc(); cmgr->accept(this); indentDec(); return; } void VisitorPretty::visit(Goal* goal) { indentOutput(); std::cerr << "visiting Goal: IsConcrete=" << goal->isConcrete << std::endl; indentInc(); goal->accept(this); indentDec(); return; } void VisitorPretty::visit(GoalGraphManager* gmgr) { indentOutput(); std::cerr << "visiting GoalGraphManager: " << "isGoalRootSolved: " << gmgr->getIsGoalRootSolved() << std::endl; indentInc(); gmgr->accept(this); indentDec(); } void VisitorPretty::printIntVec(std::vector<int>& intvec) { indentOutput(); std::cerr << "[IntVec size:" << intvec.size() << " ("; for(int i = 0; i < intvec.size(); i++) { std::cerr << "[" << i << "]:" << intvec[i] << ", "; } std::cerr << ")]\n"; }
25.258278
84
0.583115
[ "vector" ]
bf8f094b1ccd5aded7d823f9ee8bfc497eeb537a
16,561
cpp
C++
Robotron/Source/DirectX9Framework/GameBase/GameLogic.cpp
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
Robotron/Source/DirectX9Framework/GameBase/GameLogic.cpp
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
Robotron/Source/DirectX9Framework/GameBase/GameLogic.cpp
ThatBeanBag/Slimfish
7b0f821bccf2cae7d67f8a822f078def7a2d354d
[ "Apache-2.0" ]
null
null
null
// // Bachelor of Software Engineering // Media Design School // Auckland // New Zealand // // (c) 2005 - 2015 Media Design School // // File Name : GameLogic.cpp // Description : CGameLogic implementation file. // Author : Hayden Asplet. // Mail // PCH #include "GameStd.h" // Library Includes // This Include #include "GameLogic.h" // Local Includes #include "EventData_RequestNewActor.h" #include "..\Actor\Actor.h" #include "..\Actor\TransformComponent.h" #include "..\Actor\PhysicsComponent.h" #include "..\Physics\BulletSDKPhysics.h" #include "..\Events\EventData_ClientJoin.h" #include "..\Events\EventData_RequestDestroyActor.h" #include "..\View\NetworkView.h" #include "..\AI\SteeringBehaviours.h" CGameLogic::CGameLogic() :m_fElapsedTime(0.0f), m_bIsRemote(false), m_eState(GS_INVALID), m_iNumPlayers(0), m_iNumLoadedPlayers(0) { m_options.m_iMaxPlayers = 16; // TODO: remove this hard code. } CGameLogic::~CGameLogic() { for (auto iter = m_actorMap.begin(); iter != m_actorMap.end(); ++iter) { iter->second->DestroyComponents(); } } bool CGameLogic::Initialise() { ChangeState(GS_INITIALISING); // We are now initialising. RegisterDelegates(); // Also registers derived delegates. // Create the game physics engine. m_pPhysics = std::move(VCreateGamePhysics()); if (m_pPhysics) { // Is there physics? if (!m_pPhysics->VInitialize()) { DEBUG_ERROR("Failed to initialise physics"); return false; } } else { // No physics. // It's valid to have no physics. } // Initialise derived. if (!VInitialise()) { return false; } // Done initialisation goto main menu. ChangeState(GS_MAINMENU); return true; } bool CGameLogic::OnRestore() { bool bHasSuceeded = true; // Restore game views. for (auto iter = m_gameViews.begin(); iter != m_gameViews.end(); ++iter) { if (*iter) { if (!(*iter)->VOnRestore()) { bHasSuceeded = false; } } } // Restore derived logic. return bHasSuceeded && VOnRestore(); } bool CGameLogic::LoadGame() { // Load derived game. return VLoadGame(); } void CGameLogic::Update(float _fDeltaTime) { m_fElapsedTime += _fDeltaTime; // Update derived logic. VUpdate(_fDeltaTime); m_steeringBehaviours.Update(_fDeltaTime); for (auto iter = m_gameViews.begin(); iter != m_gameViews.end(); ++iter) { if (*iter) { (*iter)->VOnUpdate(_fDeltaTime); } } for (auto iter = m_actorMap.begin(); iter != m_actorMap.end(); ++iter) { iter->second->Update(_fDeltaTime); } if (m_pPhysics) { m_pPhysics->VUpdate(_fDeltaTime); m_pPhysics->VSyncScene(); } } void CGameLogic::RegisterDelegates() { // Register base logic delegates. CEventManager* pEventManager = CEventManager::GetInstance().get(); pEventManager->AddListener<CEventData_RequestStartGame>(MakeDelegate(this, &CGameLogic::StartGameDelegate)); pEventManager->AddListener<CEventData_JoinGame>(MakeDelegate(this, &CGameLogic::JoinGameDelegate)); pEventManager->AddListener<CEventData_HostGame>(MakeDelegate(this, &CGameLogic::HostGameDelegate)); pEventManager->AddListener<CEventData_ClientJoin>(MakeDelegate(this, &CGameLogic::ClientJoinDelegate)); pEventManager->AddListener<CEventData_RequestPlayerReady>(MakeDelegate(this, &CGameLogic::RequestPlayerReadyDelegate)); pEventManager->AddListener<CEventData_RequestPlayerLeave>(MakeDelegate(this, &CGameLogic::RequestPlayerLeaveDelegate)); pEventManager->AddListener<CEventData_LoadedGame>(MakeDelegate(this, &CGameLogic::LoadedGameDelegate)); // Register derived delegates. VRegisterDelegates(); } void CGameLogic::RemoveDelegates() { // Remove base logic delegates. CEventManager* pEventManager = CEventManager::GetInstance().get(); pEventManager->RemoveListener<CEventData_RequestStartGame>(MakeDelegate(this, &CGameLogic::StartGameDelegate)); pEventManager->RemoveListener<CEventData_JoinGame>(MakeDelegate(this, &CGameLogic::JoinGameDelegate)); pEventManager->RemoveListener<CEventData_HostGame>(MakeDelegate(this, &CGameLogic::HostGameDelegate)); pEventManager->RemoveListener<CEventData_ClientJoin>(MakeDelegate(this, &CGameLogic::ClientJoinDelegate)); pEventManager->RemoveListener<CEventData_RequestPlayerReady>(MakeDelegate(this, &CGameLogic::RequestPlayerReadyDelegate)); pEventManager->RemoveListener<CEventData_RequestPlayerLeave>(MakeDelegate(this, &CGameLogic::RequestPlayerLeaveDelegate)); pEventManager->RemoveListener<CEventData_LoadedGame>(MakeDelegate(this, &CGameLogic::LoadedGameDelegate)); if (m_bIsRemote) { pEventManager->RemoveListener<CEventData_RequestNewActor>(MakeDelegate(this, &CGameLogic::RequestNewActorDelegate)); pEventManager->RemoveListener<CEventData_RequestDestroyActor>(MakeDelegate(this, &CGameLogic::RequestDestroyActorDelegate)); } // Remove derived delegates. VRemoveDelegates(); } void CGameLogic::ChangeState(EGameState _eNewState) { // Set the internal state to the new state. m_eState = _eNewState; switch (m_eState) { case CGameLogic::GS_INVALID: { break; } case CGameLogic::GS_INITIALISING: { break; } case CGameLogic::GS_MAINMENU: { break; } case CGameLogic::GS_LOBBY: { break; } case CGameLogic::GS_LOADING: { break; } case CGameLogic::GS_RUNNING: { break; } default: { break; } } VOnStateChange(_eNewState); } void CGameLogic::AddGameView(unique_ptr<IGameView> _pView) { _pView->VOnRestore(); m_gameViews.push_back(std::move(_pView)); } void CGameLogic::RemoveGameView(IGameView* _pView) { for (auto iter = m_gameViews.begin(); iter != m_gameViews.end(); ++iter) { if (iter->get() == _pView) { m_gameViews.erase(iter); break; } } } TActorID CGameLogic::CreateActor(const std::string& _krActorResource, const CMatrix4x4* _pInitialTransform, TActorID _serverActorID) { /*if (m_bIsRemote && (m_eState == GS_SPAWNING_PLAYERS || m_eState == GS_RUNNING || m_eState == GS_WAITING_FOR_PLAYERS_TO_LOAD)) { DEBUG_ASSERT(_serverActorID != CActor::s_kINVALID_ACTOR_ID); // If we remote the serverActorID must be valid. } else { DEBUG_ASSERT(_serverActorID == CActor::s_kINVALID_ACTOR_ID); // If we are running the logic the serverActorID must be invalid. }*/ unique_ptr<CActor> pActor = m_actorFactory.CreateActor(_krActorResource, _pInitialTransform, _serverActorID); if (pActor) { TActorID actorID = pActor->GetID(); if (!m_bIsRemote && (m_eState == GS_SPAWNING_PLAYERS || m_eState == GS_RUNNING)) { // Request actor creation on client/remote machines. shared_ptr<CEventData_RequestNewActor> pNewActor(new CEventData_RequestNewActor(_krActorResource, _pInitialTransform, pActor->GetID())); CEventManager::GetInstance()->TriggerEvent(pNewActor); } m_actorMap[actorID] = std::move(pActor); return actorID; } else { return CActor::s_kINVALID_ACTOR_ID; } return CActor::s_kINVALID_ACTOR_ID; } CActor* CGameLogic::GetActor(TActorID _actorID) { auto findIter = m_actorMap.find(_actorID); if (findIter != m_actorMap.end()) { // Did we find an actor with the specified ID? return findIter->second.get(); } return nullptr; } void CGameLogic::DestroyActor(TActorID _actorID) { auto findIter = m_actorMap.find(_actorID); if (findIter != m_actorMap.end()) { // Did we find an actor with the specified ID? // First let other sub-systems know about the destroying of the actor. shared_ptr<CEventData_DestroyActor> pEvent(new CEventData_DestroyActor(_actorID)); CEventManager::GetInstance()->TriggerEvent(pEvent); if (!m_bIsRemote) { shared_ptr<CEventData_RequestDestroyActor> pEvent(new CEventData_RequestDestroyActor(_actorID)); CEventManager::GetInstance()->QueueEvent(pEvent); } // Destroy the actors components, this must be done before destroying the actor. findIter->second->DestroyComponents(); // Remove the actor. m_actorMap.erase(findIter); } else { // No actor found. DEBUG_WARNING("Failed to find actor with id: " + ToString(_actorID) + " to destroy"); } } void CGameLogic::SetAsRemote() { m_bIsRemote = true; CEventManager::GetInstance()->AddListener<CEventData_RequestNewActor>(MakeDelegate(this, &CGameLogic::RequestNewActorDelegate)); CEventManager::GetInstance()->AddListener<CEventData_RequestDestroyActor>(MakeDelegate(this, &CGameLogic::RequestDestroyActorDelegate)); // A remote logic does not need to run physics. m_pPhysics.reset(nullptr); } bool CGameLogic::IsRemote() const { return m_bIsRemote; } bool CGameLogic::OnMsgProc(const TAppMsg& _krMsg) { for (auto iter = m_gameViews.begin(); iter != m_gameViews.end(); ++iter) { if (*iter) { if ((*iter)->VOnMsgProc(_krMsg)) { // Did this view handle the message? return true; // Breaks from the loop, so no more game views can handle the input. } } } // Failed to be handled. return false; } void CGameLogic::Render() { // Render the game views. for (auto iter = m_gameViews.begin(); iter != m_gameViews.end(); ++iter) { if (*iter) { (*iter)->VRender(); } } if (m_pPhysics) { g_pApp->GetRenderer()->VSetWorldTransform(&CMatrix4x4::s_kIdentity); //m_pPhysics->VDrawDebugDiagnostics(); } } unique_ptr<IPhysics> CGameLogic::VCreateGamePhysics() { unique_ptr<CBulletSDKPhysics> pPhysics(new CBulletSDKPhysics()); return std::move(pPhysics); } void CGameLogic::StartGameDelegate(shared_ptr<IEventData> _pEventData) { shared_ptr<CEventData_RequestStartGame> pStartGameData = static_pointer_cast<CEventData_RequestStartGame>(_pEventData); if (m_eState == GS_LOBBY || m_eState == GS_MAINMENU) { ChangeState(GS_LOADING); } else if (m_eState == GS_WAITING_FOR_PLAYERS_TO_LOAD) { ChangeState(GS_SPAWNING_PLAYERS); } } void CGameLogic::JoinGameDelegate(shared_ptr<IEventData> _pEventData) { shared_ptr<CEventData_JoinGame> pJoinGameData = static_pointer_cast<CEventData_JoinGame>(_pEventData); SetAsRemote(); m_options.m_iMaxPlayers = pJoinGameData->GetMaxPlayers(); m_options.m_strUsername = pJoinGameData->GetUsername(); TAddress address = pJoinGameData->GetAddress(); if (address.m_strIPAddress != "" && address.m_usPort != 0) { // Create a new event forwarder to forward events to this client. unique_ptr<CNetworkEventForwarder> pEventForwarder(new CNetworkEventForwarder(address)); if (!pEventForwarder) { std::string strError = "Failed to create network event forwarder for address: "; strError += address.m_strIPAddress + ":" + ToString(address.m_usPort); DEBUG_ERROR(strError); return; } // Add the events to forward to the server. pEventForwarder->AddEventForwarder<CEventData_RequestPlayerReady>(); pEventForwarder->AddEventForwarder<CEventData_LoadedGame>(); pEventForwarder->AddEventForwarder<CEventData_RequestPlayerLeave>(); VAddNetworkEventsClientToServer(pEventForwarder.get()); // Add the server as a view to the game. unique_ptr<CNetworkView> pNetworkView(new CNetworkView(std::move(pEventForwarder), "Server")); if (pNetworkView) { AddGameView(std::move(pNetworkView)); } } else { DEBUG_ERROR("Join game event is invalid"); } ChangeState(GS_LOBBY); } void CGameLogic::HostGameDelegate(shared_ptr<IEventData> _pEventData) { shared_ptr<CEventData_HostGame> pHostGameData = static_pointer_cast<CEventData_HostGame>(_pEventData); CServerNetwork* pNetwork = g_pApp->CreateServerNetwork(pHostGameData->GetServerName()); m_options.m_strUsername = pHostGameData->GetUsername(); // We've joined the game. m_iNumPlayers = 1; if (pNetwork) { ChangeState(GS_LOBBY); } else { // TODO: Display a nice error message. ChangeState(GS_MAINMENU); } } void CGameLogic::RequestNewActorDelegate(shared_ptr<IEventData> _pEventData) { DEBUG_ASSERT(m_bIsRemote); // Only remote logic's should be listening to this event. shared_ptr<CEventData_RequestNewActor> pRequestNewActorData = static_pointer_cast<CEventData_RequestNewActor>(_pEventData); CMatrix4x4 initialTransform = pRequestNewActorData->GetInitialTransform(); TActorID serverActorID = pRequestNewActorData->GetServerActorID(); std::string strActorResource = pRequestNewActorData->GetActorResource(); TActorID actorID = CActor::s_kINVALID_ACTOR_ID; if (pRequestNewActorData->HasInitialTransform()) { actorID = CreateActor(strActorResource, &initialTransform, serverActorID); } else { actorID = CreateActor(strActorResource, nullptr, serverActorID); } if (actorID != serverActorID) { DEBUG_WARNING("Failed to create actor request by server from resource \"" + strActorResource + "\""); } } void CGameLogic::RequestDestroyActorDelegate(shared_ptr<IEventData> _pEventData) { DEBUG_ASSERT(m_bIsRemote); // Only remote logic's should be listening to this event. shared_ptr<CEventData_RequestDestroyActor> pRequestNewActorData = static_pointer_cast<CEventData_RequestDestroyActor>(_pEventData); TActorID actorID = pRequestNewActorData->GetActorID(); DestroyActor(actorID); } void CGameLogic::RequestPlayerReadyDelegate(shared_ptr<IEventData> _pEventData) { // This event is to be received by the server to fire off a player ready event. // This avoids entering an infinite loop. if (m_bIsRemote) { return; } shared_ptr<CEventData_RequestPlayerReady> pPlayerReadyData = static_pointer_cast<CEventData_RequestPlayerReady>(_pEventData); shared_ptr<CEventData_PlayerReady> pEvent(new CEventData_PlayerReady(pPlayerReadyData->GetUsername(), pPlayerReadyData->IsReady())); CEventManager::GetInstance()->QueueEvent(pEvent); } void CGameLogic::RequestPlayerLeaveDelegate(shared_ptr<IEventData> _pEventData) { // This event is to be received by the server to fire off a player left event. // This avoids entering an infinite loop. if (m_bIsRemote) { return; } shared_ptr<CEventData_RequestPlayerLeave> pRequestLeaveData = static_pointer_cast<CEventData_RequestPlayerLeave>(_pEventData); shared_ptr<CEventData_PlayerLeft> pEvent(new CEventData_PlayerLeft(pRequestLeaveData->GetUsername())); CEventManager::GetInstance()->QueueEvent(pEvent); } void CGameLogic::LoadedGameDelegate(shared_ptr<IEventData> _pEventData) { if (!m_bIsRemote) { m_iNumLoadedPlayers++; if (m_iNumLoadedPlayers >= m_iNumPlayers) { // Have all players loaded? // Start the game. shared_ptr<CEventData_RequestStartGame> pEvent(new CEventData_RequestStartGame(false)); CEventManager::GetInstance()->TriggerEvent(pEvent); } } } CSteeringBehaviours& CGameLogic::GetSteeringBehaviours() { return m_steeringBehaviours; } void CGameLogic::ClearActors() { while (!m_actorMap.empty()) { auto iter = m_actorMap.begin(); DestroyActor(iter->first); } } void CGameLogic::ClientJoinDelegate(shared_ptr<IEventData> _pEventData) { if (m_bIsRemote) { // Only servers actually add clients. return; } shared_ptr<CEventData_ClientJoin> pClientJoinData = static_pointer_cast<CEventData_ClientJoin>(_pEventData); // Get the remote address from the client join data. TAddress remoteAddress = pClientJoinData->GetRemoteAddress(); // Create a new event forwarder to forward events to this client. unique_ptr<CNetworkEventForwarder> pEventForwarder(new CNetworkEventForwarder(remoteAddress)); if (!pEventForwarder) { std::string strError = "Failed to create network event forwarder for address: "; strError += remoteAddress.m_strIPAddress + ":" + ToString(remoteAddress.m_usPort); strError += " username: \"" + pClientJoinData->GetUsername() + "\""; DEBUG_ERROR(strError); return; } // Add the events to forward to the client. pEventForwarder->AddEventForwarder<CEventData_MoveActor>(); pEventForwarder->AddEventForwarder<CEventData_RequestNewActor>(); pEventForwarder->AddEventForwarder<CEventData_RequestDestroyActor>(); pEventForwarder->AddEventForwarder<CEventData_RequestStartGame>(); pEventForwarder->AddEventForwarder<CEventData_PlayerReady>(); pEventForwarder->AddEventForwarder<CEventData_PlayerLeft>(); VAddNetworkEventsServerToClient(pEventForwarder.get()); unique_ptr<CNetworkView> pNetworkView(new CNetworkView(std::move(pEventForwarder), pClientJoinData->GetUsername())); if (pNetworkView) { AddGameView(std::move(pNetworkView)); m_iNumPlayers++; } } IPhysics* CGameLogic::GetGamePhysics() { return m_pPhysics.get(); } CActorFactory* CGameLogic::GetActorFactory() { return &m_actorFactory; } const CGameLogic::TActorMap& CGameLogic::GetActorMap() { return m_actorMap; } int CGameLogic::GetNumPlayers() const { return m_iNumPlayers; } int CGameLogic::GetMaxPlayers() const { return m_options.m_iMaxPlayers; } std::string CGameLogic::GetUsername() const { return m_options.m_strUsername; } CGameLogic::EGameState CGameLogic::GetGameState() const { return m_eState; }
28.952797
139
0.759616
[ "render" ]
bf903b8277077d2317731457dbf8bd1dd2f1cc4e
2,541
cc
C++
Codeforces/243 Division 1/D/D.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/243 Division 1/D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/243 Division 1/D/D.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <bits/stdc++.h> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb push_back #define mp make_pair #define foreach(it, v) for(auto it=(v).begin(); it != (v).end(); ++it) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #define tr(...) cout<<__FUNCTION__<<' '<<__LINE__<<" = ";trace(#__VA_ARGS__, __VA_ARGS__) using namespace std; typedef long long ll; typedef long double ld; typedef pair<int,int> pii; template<typename S, typename T> ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;} template<typename T> ostream& operator<<(ostream& out,vector<T> const& v){ int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;} template<typename T> void trace(const char* name, T&& arg1){cout<<name<<" : "<<arg1<<endl;} template<typename T, typename... Args> void trace(const char* names, T&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cout.write(names, comma-names)<<" : "<<arg1<<" | ";trace(comma+1,args...);} const ld PI = 3.1415926535897932384626433832795; const int N = 100100; const int M = 330; unordered_set<int> p[N]; vector<int> pts[N]; int main(){ for(int i = 0; i < N; i++){ p[i].reserve(1024); p[i].max_load_factor(0.25); } int n; sd(n); for(int i = 0; i < n; i++){ int x, y; sd2(x,y); p[x].insert(y); pts[x].pb(y); } for(int i = 0; i < N; i++){ sort(pts[i].begin(), pts[i].end()); } vector<int> heavy; int ans = 0; for(int i = 0; i < N; i++){ if(pts[i].size() <= M){ for(int x = 0; x < pts[i].size(); x++){ for(int y = x+1; y < pts[i].size(); y++){ int dis = pts[i][y] - pts[i][x]; if(i-dis >= 0 and pts[i-dis].size() > M and p[i-dis].count(pts[i][x]) and p[i-dis].count(pts[i][x]+dis)) ans++; if(i + dis < N and p[i+dis].count(pts[i][x]) and p[i+dis].count(pts[i][y])) ans++; } } } else{ heavy.pb(i); } } for(int i = 0; i < heavy.size(); i++){ int A = heavy[i]; for(int j = i+1; j < heavy.size(); j++){ int B = heavy[j]; int dis = B - A; assert(dis >= 0); for(int x = 0; x < pts[A].size(); x++){ B = pts[A][x]; if(B + dis >= N or A + dis >= N) continue; if(p[A].count(B+dis) and p[A+dis].count(B) and p[A+dis].count(B+dis)) ans++; } } } printf("%d\n", ans); return 0; }
23.971698
118
0.559229
[ "vector" ]
bf92e1629dab874226f954995b4881f85bf65435
5,221
cpp
C++
polygonVect.cpp
programmer-furkan/Shape-Fit-Mathematically
596b25d65557d901a8622db19f2954ce74d2689e
[ "MIT" ]
null
null
null
polygonVect.cpp
programmer-furkan/Shape-Fit-Mathematically
596b25d65557d901a8622db19f2954ce74d2689e
[ "MIT" ]
null
null
null
polygonVect.cpp
programmer-furkan/Shape-Fit-Mathematically
596b25d65557d901a8622db19f2954ce74d2689e
[ "MIT" ]
null
null
null
#include "polygonVect.h" #include <iostream> using namespace std; namespace PolygonVect{ PolygonVect::PolygonVect() throw(std::domain_error):Polygon(){ points.push_back(Polygon::Point2D(0,0)); }//No parameter PolygonVect::PolygonVect(const PolygonVect& copyPoly) throw(std::domain_error): Polygon(copyPoly){ for(int i = 0; i < getCapacity(); i++){ points.push_back(copyPoly.points[i]); } }//Copy constructor PolygonVect::PolygonVect(vector<Polygon::Point2D> &pointVec) throw(): Polygon(pointVec){ for(int i = 0; i < getCapacity(); i++) points.push_back(pointVec[i]); } PolygonVect::PolygonVect(Point2D& pointObj) throw(): Polygon(pointObj){ points.push_back(pointObj); }//From a two 2D point PolygonVect::PolygonVect(Rectangle& rect) throw(std::domain_error):Polygon(rect){ points.push_back(Polygon::Point2D(rect.getInitX(), rect.getInitY())); points.push_back(Polygon::Point2D(rect.getInitX(), rect.getInitY() + rect.getHeight())); points.push_back(Polygon::Point2D(rect.getInitX() + rect.getWidth(), rect.getInitY() + rect.getHeight())); points.push_back(Polygon::Point2D(rect.getInitX() + rect.getWidth(), rect.getInitY())); }//From Rectangle PolygonVect::PolygonVect(Triangle& triang) throw(std::domain_error):Polygon(triang){ points.push_back(Polygon::Point2D(triang.getP1(), triang.getP2())); points.push_back(Polygon::Point2D(triang.getP3(), triang.getP4())); points.push_back(Polygon::Point2D(triang.getP5(), triang.getP6())); }//From Triangle PolygonVect::PolygonVect(Circle& circ) throw(std::domain_error):Polygon(circ){ double angle = (2 * M_PI) / 100; double init_angle = 0; for(int i = 0; i < getCapacity(); i++){ points.push_back(Polygon::Point2D((circ.getRadius() * cos(init_angle)) + circ.getInitX(), (circ.getRadius() * sin(init_angle)) + circ.getInitY())); init_angle += angle; } }//From Circle PolygonVect& PolygonVect::operator =(const PolygonVect& assingPol) throw(std::domain_error){ setCapacity(assingPol.getCapacity()); for(int i=0; i < getCapacity(); i++){ points.push_back(assingPol[i]); } return *this; } PolygonVect::~PolygonVect() throw(){ points.clear(); } Polygon::Point2D& PolygonVect::operator [](int index) throw(std::out_of_range){ if(index >= getCapacity()){ throw std::out_of_range("Index out of range.\n"); } return points[index]; } const Polygon::Point2D& PolygonVect::operator [](int index) const throw(std::out_of_range){ if(index >= getCapacity()){ throw std::out_of_range("Index out of range.\n"); } return points[index]; }//[] overoading bool PolygonVect::operator ==(const PolygonVect& otherPoly) const throw(){ if(getCapacity() != otherPoly.getCapacity()){ return false; } for(int i = 0; i < getCapacity(); i++){ if((points[i].getX() != otherPoly[i].getX()) && (points[i].getY() != otherPoly[i].getY())){ return false; } } return true; } bool PolygonVect::operator !=(const PolygonVect& otherPoly) const throw(){ if(getCapacity() != otherPoly.getCapacity()){ return true; } for(int i = 0; i < getCapacity(); i++){ if((points[i].getX() == otherPoly[i].getX()) && (points[i].getY() == otherPoly[i].getY())){ return false; } } return true; } const PolygonVect PolygonVect::operator +(const PolygonVect& otherPoly) const throw(){ vector<Polygon::Point2D> newObj; if(getCapacity() > otherPoly.getCapacity()){ for(int i = 0; i < otherPoly.getCapacity(); i++){ Point2D obj(points[i].getX() + otherPoly[i].getX(), points[i].getY() + otherPoly[i].getY()); newObj.push_back(obj); } for(int j = otherPoly.getCapacity() + 1; j < getCapacity(); j++){ Point2D obj_2(points[j].getX() + otherPoly[j].getX(), points[j].getY() + otherPoly[j].getY()); newObj.push_back(obj_2); } return PolygonVect{newObj}; } else if(getCapacity() < otherPoly.getCapacity()){ for(int i = 0; i < getCapacity(); i++){ Polygon::Point2D obj(points[i].getX() + otherPoly[i].getX(), points[i].getY() + otherPoly[i].getY()); newObj.push_back(obj); } for(int j = getCapacity() + 1; j < otherPoly.getCapacity(); j++){ Polygon::Point2D obj_2(points[j].getX() + otherPoly[j].getX(), points[j].getY() + otherPoly[j].getY()); newObj.push_back(obj_2); } return PolygonVect{newObj}; } else{ for(int i = 0; i < getCapacity(); i++){ Polygon::Point2D obj(points[i].getX() + otherPoly[i].getX(), points[i].getY() + otherPoly[i].getY()); newObj.push_back(obj); } return PolygonVect{newObj}; } } void PolygonVect::print(ostream& outputStream) const throw(){//Overrided print function outputStream << "<polygon points=\""; for(int i = 0; i < getCapacity(); i++){ outputStream << points[i].getX() << "," << points[i].getY() << " "; } outputStream << "\" fill=\"red\" stroke=\"black\"/>\n"; } }
40.161538
154
0.615399
[ "vector" ]
bcca169b212938df796b6b0336f9f9329f224954
3,333
cpp
C++
mplugins/math_mplugin/src/math/flow/ConstStreamer.cpp
mico-corp/mico
45febf13da8c919eea77af9fa3b91afeb324f81b
[ "MIT" ]
3
2020-02-08T19:47:14.000Z
2022-03-14T14:13:29.000Z
mplugins/math_mplugin/src/math/flow/ConstStreamer.cpp
mico-corp/mico
45febf13da8c919eea77af9fa3b91afeb324f81b
[ "MIT" ]
10
2020-01-29T21:27:12.000Z
2022-03-22T17:03:02.000Z
mplugins/math_mplugin/src/math/flow/ConstStreamer.cpp
mico-corp/mico
45febf13da8c919eea77af9fa3b91afeb324f81b
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------------------------------------------------- // Cameras wrapper MICO plugin //--------------------------------------------------------------------------------------------------------------------- // Copyright 2020 Pablo Ramon Soria (a.k.a. Bardo91) pabramsor@gmail.com //--------------------------------------------------------------------------------------------------------------------- // 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 <mico/math/flow/ConstStreamer.h> #include <flow/Outpipe.h> #include <QSpinBox> #include <QGroupBox> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <sstream> namespace mico{ namespace math{ ConstStreamer::ConstStreamer(){ createPipe<float>("value"); } bool ConstStreamer::configure(std::vector<flow::ConfigParameterDef> _params) { if (auto value = getParamByName(_params, "value"); value) value_ = value.value().asDecimal(); if (auto rate = getParamByName(_params, "rate"); rate) rate_ = rate.value().asInteger(); return true; } std::vector<flow::ConfigParameterDef> ConstStreamer::parameters(){ return { {"value", flow::ConfigParameterDef::eParameterType::DECIMAL, 0.0f}, {"rate", flow::ConfigParameterDef::eParameterType::INTEGER, 1} }; } QWidget * ConstStreamer::customWidget(){ return nullptr; } void ConstStreamer::loopCallback() { auto t0 = std::chrono::steady_clock::now(); while(isRunningLoop()){ auto t1 = std::chrono::steady_clock::now(); float incT = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count(); if(incT / 1000 > 1/rate_){ t0 = t1; if(auto pipe = getPipe("value"); pipe->registrations() !=0 ){ pipe->flush(value_); } } } } } }
44.44
119
0.531353
[ "vector" ]
bccb43f0679ba43eab16cc4983af5861c3def369
2,317
cpp
C++
src/DX12/LLGI.CompilerDX12.cpp
jayrulez/LLGI
a0836e6db18e444d4534deb8eedb18263439fc4c
[ "Zlib" ]
29
2018-10-01T20:46:18.000Z
2022-03-11T17:00:42.000Z
src/DX12/LLGI.CompilerDX12.cpp
jayrulez/LLGI
a0836e6db18e444d4534deb8eedb18263439fc4c
[ "Zlib" ]
23
2019-07-05T15:29:37.000Z
2020-09-18T19:55:50.000Z
src/DX12/LLGI.CompilerDX12.cpp
jayrulez/LLGI
a0836e6db18e444d4534deb8eedb18263439fc4c
[ "Zlib" ]
10
2018-10-06T15:41:54.000Z
2020-11-01T13:58:11.000Z
#include "LLGI.CompilerDX12.h" #include <d3dcompiler.h> namespace LLGI { CompilerDX12::CompileShaderResultDX12 CompilerDX12::CompileShader(const char* text, const char* fileName, const char* target, const std::vector<D3D_SHADER_MACRO>& macro, const CompilerDX12Option& option) { ID3DBlob* shader = nullptr; ID3DBlob* error = nullptr; UINT flag = 0; if ((static_cast<int32_t>(option) & static_cast<int32_t>(CompilerDX12Option::ColumnMajor)) != 0) { flag |= D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR; } else { flag |= D3DCOMPILE_PACK_MATRIX_ROW_MAJOR; } #if !_DEBUG flag = flag | D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif HRESULT hr; hr = D3DCompile(text, strlen(text), fileName, macro.size() > 0 ? (D3D_SHADER_MACRO*)&macro[0] : NULL, NULL, "main", target, flag, 0, &shader, &error); CompileShaderResultDX12 result; if (FAILED(hr)) { if (hr == E_OUTOFMEMORY) { result.error += "Out of memory\n"; } else { result.error += "Unknown error\n"; } if (error != NULL) { result.error += (const char*)error->GetBufferPointer(); error->Release(); } return result; } result.shader = shader; return result; } CompilerDX12::CompilerDX12(const CompilerDX12Option& option) : option_(option) {} void CompilerDX12::Initialize() {} void CompilerDX12::Compile(CompilerResult& result, const char* code, ShaderStageType shaderStage) { char* vs_target = "vs_5_0"; char* ps_target = "ps_5_0"; char* cs_target = "cs_5_0"; char* target = nullptr; if (shaderStage == ShaderStageType::Vertex) { target = vs_target; } else if (shaderStage == ShaderStageType::Pixel) { target = ps_target; } else if (shaderStage == ShaderStageType::Compute) { target = cs_target; } std::vector<D3D_SHADER_MACRO> macro; auto compileResult = CompileShader(code, "dx12_code", target, macro, option_); result.Message = compileResult.error; if (compileResult.shader != nullptr) { auto size = compileResult.shader->GetBufferSize(); result.Binary.resize(1); result.Binary[0].resize(size); memcpy(result.Binary[0].data(), compileResult.shader->GetBufferPointer(), result.Binary[0].size()); SafeRelease(compileResult.shader); } } } // namespace LLGI
20.6875
101
0.670695
[ "vector" ]
bcce63a76867afa369b435521228c5c32a1c359d
6,571
cc
C++
mindspore/lite/src/runtime/kernel/arm/fp32/uniform_real_fp32.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
2
2021-07-08T13:10:42.000Z
2021-11-08T02:48:57.000Z
mindspore/lite/src/runtime/kernel/arm/fp32/uniform_real_fp32.cc
peixinhou/mindspore
fcb2ec2779b753e95c762cf292b23bd81d1f561b
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/arm/fp32/uniform_real_fp32.cc
peixinhou/mindspore
fcb2ec2779b753e95c762cf292b23bd81d1f561b
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * 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 "src/runtime/kernel/arm/fp32/uniform_real_fp32.h" #include <stdlib.h> #include <string.h> #include <vector> #include "src/kernel_registry.h" #include "include/errorcode.h" using mindspore::lite::KernelRegistrar; using mindspore::lite::RET_ERROR; using mindspore::lite::RET_OK; using mindspore::schema::PrimitiveType_UniformReal; namespace mindspore::kernel { class PhiloxRandom { public: explicit PhiloxRandom(uint64_t seed_lo, uint64_t seed_hi) { key_[0] = static_cast<uint32_t>(seed_lo); key_[1] = static_cast<uint32_t>(seed_lo >> 32); counter_[2] = static_cast<uint32_t>(seed_hi); counter_[3] = static_cast<uint32_t>(seed_hi >> 32); } ~PhiloxRandom() = default; // Skip the specified number of samples of 128-bits in the current stream. void Skip(uint64_t count) { const uint32_t count_lo = static_cast<uint32_t>(count); uint32_t count_hi = static_cast<uint32_t>(count >> 32); counter_[0] += count_lo; if (counter_[0] < count_lo) { ++count_hi; } counter_[1] += count_hi; if (counter_[1] < count_hi) { if (++counter_[2] == 0) { ++counter_[3]; } } } // Returns a group of four random numbers using the underlying Philox // algorithm. std::vector<uint32_t> operator()() { std::vector<uint32_t> counter = counter_; std::vector<uint32_t> key = key_; counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); RaiseKey(&key); counter = ComputeSingleRound(counter, key); SkipOne(); return counter; } private: // We use the same constants as recommended by the original paper. static constexpr uint32_t kPhiloxW32A = 0x9E3779B9; static constexpr uint32_t kPhiloxW32B = 0xBB67AE85; static constexpr uint32_t kPhiloxM4x32A = 0xD2511F53; static constexpr uint32_t kPhiloxM4x32B = 0xCD9E8D57; // Helper function to skip the next sample of 128-bits in the current stream. void SkipOne() { if (++counter_[0] == 0) { if (++counter_[1] == 0) { if (++counter_[2] == 0) { ++counter_[3]; } } } } static void MultiplyHighLow(uint32_t a, uint32_t b, uint32_t *result_low, uint32_t *result_high) { const uint64_t product = static_cast<uint64_t>(a) * b; *result_low = static_cast<uint32_t>(product); *result_high = static_cast<uint32_t>(product >> 32); } // Helper function for a single round of the underlying Philox algorithm. static std::vector<uint32_t> ComputeSingleRound(const std::vector<uint32_t> &counter, const std::vector<uint32_t> &key) { uint32_t lo0; uint32_t hi0; MultiplyHighLow(kPhiloxM4x32A, counter[0], &lo0, &hi0); uint32_t lo1; uint32_t hi1; MultiplyHighLow(kPhiloxM4x32B, counter[2], &lo1, &hi1); std::vector<uint32_t> result = {0, 0, 0, 0}; result[0] = hi1 ^ counter[1] ^ key[0]; result[1] = lo1; result[2] = hi0 ^ counter[3] ^ key[1]; result[3] = lo0; return result; } void RaiseKey(std::vector<uint32_t> *key) { (*key)[0] += kPhiloxW32A; (*key)[1] += kPhiloxW32B; } private: std::vector<uint32_t> counter_ = {0, 0, 0, 0}; std::vector<uint32_t> key_ = {0, 0}; }; float uint32ToFloat(uint32_t x) { const uint32_t man = x & 0x7fffffu; // 23 bit mantissa const uint32_t exp = static_cast<uint32_t>(127); const uint32_t val = (exp << 23) | man; // Assumes that endian-ness is same for float and uint32_t. float result; memcpy(&result, &val, sizeof(val)); return result - 1.0f; } void GetPhiloxRandomFloat(float *data, size_t length, int seed, int seed2) { PhiloxRandom philoxRandom(seed, seed2); if (length < 4) { auto randNum = philoxRandom.operator()(); for (size_t i = 0; i < length; i++) { data[i] = uint32ToFloat(randNum[i]); } } else { auto randNum = philoxRandom.operator()(); data[0] = uint32ToFloat(randNum[0]); data[1] = uint32ToFloat(randNum[1]); data[2] = uint32ToFloat(randNum[2]); data[3] = uint32ToFloat(randNum[3]); for (size_t i = 1; i < length / 4; i++) { philoxRandom.Skip(0); randNum = philoxRandom.operator()(); data[4 * i] = uint32ToFloat(randNum[0]); data[4 * i + 1] = uint32ToFloat(randNum[1]); data[4 * i + 2] = uint32ToFloat(randNum[2]); data[4 * i + 3] = uint32ToFloat(randNum[3]); } philoxRandom.Skip(0); randNum = philoxRandom.operator()(); for (size_t i = 0; i < length % 4; i++) { data[4 * (length / 4) + i] = uint32ToFloat(randNum[i]); } } } int UniformRealCPUKernel::Init() { return RET_OK; } int UniformRealCPUKernel::ReSize() { return RET_OK; } int UniformRealCPUKernel::Run() { auto output0 = reinterpret_cast<float *>(out_tensors_.at(0)->MutableData()); MS_ASSERT(output0); if (seed_ < 0 || seed2_ < 0) { MS_LOG(ERROR) << "seed_:" << seed_ << " and seed2_:" << seed2_ << " must be greater than 0!"; return RET_ERROR; } if (seed_ > 0 && seed2_ > 0) { GetPhiloxRandomFloat(output0, out_tensors_.at(0)->ElementsNum(), seed_, seed2_); return RET_OK; } std::srand(seed_ || seed2_); for (int i = 0; i < out_tensors_.at(0)->ElementsNum(); ++i) { output0[i] = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX); } return RET_OK; } REG_KERNEL(kCPU, kNumberTypeInt32, PrimitiveType_UniformReal, LiteKernelCreator<UniformRealCPUKernel>) } // namespace mindspore::kernel
31.898058
102
0.65713
[ "vector" ]
bcced442b300ae61175b6b8bbc36973f0dec4b3a
4,462
hxx
C++
inetsrv/query/web/ixsso/ixsutil.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/query/web/ixsso/ixsutil.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/query/web/ixsso/ixsutil.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Copyright (C) 1996-1997, Microsoft Corporation. // // File: ixsutil.hxx // // Contents: Query SSO class // // History: 29 Oct 1996 Alanw Created // //---------------------------------------------------------------------------- #pragma once //----------------------------------------------------------------------------- // Include Files //----------------------------------------------------------------------------- // Query object interface declarations #include "ixssoifc.h" #include "ixserror.hxx" //----------------------------------------------------------------------------- // CixssoUtil Declaration //----------------------------------------------------------------------------- class CixssoUtil : public IixssoUtil, public ISupportErrorInfo { friend class CIxssoUtilCF; public: // IUnknown methods STDMETHOD(QueryInterface)(THIS_ REFIID riid, LPVOID * ppvObj); STDMETHOD_(ULONG, AddRef)(THIS); STDMETHOD_(ULONG, Release)(THIS); // IDispatch methods STDMETHOD(GetTypeInfoCount)(THIS_ UINT * pctinfo); STDMETHOD(GetTypeInfo)( THIS_ UINT itinfo, LCID lcid, ITypeInfo * * pptinfo); STDMETHOD(GetIDsOfNames)( THIS_ REFIID riid, OLECHAR * * rgszNames, UINT cNames, LCID lcid, DISPID * rgdispid); STDMETHOD(Invoke)( THIS_ DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pdispparams, VARIANT * pvarResult, EXCEPINFO * pexcepinfo, UINT * puArgErr); // ISupportErrorInfo method STDMETHOD(InterfaceSupportsErrorInfo)( THIS_ REFIID riid); // // IixssoUtil methods // HRESULT STDMETHODCALLTYPE LocaleIDToISO( /* [in] */ LONG lcid, /* [retval][out] */ BSTR *val); HRESULT STDMETHODCALLTYPE ISOToLocaleID( /* [in] */ BSTR bstrLocale, /* [retval][out] */ LONG *pLcid); HRESULT STDMETHODCALLTYPE AddScopeToQuery( /* [in] */ IDispatch * pDisp, /* [in] */ BSTR pwszScope, /* [in] */ BSTR pwszDepth); HRESULT STDMETHODCALLTYPE TruncateToWhitespace( /* [in] */ BSTR bstrIn, /* [in] */ LONG maxLen, /* [retval][out] */ BSTR * pbstrOut); HRESULT STDMETHODCALLTYPE GetArrayElement( /* [in] */ VARIANT * pVariantArray, /* [in] */ LONG iElement, /* [out,retval] */ VARIANT * pOutputVariant); HRESULT STDMETHODCALLTYPE HTMLEncode( /* [in] */ BSTR bstrIn, /* [in] */ LONG codepage, /* [retval][out] */ BSTR * pbstrOut); HRESULT STDMETHODCALLTYPE URLEncode( /* [in] */ BSTR bstrIn, /* [in] */ LONG codepage, /* [retval][out] */ BSTR * pbstrOut); #if 0 // NOTE: not needed // // ASP standard methods // HRESULT STDMETHODCALLTYPE OnStartPage( IUnknown * pUnk ); HRESULT STDMETHODCALLTYPE OnEndPage( void ); #endif // 0 NOTE: not needed private: CixssoUtil( ITypeLib * pitlb ); ~CixssoUtil(); // Local methods SCODE SetError( SCODE sc, const WCHAR * loc = 0, unsigned eErrClass = 0 ) { _err.SetError( sc, 0, 0, loc, eErrClass, _lcid ); return sc; } LCID GetLCID() const { return _lcid; } // Property get/put helpers SCODE CopyWstrToBstr( BSTR * pbstr, WCHAR const * pwstr ); ULONG _cRef; CixssoError _err; LCID _lcid; // Locale ID used for this query ITypeInfo * _ptinfo; // Type info from type lib };
30.986111
80
0.420215
[ "object" ]
bcd57acad2d4cd03fdd221a360cec9671045522e
4,702
cpp
C++
src/bindings.cpp
statquant/clustermq
ee71d865f4776ec1b0e76021820fdc04f273169f
[ "Apache-2.0" ]
128
2016-07-01T18:17:26.000Z
2022-03-28T03:01:55.000Z
src/bindings.cpp
statquant/clustermq
ee71d865f4776ec1b0e76021820fdc04f273169f
[ "Apache-2.0" ]
255
2016-07-02T15:31:32.000Z
2022-02-24T11:25:07.000Z
src/bindings.cpp
statquant/clustermq
ee71d865f4776ec1b0e76021820fdc04f273169f
[ "Apache-2.0" ]
26
2017-04-03T11:01:35.000Z
2021-11-10T14:18:52.000Z
#include <Rcpp.h> #include <chrono> #include <string> #include "zmq.hpp" typedef std::chrono::high_resolution_clock Time; typedef std::chrono::milliseconds ms; Rcpp::Function R_serialize("serialize"); Rcpp::Function R_unserialize("unserialize"); int str2socket_(std::string str) { if (str == "ZMQ_REP") { return ZMQ_REP; } else if (str == "ZMQ_REQ") { return ZMQ_REQ; } else if (str == "ZMQ_XREP") { return ZMQ_XREP; } else if (str == "ZMQ_XREQ") { return ZMQ_XREQ; } else { Rcpp::exception(("Invalid socket type: " + str).c_str()); } return -1; } /* Check for interrupt without long jumping */ void check_interrupt_fn(void *dummy) { R_CheckUserInterrupt(); } int pending_interrupt() { return !(R_ToplevelExec(check_interrupt_fn, NULL)); } // [[Rcpp::export]] SEXP init_context(int threads=1) { auto context_ = new zmq::context_t(threads); Rcpp::XPtr<zmq::context_t> context(context_, true); return context; } // [[Rcpp::export]] SEXP init_socket(SEXP context, std::string socket_type) { Rcpp::XPtr<zmq::context_t> context_(context); auto socket_type_ = str2socket_(socket_type); auto socket_ = new zmq::socket_t(*context_, socket_type_); Rcpp::XPtr<zmq::socket_t> socket(socket_, true); return socket; } // [[Rcpp::export]] void bind_socket(SEXP socket, std::string address) { Rcpp::XPtr<zmq::socket_t> socket_(socket); socket_->bind(address); } // [[Rcpp::export]] void connect_socket(SEXP socket, std::string address) { Rcpp::XPtr<zmq::socket_t> socket_(socket); socket_->connect(address); } // [[Rcpp::export]] void disconnect_socket(SEXP socket, std::string address) { Rcpp::XPtr<zmq::socket_t> socket_(socket); socket_->disconnect(address); } // [[Rcpp::export]] SEXP poll_socket(SEXP sockets, int timeout=-1) { auto sockets_ = Rcpp::as<Rcpp::List>(sockets); auto nsock = sockets_.length(); auto pitems = std::vector<zmq::pollitem_t>(nsock); for (int i = 0; i < nsock; i++) { pitems[i].socket = *Rcpp::as<Rcpp::XPtr<zmq::socket_t>>(sockets_[i]); pitems[i].events = ZMQ_POLLIN; // | ZMQ_POLLOUT; ssh_proxy XREP/XREQ has 2200 } int rc = -1; auto start = Time::now(); auto time_ms = std::chrono::milliseconds(timeout); do { try { rc = zmq::poll(pitems, time_ms); } catch(zmq::error_t &e) { if (errno != EINTR || pending_interrupt()) throw e; if (timeout != -1) { time_ms -= std::chrono::duration_cast<ms>(Time::now() - start); if (time_ms.count() <= 0) break; } } } while(rc < 0); auto result = Rcpp::IntegerVector(nsock); for (int i = 0; i < nsock; i++) result[i] = pitems[i].revents; return result; } zmq::message_t rcv_msg(SEXP socket, bool dont_wait=false) { Rcpp::XPtr<zmq::socket_t> socket_(socket); auto flags = zmq::recv_flags::none; if (dont_wait) flags = flags | zmq::recv_flags::dontwait; zmq::message_t message; socket_->recv(message, flags); return message; } // [[Rcpp::export]] SEXP receive_socket(SEXP socket, bool dont_wait=false, bool unserialize=true) { auto message = rcv_msg(socket, dont_wait); // if (! socket_->recv(message, flags)) // return {}; // EAGAIN: no message in non-blocking mode -> empty result SEXP ans = Rf_allocVector(RAWSXP, message.size()); memcpy(RAW(ans), message.data(), message.size()); if (unserialize) return R_unserialize(ans); else return ans; } // [[Rcpp::export]] Rcpp::List receive_multipart(SEXP socket, bool dont_wait=false, bool unserialize=true) { zmq::message_t message; Rcpp::List result; do { message = rcv_msg(socket, dont_wait); SEXP ans = Rf_allocVector(RAWSXP, message.size()); memcpy(RAW(ans), message.data(), message.size()); if (unserialize) result.push_back(R_unserialize(ans)); else result.push_back(ans); } while (message.more()); return result; } // [[Rcpp::export]] void send_socket(SEXP socket, SEXP data, bool dont_wait=false, bool send_more=false) { Rcpp::XPtr<zmq::socket_t> socket_(socket); auto flags = zmq::send_flags::none; if (dont_wait) flags = flags | zmq::send_flags::dontwait; if (send_more) flags = flags | zmq::send_flags::sndmore; if (TYPEOF(data) != RAWSXP) data = R_serialize(data, R_NilValue); zmq::message_t message(Rf_xlength(data)); memcpy(message.data(), RAW(data), Rf_xlength(data)); socket_->send(message, flags); }
29.024691
88
0.623564
[ "vector" ]
bcd587393819737d0d8910e0b7dbe9b733f2f025
2,349
hpp
C++
include/percemon/monitoring.hpp
atharvapotdar/PerceMon
633212190dae1ce502b96410af83c8b796b678e6
[ "BSD-3-Clause" ]
1
2021-11-08T08:11:21.000Z
2021-11-08T08:11:21.000Z
include/percemon/monitoring.hpp
atharvapotdar/PerceMon
633212190dae1ce502b96410af83c8b796b678e6
[ "BSD-3-Clause" ]
null
null
null
include/percemon/monitoring.hpp
atharvapotdar/PerceMon
633212190dae1ce502b96410af83c8b796b678e6
[ "BSD-3-Clause" ]
2
2021-11-22T22:09:35.000Z
2022-02-11T13:27:31.000Z
#pragma once #ifndef __PERCEMON_MONITORING_HPP__ #define __PERCEMON_MONITORING_HPP__ #include "percemon/ast.hpp" #include "percemon/datastream.hpp" // TODO: Consider unordered_map if memory and hashing isn't an issue. #include <map> // TODO: Consider performance/space efficiency of deque vs vector. #include <deque> #include <optional> namespace percemon::monitoring { /** * Returns if the formula is purely past-time. Only place where this can be true is in * the TimeBound and FrameBound constraints. * * @todo This can be enforced in the TimeBound and FrameBound constructors. */ // bool is_past_time(const percemon::ast::Expr& expr); /** * Get the horizon for a formula in number of frames. This function will throw an * exception if there are TimeBound constraints in the formula. */ std::optional<size_t> get_horizon(const percemon::ast::Expr& expr); /** * Get the horizon for a formula in number of frames. This uses the frames per second of * the stream to convert TimeBound constraints to FrameBound constraints. */ std::optional<size_t> get_horizon(const percemon::ast::Expr& expr, double fps); /** * Object representing the online monitor. */ struct OnlineMonitor { public: OnlineMonitor() = delete; OnlineMonitor( ast::Expr phi_, const double fps_, double x_boundary, double y_boundary); /** * Add a new frame to the monitor buffer */ void add_frame(const datastream::Frame& frame); void add_frame(datastream::Frame&& frame); // Efficient move semantics /** * Compute the robustness of the currently buffered frames. */ double eval(); [[nodiscard]] size_t get_max_horizon() const { return max_horizon; } [[nodiscard]] size_t get_fps() const { return fps; }; const ast::Expr& get_phi() { return phi; } private: /** * The formula being monitored */ const ast::Expr phi; /** * Frames per second for the datastream */ const double fps; /** * A buffer containing the history of Frames required to compute robustness of phi * efficiently. */ std::deque<datastream::Frame> buffer; /** * Maximum width of buffer. */ size_t max_horizon; /** * Boundary for UNIVERSE */ double universe_x, universe_y; }; } // namespace percemon::monitoring #endif /* end of include guard: __PERCEMON_MONITORING_HPP__ */
24.46875
88
0.704981
[ "object", "vector" ]
bce06a4e0a0334e34cf544792e893682917410cb
24,957
cpp
C++
src/sgd/ttc_sgd_problem_models.cpp
AlexanderDavid/NHTTC
5cb9c9a635e414c754bff47869dd5154f0a91377
[ "MIT" ]
null
null
null
src/sgd/ttc_sgd_problem_models.cpp
AlexanderDavid/NHTTC
5cb9c9a635e414c754bff47869dd5154f0a91377
[ "MIT" ]
null
null
null
src/sgd/ttc_sgd_problem_models.cpp
AlexanderDavid/NHTTC
5cb9c9a635e414c754bff47869dd5154f0a91377
[ "MIT" ]
1
2020-10-18T19:51:25.000Z
2020-10-18T19:51:25.000Z
/* Copyright 2020 University of Minnesota and Clemson University 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. */ /* This file contains the implementations of the dynamics models for each agent type: Velocity, Acceleration, Differential Drive, Smooth Differential Drive, Simple Car, Smooth Car In addition, any dynamics model specific features are handled here (such as special constraint projections or collision center computations). */ #include <sgd/ttc_sgd_problem_models.h> #include <iostream> // -------------------------------------------- // ******************* V ********************** // -------------------------------------------- void VTTCSGDProblem::ContDynamics(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, Eigen::VectorXf* x_dot, Eigen::MatrixXf* dxdot_du, Eigen::MatrixXf* dxdot_dx) { if (x_dot != nullptr) { (*x_dot) = Eigen::VectorXf::Zero(2); (*x_dot)[0] = u[0]; (*x_dot)[1] = u[1]; } if (dxdot_du != nullptr) { (*dxdot_du) = Eigen::MatrixXf::Identity(2,2); } if (dxdot_dx != nullptr) { (*dxdot_dx) = Eigen::MatrixXf::Zero(2,2); } } void VTTCSGDProblem::GetDynamicsDeriv(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, const float dt, Eigen::MatrixXf* dxtpdt_du, Eigen::MatrixXf* dxtpdt_dx) { if (dxtpdt_dx != nullptr) { (*dxtpdt_dx) = Eigen::Matrix2f::Identity(); } if (dxtpdt_du != nullptr) { (*dxtpdt_du) = dt * Eigen::Matrix2f::Identity(); } } TTCObstacle* VTTCSGDProblem::CreateObstacle() { TTCObstacle* o = new VTTCObstacle(); FillObstacle(o); return o; } // -------------------------------------------- // ******************* A ********************** // -------------------------------------------- void ATTCSGDProblem::ContDynamics(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, Eigen::VectorXf* x_dot, Eigen::MatrixXf* dxdot_du, Eigen::MatrixXf* dxdot_dx) { float scale_a = 1.0f; // Leaky velocity constraint if (x.tail<2>().norm() > params.vel_limit && x.tail<2>().dot(u) > 0.0f) { scale_a = 1e-2f; } if (x_dot != nullptr) { (*x_dot) = Eigen::VectorXf::Zero(4); x_dot->head<2>() = x.tail<2>(); x_dot->tail<2>() = scale_a * u; } if (dxdot_du != nullptr) { (*dxdot_du) = Eigen::MatrixXf::Zero(4,2); (*dxdot_du)(2,0) = scale_a; (*dxdot_du)(3,1) = scale_a; } if (dxdot_dx != nullptr) { (*dxdot_dx) = Eigen::MatrixXf::Zero(4,4); (*dxdot_dx)(0,2) = 1.0f; (*dxdot_dx)(1,3) = 1.0f; } } void ATTCSGDProblem::GetDynamicsDeriv(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, const float dt, Eigen::MatrixXf* dxtpdt_du, Eigen::MatrixXf* dxtpdt_dx) { if (dxtpdt_dx != nullptr) { (*dxtpdt_dx) = Eigen::MatrixXf::Identity(4, 4); (*dxtpdt_dx)(0, 2) = dt; (*dxtpdt_dx)(1, 3) = dt; } if (dxtpdt_du != nullptr) { // leaky constraints on velocity float scale_a = 1.0f; if (x.tail<2>().norm() > params.vel_limit && x.tail<2>().dot(u) > 0.0f) { scale_a = 1e-2f; } (*dxtpdt_du) = Eigen::MatrixXf::Zero(4, 2); (*dxtpdt_du)(0, 0) = 0.5f * dt * dt * scale_a; (*dxtpdt_du)(1, 1) = 0.5f * dt * dt * scale_a; (*dxtpdt_du)(2, 0) = dt * scale_a; (*dxtpdt_du)(3, 1) = dt * scale_a; } } void ATTCSGDProblem::AdditionalCosts(const Eigen::VectorXf &u, float* cost, Eigen::VectorXf* dc_du) { // Velocity Constraint Cost: Eigen::VectorXf x_t; Eigen::MatrixXf dxt_du; if (dc_du != nullptr) { DynamicsLong(u, params.x_0, 0.0f, 1.0f, &x_t, &dxt_du, nullptr); } else { DynamicsLong(u, params.x_0, 0.0f, 1.0f, &x_t); } if (x_t.tail<2>().norm() > params.vel_limit) { if (cost != nullptr) { (*cost) += params.k_v_constr * (x_t.tail<2>().squaredNorm() - params.vel_limit * params.vel_limit); } if (dc_du != nullptr) { (*dc_du) += 2.0 * params.k_v_constr * x_t.tail<2>().transpose() * dxt_du.bottomRows<2>(); } } } void ATTCSGDProblem::ProjConstr(Eigen::VectorXf& u) { // Trim u to control constraints: TTCSGDProblem::ProjConstr(u); // Trim u to state constraints: Eigen::Vector2f v_new = params.x_0.tail<2>() + params.dt_step * u; if (v_new.norm() > params.vel_limit) { v_new = params.vel_limit / v_new.norm() * v_new; u = (v_new - params.x_0.tail<2>()) / params.dt_step; } } TTCObstacle* ATTCSGDProblem::CreateObstacle() { TTCObstacle* o = new ATTCObstacle(); FillObstacle(o); return o; } // -------------------------------------------- // ******************* DD ********************* // -------------------------------------------- void DDTTCSGDProblem::ContDynamics(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, Eigen::VectorXf* x_dot, Eigen::MatrixXf* dxdot_du, Eigen::MatrixXf* dxdot_dx) { if (x_dot != nullptr) { (*x_dot) = Eigen::VectorXf::Zero(3); (*x_dot)[0] = u[0] * std::cos(x[2]); (*x_dot)[1] = u[0] * std::sin(x[2]); (*x_dot)[2] = u[1]; } if (dxdot_du != nullptr) { (*dxdot_du) = Eigen::MatrixXf::Zero(3,2); (*dxdot_du)(0,0) = std::cos(x[2]); (*dxdot_du)(1,0) = std::sin(x[2]); (*dxdot_du)(2,1) = 1.0f; } if (dxdot_dx != nullptr) { (*dxdot_dx) = Eigen::MatrixXf::Zero(3,3); (*dxdot_dx)(0,2) = -u[0] * std::sin(x[2]); (*dxdot_dx)(1,2) = u[0] * std::cos(x[2]); } } void DDTTCSGDProblem::GetDynamicsDeriv(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, const float dt, Eigen::MatrixXf* dxtpdt_du, Eigen::MatrixXf* dxtpdt_dx) { float th_new = x[2] + dt * u[1]; if (dxtpdt_dx != nullptr) { (*dxtpdt_dx) = Eigen::Matrix3f::Identity(); (*dxtpdt_dx)(0, 2) = -0.5f * dt * u[0] * (std::sin(x[2]) + std::sin(th_new)); (*dxtpdt_dx)(1, 2) = 0.5f * dt * u[0] * (std::cos(x[2]) + std::cos(th_new)); } if (dxtpdt_du != nullptr) { (*dxtpdt_du) = Eigen::MatrixXf::Zero(3, 2); (*dxtpdt_du)(0, 0) = 0.5f * dt * (std::cos(x[2]) + std::cos(th_new)); (*dxtpdt_du)(1, 0) = 0.5f * dt * (std::sin(x[2]) + std::sin(th_new)); (*dxtpdt_du)(0, 1) = -0.5f * dt * dt * u[0] * std::sin(th_new); (*dxtpdt_du)(1, 1) = 0.5f * dt * dt * u[0] * std::cos(th_new); (*dxtpdt_du)(2, 1) = dt; } } TTCObstacle* DDTTCSGDProblem::CreateObstacle() { TTCObstacle* o = new DDTTCObstacle(); FillObstacle(o); return o; } // -------------------------------------------- // ****************** ADD ********************* // -------------------------------------------- void ADDTTCSGDProblem::ContDynamics(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, Eigen::VectorXf* x_dot, Eigen::MatrixXf* dxdot_du, Eigen::MatrixXf* dxdot_dx) { // leaky constraints on velocities float scale_v = ((x[3] > params.vel_limit && u[0] > 0.0f) || (x[3] < -params.vel_limit && u[0] < 0.0f)) ? 1e-2f : 1.0f; float scale_w = ((x[4] > params.rot_vel_limit && u[1] > 0.0f) || (x[4] < -params.rot_vel_limit && u[1] < 0.0f)) ? 1e-2f : 1.0f; if (x_dot != nullptr) { (*x_dot) = Eigen::VectorXf::Zero(5); (*x_dot)[0] = x[3] * std::cos(x[2]); (*x_dot)[1] = x[3] * std::sin(x[2]); (*x_dot)[2] = x[4]; (*x_dot)[3] = scale_v * u[0]; (*x_dot)[4] = scale_w * u[1]; } if (dxdot_du != nullptr) { (*dxdot_du) = Eigen::MatrixXf::Zero(5,2); (*dxdot_du)(3,0) = scale_v; (*dxdot_du)(4,1) = scale_w; } if (dxdot_dx != nullptr) { (*dxdot_dx) = Eigen::MatrixXf::Zero(5,5); (*dxdot_dx)(0,2) = -x[3] * std::sin(x[2]); (*dxdot_dx)(0,3) = std::cos(x[2]); (*dxdot_dx)(1,2) = x[3] * std::cos(x[2]); (*dxdot_dx)(1,3) = std::sin(x[2]); (*dxdot_dx)(2,4) = 1.0f; } } void ADDTTCSGDProblem::GetDynamicsDeriv(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, const float dt, Eigen::MatrixXf* dxtpdt_du, Eigen::MatrixXf* dxtpdt_dx) { // leaky constraints on velocities float scale_v = ((x[3] > params.vel_limit && u[0] > 0.0f) || (x[3] < -params.vel_limit && u[0] < 0.0f)) ? 1e-2f : 1.0f; float scale_w = ((x[4] > params.rot_vel_limit && u[1] > 0.0f) || (x[4] < -params.rot_vel_limit && u[1] < 0.0f)) ? 1e-2f : 1.0f; float v_new = x[3] + dt * scale_v * u[0]; float w_new = x[4] + dt * scale_w * u[1]; float th_new = x[2] + 0.5f * dt * (x[4] + w_new); if (dxtpdt_dx != nullptr) { (*dxtpdt_dx) = Eigen::MatrixXf::Identity(5, 5); (*dxtpdt_dx)(0, 2) = -0.5f * dt * (x[3] * std::sin(x[2]) + v_new * std::sin(th_new)); (*dxtpdt_dx)(1, 2) = 0.5f * dt * (x[3] * std::cos(x[2]) + v_new * std::cos(th_new)); (*dxtpdt_dx)(0, 3) = 0.5f * dt * (std::cos(x[2]) + std::cos(th_new)); (*dxtpdt_dx)(1, 3) = 0.5f * dt * (std::sin(x[2]) + std::sin(th_new)); (*dxtpdt_dx)(2, 4) = dt; (*dxtpdt_dx)(0, 4) = -0.5f * dt * v_new * std::sin(th_new) * (*dxtpdt_dx)(2, 4); (*dxtpdt_dx)(1, 4) = 0.5f * dt * v_new * std::cos(th_new) * (*dxtpdt_dx)(2, 4); } if (dxtpdt_du != nullptr) { (*dxtpdt_du) = Eigen::MatrixXf::Zero(5, 2); (*dxtpdt_du)(3, 0) = dt * scale_v; (*dxtpdt_du)(4, 1) = dt * scale_w; (*dxtpdt_du)(2, 1) = 0.5f * dt * (*dxtpdt_du)(4, 1); (*dxtpdt_du)(0, 0) = 0.5f * dt * std::cos(th_new) * (*dxtpdt_du)(3, 0); (*dxtpdt_du)(1, 0) = 0.5f * dt * std::sin(th_new) * (*dxtpdt_du)(3, 0); (*dxtpdt_du)(0, 1) = -0.5f * dt * v_new * std::sin(th_new) * (*dxtpdt_du)(2, 1); (*dxtpdt_du)(1, 1) = 0.5f * dt * v_new * std::cos(th_new) * (*dxtpdt_du)(2, 1); } } void ADDTTCSGDProblem::AdditionalCosts(const Eigen::VectorXf &u, float* cost, Eigen::VectorXf* dc_du) { // Velocity Constraint Cost: Eigen::VectorXf x_t; Eigen::MatrixXf dxt_du; if (dc_du != nullptr) { DynamicsLong(u, params.x_0, 0.0f, 1.0f, &x_t, &dxt_du, nullptr); } else { DynamicsLong(u, params.x_0, 0.0f, 1.0f, &x_t); } if (std::abs(x_t[3]) > params.vel_limit) { float err; if (x_t[3] > params.vel_limit) { err = x_t[3] - params.vel_limit; } else { err = x_t[3] + params.vel_limit; // x_t[3] is negative } if (cost != nullptr) { (*cost) += params.k_v_constr * err * err; } if (dc_du != nullptr) { (*dc_du) += 2.0 * params.k_v_constr * err * dxt_du.row(3); } } } void ADDTTCSGDProblem::ProjConstr(Eigen::VectorXf& u) { // Trim u to control constraints TTCSGDProblem::ProjConstr(u); // Trim u to state constraints float v_new = params.x_0[3] + params.dt_step * u[0]; if (v_new > params.vel_limit) { u[0] = (params.vel_limit - params.x_0[3]) / params.dt_step; } float w_new = params.x_0[4] + params.dt_step * u[1]; if (w_new > params.rot_vel_limit) { u[1] = (params.rot_vel_limit - params.x_0[4]) / params.dt_step; } } TTCObstacle* ADDTTCSGDProblem::CreateObstacle() { TTCObstacle* o = new ADDTTCObstacle(); FillObstacle(o); return o; } // -------------------------------------------- // ****************** CAR ********************* // -------------------------------------------- void CARTTCSGDProblem::ContDynamics(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, Eigen::VectorXf* x_dot, Eigen::MatrixXf* dxdot_du, Eigen::MatrixXf* dxdot_dx) { float len_scale = 2.0f / std::sqrt(5.0f); float L = 2.0f * len_scale * params.radius; if (x_dot != nullptr) { (*x_dot) = Eigen::VectorXf::Zero(3); (*x_dot)[0] = u[0] * std::cos(x[2]); (*x_dot)[1] = u[0] * std::sin(x[2]); (*x_dot)[2] = u[0] * std::tan(u[1]) / L; } if (dxdot_du != nullptr) { (*dxdot_du) = Eigen::MatrixXf::Zero(3,2); (*dxdot_du)(0,0) = std::cos(x[2]); (*dxdot_du)(1,0) = std::sin(x[2]); (*dxdot_du)(2,0) = std::tan(u[1]) / L; (*dxdot_du)(2,1) = u[0] / (std::cos(u[1]) * std::cos(u[1]) * L); } if (dxdot_dx != nullptr) { (*dxdot_dx) = Eigen::MatrixXf::Zero(3,3); (*dxdot_dx)(0,2) = -u[0] * std::sin(x[2]); (*dxdot_dx)(1,2) = u[0] * std::cos(x[2]); } } void CARTTCSGDProblem::GetDynamicsDeriv(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, const float dt, Eigen::MatrixXf* dxtpdt_du, Eigen::MatrixXf* dxtpdt_dx) { float len_scale = 2.0f / std::sqrt(5.0f); float L = 2.0f * len_scale * params.radius; float th_new = x[2] + dt * u[0] / L * std::tan(u[1]); if (dxtpdt_dx != nullptr) { (*dxtpdt_dx) = Eigen::MatrixXf::Identity(3, 3); (*dxtpdt_dx)(0, 2) = -0.5f * dt * u[0] * (std::sin(x[2]) + std::sin(th_new)); (*dxtpdt_dx)(1, 2) = 0.5f * dt * u[0] * (std::cos(x[2]) + std::cos(th_new)); } if (dxtpdt_du != nullptr) { (*dxtpdt_du) = Eigen::MatrixXf::Zero(3, 2); (*dxtpdt_du)(2, 0) = dt * std::tan(u[1]) / L; (*dxtpdt_du)(2, 1) = u[0] * dt / (L * std::cos(u[1]) * std::cos(u[1])); (*dxtpdt_du)(0, 0) = 0.5f * dt * (std::cos(x[2]) + std::cos(th_new) - u[0] * std::sin(th_new) * (*dxtpdt_du)(2, 0)); (*dxtpdt_du)(1, 0) = 0.5f * dt * (std::sin(x[2]) + std::sin(th_new) + u[0] * std::cos(th_new) * (*dxtpdt_du)(2, 0)); (*dxtpdt_du)(0, 1) = -0.5f * dt * u[0] * std::sin(th_new) * (*dxtpdt_du)(2, 1); (*dxtpdt_du)(1, 1) = 0.5f * dt * u[0] * std::cos(th_new) * (*dxtpdt_du)(2, 1); } } Eigen::Vector2f CARTTCSGDProblem::GetCollisionCenter(const Eigen::VectorXf &x, Eigen::MatrixXf* dc_dx) { float len_scale = 2.0f / std::sqrt(5.0f); if (dc_dx != nullptr) { (*dc_dx) = Eigen::MatrixXf::Identity(2,x.size()); (*dc_dx)(0,2) = -len_scale * params.radius * std::sin(x[2]); (*dc_dx)(1,2) = len_scale * params.radius * std::cos(x[2]); } return x.head<2>() + len_scale * params.radius * Eigen::Vector2f(std::cos(x[2]), std::sin(x[2])); } TTCObstacle* CARTTCSGDProblem::CreateObstacle() { TTCObstacle* o = new CARTTCObstacle(); FillObstacle(o); return o; } // -------------------------------------------- // ****************** A Car ******************* // -------------------------------------------- void ACARTTCSGDProblem::ContDynamics(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, Eigen::VectorXf* x_dot, Eigen::MatrixXf* dxdot_du, Eigen::MatrixXf* dxdot_dx) { float len_scale = 2.0f / std::sqrt(5.0f); float L = 2.0f * len_scale * params.radius; // leaky constraints on velocities float scale_v = ((x[3] > params.vel_limit && u[0] > 0.0f) || (x[3] < -params.vel_limit && u[0] < 0.0f)) ? 1e-2f : 1.0f; float scale_phi = ((x[4] > params.steer_limit && u[1] > 0.0f) || (x[4] < -params.steer_limit && u[1] < 0.0f)) ? 1e-2f : 1.0f; if (x_dot != nullptr) { (*x_dot) = Eigen::VectorXf::Zero(5); (*x_dot)[0] = x[3] * std::cos(x[2]); (*x_dot)[1] = x[3] * std::sin(x[2]); (*x_dot)[2] = x[3] * std::tan(x[4]) / L; (*x_dot)[3] = scale_v * u[0]; (*x_dot)[4] = scale_phi * u[1]; } if (dxdot_du != nullptr) { (*dxdot_du) = Eigen::MatrixXf::Zero(5,2); (*dxdot_du)(3,0) = scale_v; (*dxdot_du)(4,1) = scale_phi; } if (dxdot_dx != nullptr) { (*dxdot_dx) = Eigen::MatrixXf::Zero(5,5); (*dxdot_dx)(0,2) = -x[3] * std::sin(x[2]); (*dxdot_dx)(0,3) = std::cos(x[2]); (*dxdot_dx)(1,2) = x[3] * std::cos(x[2]); (*dxdot_dx)(1,3) = std::sin(x[2]); (*dxdot_dx)(2,3) = std::tan(x[4]) / L; (*dxdot_dx)(2,4) = x[3] / (std::cos(x[4]) * std::cos(x[4]) * L); } } void ACARTTCSGDProblem::GetDynamicsDeriv(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, const float dt, Eigen::MatrixXf* dxtpdt_du, Eigen::MatrixXf* dxtpdt_dx) { float len_scale = 2.0f / std::sqrt(5.0f); float L = 2.0f * len_scale * params.radius; // leaky constraints on velocities float scale_v = ((x[3] > params.vel_limit && u[0] > 0.0f) || (x[3] < -params.vel_limit && u[0] < 0.0f)) ? 1e-2f : 1.0f; float scale_phi = ((x[4] > params.steer_limit && u[1] > 0.0f) || (x[4] < -params.steer_limit && u[1] < 0.0f)) ? 1e-2f : 1.0f; float v_new = x[3] + dt * scale_v * u[0]; float tan_phi = std::tan(x[4]); float cos_phi = std::cos(x[4]); float phi_new = x[4] + dt * scale_phi * u[1]; float tan_phi_new = std::tan(phi_new); float cos_phi_new = std::cos(phi_new); float cos_th = std::cos(x[2]); float sin_th = std::sin(x[2]); float th_new = x[2] + 0.5f * dt / L * (x[3]*tan_phi + v_new*tan_phi_new); float cos_th_new = std::cos(th_new); float sin_th_new = std::sin(th_new); if (dxtpdt_dx != nullptr) { (*dxtpdt_dx) = Eigen::MatrixXf::Identity(5, 5); (*dxtpdt_dx)(2, 3) = 0.5f * dt / L * (tan_phi + tan_phi_new); (*dxtpdt_dx)(2, 4) = 0.5f * dt / L * (x[3] / (cos_phi * cos_phi) + v_new / (cos_phi_new * cos_phi_new)); (*dxtpdt_dx)(0, 2) = -0.5f * dt * (x[3] * sin_th + v_new * sin_th_new); (*dxtpdt_dx)(0, 3) = 0.5f * dt * (cos_th + cos_th_new - v_new * sin_th_new * (*dxtpdt_dx)(2, 3)); (*dxtpdt_dx)(0, 4) = -0.5f * dt * v_new * sin_th_new * (*dxtpdt_dx)(2, 4); (*dxtpdt_dx)(1, 2) = 0.5f * dt * (x[3] * cos_th + v_new * cos_th_new); (*dxtpdt_dx)(1, 3) = 0.5f * dt * (sin_th + sin_th_new + v_new * cos_th_new * (*dxtpdt_dx)(2, 3)); (*dxtpdt_dx)(1, 4) = 0.5f * dt * v_new * cos_th_new * (*dxtpdt_dx)(2, 4); } if (dxtpdt_du != nullptr) { (*dxtpdt_du) = Eigen::MatrixXf::Zero(5, 2); (*dxtpdt_du)(3, 0) = dt * scale_v; (*dxtpdt_du)(4, 1) = dt * scale_phi; (*dxtpdt_du)(2, 0) = 0.5f * dt / L * tan_phi_new * (*dxtpdt_du)(3, 0); (*dxtpdt_du)(2, 1) = 0.5f * dt * v_new * (*dxtpdt_du)(4, 1) / (L * cos_phi_new * cos_phi_new); (*dxtpdt_du)(0, 0) = 0.5f * dt * (cos_th_new * (*dxtpdt_du)(3, 0) - v_new * sin_th_new * (*dxtpdt_du)(2, 0)); (*dxtpdt_du)(0, 1) = -0.5f * dt * v_new * sin_th_new * (*dxtpdt_du)(2, 1); (*dxtpdt_du)(1, 0) = 0.5f * dt * (sin_th_new * (*dxtpdt_du)(3, 0) + v_new * cos_th_new * (*dxtpdt_du)(2, 0)); (*dxtpdt_du)(1, 1) = 0.5f * dt * v_new * cos_th_new * (*dxtpdt_du)(2, 1); } } Eigen::Vector2f ACARTTCSGDProblem::GetCollisionCenter(const Eigen::VectorXf &x, Eigen::MatrixXf* dc_dx) { float len_scale = 2.0f / std::sqrt(5.0f); float s_th = std::sin(x[2]); float c_th = std::cos(x[2]); if (dc_dx != nullptr) { (*dc_dx) = Eigen::MatrixXf::Identity(2,x.size()); (*dc_dx)(0,2) = -len_scale * params.radius * s_th; (*dc_dx)(1,2) = len_scale * params.radius * c_th; } return x.head<2>() + len_scale * params.radius * Eigen::Vector2f(c_th, s_th); } void ACARTTCSGDProblem::AdditionalCosts(const Eigen::VectorXf &u, float* cost, Eigen::VectorXf* dc_du) { // Velocity Constraint Cost: Eigen::VectorXf x_t; Eigen::MatrixXf dxt_du; if (dc_du != nullptr) { DynamicsLong(u, params.x_0, 0.0f, 1.0f, &x_t, &dxt_du, nullptr); } else { DynamicsLong(u, params.x_0, 0.0f, 1.0f, &x_t); } if (std::abs(x_t[3]) > params.vel_limit) { float err; if (x_t[3] > params.vel_limit) { err = x_t[3] - params.vel_limit; } else { err = x_t[3] + params.vel_limit; // x_t[3] is negative } if (cost != nullptr) { (*cost) += params.k_v_constr * err * err; } if (dc_du != nullptr) { (*dc_du) += 2.0 * params.k_v_constr * err * dxt_du.row(3); } } if (std::abs(x_t[4]) > params.steer_limit) { float err; if (x_t[4] > params.steer_limit) { err = x_t[4] - params.steer_limit; } else { err = x_t[4] + params.steer_limit; // x_t[3] is negative } if (cost != nullptr) { (*cost) += params.k_v_constr * err * err; } if (dc_du != nullptr) { (*dc_du) += 2.0 * params.k_v_constr * err * dxt_du.row(4); } } } void ACARTTCSGDProblem::ProjConstr(Eigen::VectorXf& u) { // Trim u to control constraints TTCSGDProblem::ProjConstr(u); // Trim u to state constraints float v_new = params.x_0[3] + params.dt_step * u[0]; if (v_new > params.vel_limit) { u[0] = (params.vel_limit - params.x_0[3]) / params.dt_step; } float phi_new = params.x_0[4] + params.dt_step * u[1]; if (phi_new > params.steer_limit) { u[1] = (params.steer_limit - params.x_0[4]) / params.dt_step; } } TTCObstacle* ACARTTCSGDProblem::CreateObstacle() { TTCObstacle* o = new ACARTTCObstacle(); FillObstacle(o); return o; } // -------------------------------------------- // ****************** MUSHR ********************* // -------------------------------------------- // x is [x, y, heading_angle] // u is [velocity, steering_angle] // For partials, see eq. 27 void MUSHRTTCSGDProblem::ContDynamics(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, Eigen::VectorXf* x_dot, Eigen::MatrixXf* dxdot_du, Eigen::MatrixXf* dxdot_dx) { // float len_scale = 2.0f / std::sqrt(5.0f); //CHANGED (not required) float L = params.wheelbase; //CHANGED. if (x_dot != nullptr) { (*x_dot) = Eigen::VectorXf::Zero(3); (*x_dot)[0] = u[0] * std::cos(x[2]); (*x_dot)[1] = u[0] * std::sin(x[2]); (*x_dot)[2] = u[0] * std::tan(u[1]) / L; } if (dxdot_du != nullptr) { (*dxdot_du) = Eigen::MatrixXf::Zero(3,2); (*dxdot_du)(0,0) = std::cos(x[2]); (*dxdot_du)(1,0) = std::sin(x[2]); (*dxdot_du)(2,0) = std::tan(u[1]) / L; (*dxdot_du)(2,1) = u[0] / (std::cos(u[1]) * std::cos(u[1]) * L); } if (dxdot_dx != nullptr) { (*dxdot_dx) = Eigen::MatrixXf::Zero(3,3); (*dxdot_dx)(0,2) = -u[0] * std::sin(x[2]); (*dxdot_dx)(1,2) = u[0] * std::cos(x[2]); } } void MUSHRTTCSGDProblem::GetDynamicsDeriv(const Eigen::VectorXf &u, const Eigen::VectorXf &x, const float t, const float dt, Eigen::MatrixXf* dxtpdt_du, Eigen::MatrixXf* dxtpdt_dx) { // float len_scale = 2.0f / std::sqrt(5.0f); //CHANGED (not required) float L = params.wheelbase; //CHANGED. float th_new = x[2] + dt * u[0] / L * std::tan(u[1]); if (dxtpdt_dx != nullptr) { (*dxtpdt_dx) = Eigen::MatrixXf::Identity(3, 3); (*dxtpdt_dx)(0, 2) = -0.5f * dt * u[0] * (std::sin(x[2]) + std::sin(th_new)); (*dxtpdt_dx)(1, 2) = 0.5f * dt * u[0] * (std::cos(x[2]) + std::cos(th_new)); } if (dxtpdt_du != nullptr) { (*dxtpdt_du) = Eigen::MatrixXf::Zero(3, 2); (*dxtpdt_du)(2, 0) = dt * std::tan(u[1]) / L; (*dxtpdt_du)(2, 1) = u[0] * dt / (L * std::cos(u[1]) * std::cos(u[1])); (*dxtpdt_du)(0, 0) = 0.5f * dt * (std::cos(x[2]) + std::cos(th_new) - u[0] * std::sin(th_new) * (*dxtpdt_du)(2, 0)); (*dxtpdt_du)(1, 0) = 0.5f * dt * (std::sin(x[2]) + std::sin(th_new) + u[0] * std::cos(th_new) * (*dxtpdt_du)(2, 0)); (*dxtpdt_du)(0, 1) = -0.5f * dt * u[0] * std::sin(th_new) * (*dxtpdt_du)(2, 1); (*dxtpdt_du)(1, 1) = 0.5f * dt * u[0] * std::cos(th_new) * (*dxtpdt_du)(2, 1); } } Eigen::Vector2f MUSHRTTCSGDProblem::GetCollisionCenter(const Eigen::VectorXf &x, Eigen::MatrixXf* dc_dx) { float len_scale = 2.0f / std::sqrt(5.0f); if (dc_dx != nullptr) { (*dc_dx) = Eigen::MatrixXf::Identity(2,x.size()); (*dc_dx)(0,2) = -len_scale * params.radius * std::sin(x[2]); (*dc_dx)(1,2) = len_scale * params.radius * std::cos(x[2]); } return x.head<2>() + len_scale * params.radius * Eigen::Vector2f(std::cos(x[2]), std::sin(x[2])); } TTCObstacle* MUSHRTTCSGDProblem::CreateObstacle() { TTCObstacle* o = new MUSHRTTCObstacle(); FillObstacle(o); return o; }
40.318255
460
0.543735
[ "model" ]
bce83c88b894b9b52ed9f75ada2dfcc10066e8b8
3,006
cpp
C++
src/slaggy-engine/slaggy-engine/physics/spatial/Octree.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
1
2021-09-24T23:13:13.000Z
2021-09-24T23:13:13.000Z
src/slaggy-engine/slaggy-engine/physics/spatial/Octree.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
null
null
null
src/slaggy-engine/slaggy-engine/physics/spatial/Octree.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
2
2020-06-24T07:10:13.000Z
2022-03-08T17:19:12.000Z
#include "Octree.hpp" #include <glm/ext/matrix_transform.hpp> #include <utils/BoxDebug.hpp> namespace slaggy { glm::vec3 Octree::cell(const unsigned index) { // example: i = 3 (0b011) -> cell = {1, 1, 0} const glm::vec3 cell(index & 1, (index & 0b010) >> 1, (index & 0b100) >> 2); return cell * 2.0f - glm::vec3(1); } Transform* Octree::transform() const { return _transform.get(); } void Octree::initialize(const glm::vec3& center, const glm::vec3& halfSize, const unsigned maxDepth) { _transform = std::make_unique<Transform>(); transform()->setPosition(center); setHalfSize(halfSize); _maxDepth = maxDepth; } void Octree::split(const unsigned depth, Shapes objects) { if (objects.empty()) return; Shapes intersecting; auto pred = [&](Shape* shape) { return shape->intersects(*this); }; std::copy_if(objects.begin(), objects.end(), std::back_inserter(intersecting), pred); if (intersecting.empty()) return; if (depth == _maxDepth || intersecting.size() == 1) { _objects.insert(intersecting.begin(), intersecting.end()); return; } for (unsigned i = 0; i < 8; ++i) { _nodes[i] = std::make_unique<Octree>(); const glm::vec3 childHalfSize = Octree::halfSize() / 2.0f; const glm::vec3 cellLocation = cell(i); _nodes[i]->construct(center() + cellLocation * childHalfSize, childHalfSize, depth + 1, _maxDepth, intersecting); } } void Octree::construct(const glm::vec3& center, const glm::vec3& halfSize, const unsigned depth, const unsigned maxDepth, const Shapes& objects) { _currentDepth = depth; initialize(center, halfSize, maxDepth); split(depth, objects); } void Octree::reset() { for (auto&& node : _nodes) node = nullptr; _objects.clear(); } std::vector<CollisionPair> Octree::collisions() const { std::vector<CollisionPair> pairs; if (!_nodes[0]) { if (_objects.empty()) return pairs; for (auto i_iter = _objects.begin(); i_iter != _objects.end(); ++i_iter) for (auto j_iter = std::next(i_iter, 1); j_iter != _objects.end(); ++j_iter) pairs.emplace_back(*i_iter, *j_iter); } else { for (unsigned i = 0; i < 8; ++i) { std::vector<CollisionPair> childPairs = _nodes[i]->collisions(); if (!childPairs.empty()) std::copy(childPairs.begin(), childPairs.end(), std::back_inserter(pairs)); } } return pairs; } void Octree::render(const glm::vec3& color, const glm::mat4& view, const glm::mat4& proj) const { const glm::mat4 model = glm::scale(scaledTransformationMatrix(), glm::vec3(1 - 0.05f * float(_currentDepth))); BoxDebug::instance().render(color, model, view, proj); } void Octree::renderNodes(const glm::mat4& view, const glm::mat4& proj) const { glm::vec3 color = glm::vec3(1); if (_objects.size() == 1) color = glm::vec3(0, 1, 0); else if (_objects.size() > 1) color = glm::vec3(1, 0, 0); if (!_objects.empty()) render(color, view, proj); for (auto&& child : _nodes) if (child) child->renderNodes(view, proj); } }
27.327273
116
0.655356
[ "render", "shape", "vector", "model", "transform" ]
bceb74928279dc5a7c06001c401ccfabd7f49417
936
cpp
C++
src/Core/Service/example/Server-listenOn.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
6
2017-08-07T07:01:48.000Z
2022-02-27T20:58:44.000Z
src/Core/Service/example/Server-listenOn.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
18
2017-08-10T20:34:50.000Z
2017-09-05T19:48:52.000Z
src/Core/Service/example/Server-listenOn.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
1
2019-02-20T19:06:13.000Z
2019-02-20T19:06:13.000Z
```cpp class MyState { // Stuf }; class MyHandler: public Serv::HandlerSuspendableWithStream { public: // Notice the last parameter is `state`. // This means a state object must be provided to the `listenOn()` method. MyHandler(Serv::Server& parent, Sock::DataSocket&& stream, MyState& state) : HandlerSuspendableWithStream(parent, std::move(stream), EV_READ) {} virtual bool eventActivateWithStream(std::istream& input, std::ostream& output) { // Stuff } }; int main() { Serv::Server server; MyStateObject state; // Because we pass state to the `listenOn()` method; this will be passed to the constructor of // `MyHandler` when it is created. This allows a user defined state object to be used consistently // across all connections. server.listenOn<MyHandler>(8080, state); // Start the event loop. server.start(); } ```
29.25
102
0.651709
[ "object" ]
bcebbea981e7bdedce6bdeb3147cf7804ac66630
1,623
cpp
C++
Array/Sequential Digits/By iterative.cpp
Ajay2521/Competitive-Programming
65a15fe04216fe058abd05c6538a8d30a78a37d3
[ "MIT" ]
1
2021-09-14T11:41:40.000Z
2021-09-14T11:41:40.000Z
Array/Sequential Digits/By iterative.cpp
Ajay2521/Competitive-Programming
65a15fe04216fe058abd05c6538a8d30a78a37d3
[ "MIT" ]
null
null
null
Array/Sequential Digits/By iterative.cpp
Ajay2521/Competitive-Programming
65a15fe04216fe058abd05c6538a8d30a78a37d3
[ "MIT" ]
null
null
null
// Method - Iteration(Brute Force) // Time Complexity - O(n^2), since nested loop runs n^2 times // Space Complexity - O(1), Bruteforce runs on constant space class Solution { public: vector<int> sequentialDigits(int low, int high) { // variable to store the result vector<int> result; // outter loop runs for 1 to 9 times for(int i =1; i<10; i++){ // assigning the "i" value to "x" int x = i; // inner loop runs for "i+1" to 9 times for (int j = i+1; j<10; j++){ // multiple the value of x with 10, // to make the value in the form of tens, hundres and so on... // Eg: 1 becomes 10, 12 becomes 120 and so on x = x * 10; // adding the value of "j" to the "x" // Ex: 10 + 2 => 12, 120 + 3 = > 123 x = x + j; // check the value of x in range of "low" and "high" // if so append the values to the "result" variable if(x>= low && x<=high){ result.push_back(x); } // if the value of "x" turns more than high // then break the inner loop if(x > high){ break; } } } // sort the result variable sort(result.begin(), result.end()); // printing the result return result; } };
31.823529
78
0.426987
[ "vector" ]
bcf3e8b97fe4320629e2ce6e08a631306ffc84c5
38,131
cpp
C++
main.cpp
katjawolff/custom_fit_garments
1d6f9dcba612010bb5552201f39595f7b288b8d5
[ "MIT" ]
4
2021-08-15T09:28:51.000Z
2022-03-14T10:19:09.000Z
main.cpp
katjawolff/custom_fit_garments
1d6f9dcba612010bb5552201f39595f7b288b8d5
[ "MIT" ]
1
2021-12-24T07:16:34.000Z
2021-12-24T07:16:34.000Z
main.cpp
katjawolff/custom_fit_garments
1d6f9dcba612010bb5552201f39595f7b288b8d5
[ "MIT" ]
null
null
null
#include <igl/opengl/glfw/Viewer.h> #include <igl/opengl/glfw/imgui/ImGuiMenu.h> #include <imgui/imgui.h> #include <iostream> #include <chrono> #include <igl/png/readPNG.h> #include <igl/unproject_onto_mesh.h> #include <igl/edges.h> #include <igl/boundary_loop.h> #include <igl/bfs.h> #include <igl/remove_duplicate_vertices.h> #include "toolbox/readGarment.h" #include "toolbox/clothsimulation/cloth.h" #include "toolbox/mesh_interpolation.h" #include "toolbox/garmentcreation/garment_boundaries.h" #include "toolbox/adjacency.h" #include "toolbox/garmentcreation/remesh.h" using namespace Eigen; using namespace std; // variables //float time_step = 0.0025; float time_step = 0.0025; float K_stretch = 800.f; // in g/s^2 float K_stretch_damping = 100.; float K_shear = 200.; float K_shear_damping = 1.; float K_bend = 0.001; float K_bend_damping = 0.01; float total_mass = 1.5; // in kg; float garment_refinement = 0.3; float t_stretch = 1.09; float t_compress = 0.; float dist_to_body = 0.005; float rs_offset = 0.; bool gar_loaded = false; bool man_loaded = false; bool cloth_loaded = false; bool show_avatar_window = false; bool man_of_many_loaded = false; bool move_avatar = false; bool adjust_garment = true; bool show_wiregrid = false; bool simulate = false; bool pause_simulation = false; bool paint = false; bool gravity = true; Cloth* clo; Eigen::MatrixXd Vg, Vg_initial, Vm, Vuv; // meshes for the garment and mannequin Eigen::MatrixXi Fg, Fm; Eigen::MatrixXi Eg; vector< vector<int> > Am, Ag_ve; // adjacency list for the mannequin mesh Vm/Fm // vertex-edge adjacency for the garment SparseMatrix<double> Ag_mat; // adjacency matrix for the garment vector<MatrixXd> V_avatars; vector<MatrixXi> F_avatars; vector<GLuint> Images_avatars; Eigen::Vector3d ambient, ambient_grey, diffuse, diffuse_grey, specular; // avatar interpolation MeshInterpolator* mesh_interpolator; const int avatar_movement_total_frames = 60; int avatar_movement_current_frame = 0; int intermediate_frames_count = 0; int max_sim_interval = 4; // frames // garment paint more cloth float paint_inner_radius = 0.01; float paint_outer_radius = 0.03; float max_edge_adjustment = 3.; vector<double> edge_adjustment; bool edge_adjustment_needed = false; MatrixXd Cpaint; // garment add new boundary bool place_boundary = false; Vector3d center, axis; vector<int> old_boundary; double avrg_dist_to_center; // boundaries GarmentBoundaries* boundaries; GarmentBoundaries* cut_boundaries; // mouse interaction enum MouseMode { SELECTVERTS, SELECTBVERTS1, SELECTBVERTS2, SELECTGARMENT, SELECTBOUNDARY, PAINT, NEWBOUNDARY, NONE }; MouseMode mouse_mode = NONE; // some extra functions we need, that are defined after the main function bool computePointOnMesh(igl::opengl::glfw::Viewer& viewer, Eigen::MatrixXd& Vuse, Eigen::MatrixXi& Fuse, Eigen::Vector3d& position, int& fid); int computeClosestVertexOnMesh(Vector3d& b, int& fid, MatrixXi& F); bool callback_mouse_down(igl::opengl::glfw::Viewer& viewer, int button, int modifier); bool callback_mouse_move(igl::opengl::glfw::Viewer& viewer, int mouse_x, int mouse_y); bool callback_mouse_up(igl::opengl::glfw::Viewer& viewer, int button, int modifier); bool callback_key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int modifiers); void avatarMenu(igl::opengl::glfw::Viewer& viewer); void setNewGarmentMesh(igl::opengl::glfw::Viewer& viewer); void setNewInterpolationMesh(MatrixXd& Vm_new); bool interpolateAvatar(igl::opengl::glfw::Viewer& viewer); void startSimulation(igl::opengl::glfw::Viewer& viewer); void pauseSimulation(igl::opengl::glfw::Viewer& viewer); void stopSimulation(igl::opengl::glfw::Viewer& viewer); void showGarment(igl::opengl::glfw::Viewer& viewer); void showMannequin(igl::opengl::glfw::Viewer& viewer); void showBoundary(igl::opengl::glfw::Viewer& viewer); void showRestShape(igl::opengl::glfw::Viewer& viewer); int left_view, right_view; bool pre_draw(igl::opengl::glfw::Viewer& viewer) { viewer.data(0).set_visible(true, left_view); viewer.data(0).set_visible(false, right_view); viewer.data(1).set_visible(true, left_view); viewer.data(1).set_visible(false, right_view); viewer.data(2).set_visible(true, left_view); viewer.data(2).set_visible(false, right_view); viewer.data(3).set_visible(false, left_view); viewer.data(3).set_visible(true, right_view); // cloth simulation if (simulate) { // update the avatar bool avatar_moved = false; if (intermediate_frames_count < max_sim_interval) intermediate_frames_count++; else { intermediate_frames_count = 0; if (move_avatar) avatar_moved = interpolateAvatar(viewer); } if (avatar_moved) clo->StepPhysics(time_step, Vm, Fm); // if the avatar moved, we need to update the collision mesh else clo->StepPhysics(time_step); // normal, faster update if (adjust_garment && intermediate_frames_count == max_sim_interval - 1) { clo->updateRestShape(Vg, t_stretch, t_compress, edge_adjustment); fill(edge_adjustment.begin(), edge_adjustment.end(), 1.); // reset paint for (int j = 0; j < Vg.rows(); j++) Cpaint.row(j) = RowVector3d(1, 1, 0); } MatrixXd U = clo->getMesh(); // set stretch colors VectorXd S = clo->ComputeStretchPerTriangle(); // S(f) should be one -> bigger: stretch, smaller: compression MatrixXd C(Fg.rows(), 3); for (int f = 0; f < Fg.rows(); f++) { double y = (S(f) - 1.) * 3.; C.row(f) = Vector3d(1.0 + y, 1. - y, 0.0); //double y = S(f); //C.row(f) = Vector3d(y, 1.0 - y, 0.0); } viewer.selected_data_index = 0; viewer.data().set_vertices(U); viewer.data().compute_normals(); viewer.data().set_colors(C); viewer.data().uniform_colors(ambient, diffuse, specular); viewer.data().set_face_based(false); viewer.data().show_texture = false; viewer.selected_data_index = 3; MatrixXd Vrs = Vg; Vrs.col(0).array() += rs_offset; viewer.data().set_vertices(Vrs); viewer.data().compute_normals(); viewer.data().uniform_colors(ambient, diffuse, specular); viewer.data().show_texture = false; viewer.data().set_face_based(false); } // show the window with all loaded avatars if (show_avatar_window) avatarMenu(viewer); return false; } int main(int argc, char* argv[]) { // viewer igl::opengl::glfw::Viewer viewer; igl::opengl::glfw::imgui::ImGuiMenu menu; viewer.plugins.push_back(&menu); viewer.callback_init = [&](igl::opengl::glfw::Viewer& viewer) { viewer.core().viewport = Eigen::Vector4f(0, 0, 640, 800); left_view = viewer.core_list[0].id; right_view = viewer.append_core(Eigen::Vector4f(640, 0, 640, 800)); return false; }; viewer.callback_post_resize = [&](igl::opengl::glfw::Viewer& v, int w, int h) { v.core(left_view).viewport = Eigen::Vector4f(0, 0, w / 2, h); v.core(right_view).viewport = Eigen::Vector4f(w / 2, 0, w - (w / 2), h); return true; }; viewer.append_mesh(); // mesh for the garment viewer.append_mesh(); // mesh for the mannequin viewer.append_mesh(); // mesh for edge visualization (cylinders around edges) viewer.append_mesh(); // mesh for the garment rest shape // Layout viewer.core().background_color = Eigen::Vector4f(1, 1, 1, 1); viewer.core().rotation_type = igl::opengl::ViewerCore::RotationType::ROTATION_TYPE_TRACKBALL; viewer.data().show_lines = false; ambient_grey = Vector3d(0.4, 0.4, 0.4); ambient = Vector3d(0.26, 0.26, 0.26); diffuse_grey = Vector3d(0.5, 0.5, 0.5); diffuse = Vector3d(0.4, 0.57, 0.66); // blue specular = Vector3d(0.01, 0.01, 0.01); // Add content to the default menu window viewer.callback_pre_draw = &pre_draw; viewer.core().animation_max_fps = 30; viewer.core().is_animating = false; menu.callback_draw_viewer_menu = [&]() { menu.draw_viewer_menu(); // Add new group if (ImGui::CollapsingHeader("Cloth", ImGuiTreeNodeFlags_DefaultOpen)) { float gui_w = ImGui::GetContentRegionAvailWidth(); float gui_p = ImGui::GetStyle().FramePadding.x; if (ImGui::Button("Load Garment OBJ", ImVec2(gui_w - gui_p, 0))) { string garment_file_name = igl::file_dialog_open(); igl::readOBJ(garment_file_name, Vg, Fg); if (Vg.rows() == 0 || Fg.rows() == 0) { fprintf(stderr, "IOError: Could not load garment...\n"); return; } setNewGarmentMesh(viewer); } if (ImGui::Button("Load Mannequin OBJ", ImVec2(gui_w - gui_p, 0))) { cout << "Choose the file used for rendering the mannequin..." << endl; string mannequin_file_name = igl::file_dialog_open(); igl::readOBJ(mannequin_file_name, Vm, Fm); if (Vm.rows() > 0) { showMannequin(viewer); boundaries = new GarmentBoundaries(Fm); man_loaded = true; man_of_many_loaded = false; } if (gar_loaded) setNewGarmentMesh(viewer); } if (ImGui::Button("Load Avatars from folder", ImVec2(gui_w - gui_p, 0))) { cout << "Choose one file from the folder you want to load..." << endl; string folder_path = igl::file_dialog_open(); readMannequinsFromFolder(folder_path, V_avatars, F_avatars, Images_avatars); viewer.core().is_animating = true; show_avatar_window = true; man_of_many_loaded = false; } if (ImGui::Button("Save Restshape", ImVec2(gui_w - gui_p, 0))) { if (cloth_loaded) { vector<MatrixXd> Vg_list; vector<MatrixXi> Fg_list; if (cut_boundaries->numberOfBoundaries() > 0) cut_boundaries->cutGarmentAlongBoundaries(Vg, Vg_list, Fg_list); else { Vg_list.push_back(Vg); Fg_list.push_back(Fg); } for (int i = 0; i < Vg_list.size(); i++) { string folder_path = igl::file_dialog_save(); igl::writeOBJ(folder_path, Vg_list[i], Fg_list[i]); } } } if (ImGui::Button("Save Garment", ImVec2(gui_w - gui_p, 0))) { if (cloth_loaded) { MatrixXd U = clo->getMesh(); string folder_path = igl::file_dialog_save(); igl::writeOBJ(folder_path, U, Fg); /* Use this code to safe OFF file with color coded stretch VectorXd S = clo->ComputeStretchPerTriangle(); // S(f) should be one -> bigger: stretch, smaller: compression MatrixXd C(U.rows(), 3); vector< vector<int> > vf_adj; createVertexFaceAdjacencyList(Fg, vf_adj); for (int v = 0; v < U.rows(); v++) { C.row(v) = Vector3d::Zero(); for (int f = 0; f < vf_adj[v].size(); f++) { double y = (S.size() > 0) ? (S(vf_adj[v][f]) - 1.) * 3. : 0; double r = max(min(1.0 + y, 1.), 0.); double g = max(min(1. - y, 1.), 0.); C.row(v) += Vector3d(r, g, 0.0) * 255.; } C.row(v) /= vf_adj[v].size(); } igl::writeOFF(folder_path, U, Fg, C); */ } } if (ImGui::Button("Save Mannequin", ImVec2(gui_w - gui_p, 0))) { string folder_path = igl::file_dialog_save(); igl::writeOBJ(folder_path, Vm, Fm); } ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); ImGui::DragFloat("mass", &(total_mass), 0.f, 0.0f, 10.0f); ImGui::DragFloat("stretch", &(K_stretch), 1000.f, 0.0f, 1000000.0f); ImGui::DragFloat("st. damp.", &(K_stretch_damping), 10.f, 0.0f, 1000000.0f); ImGui::DragFloat("shear", &(K_shear), 0.f, 0.0f, 1000000.0f); ImGui::DragFloat("sh. damp.", &(K_shear_damping), 0.f, 0.0f, 1000000.0f); ImGui::DragFloat("bend /1K", &(K_bend), 0.f, 0.0f, 1000.0f); ImGui::DragFloat("bd. damp /1K", &(K_bend_damping), 0.0f, 0.0f, 1000.0f); ImGui::DragFloat("offset from body", &(dist_to_body), 0.f, 0.0f, 1.0f); ImGui::DragFloat("time_step", &(time_step), 0.f, 0.0f, 1.0f); ImGui::DragInt("movement sim steps", &(max_sim_interval), 0.f, 0.0f, 1.0f); ImGui::PopItemWidth(); ImGui::Checkbox("Adjust garment", &adjust_garment); //ImGui::Checkbox("Gravity", &gravity); ImGui::DragFloat("Threshhold strech", &(t_stretch), 0.f, 0.0f, 2.0f); if (ImGui::Button("Start", ImVec2(gui_w - gui_p, 0))) { startSimulation(viewer); } if (ImGui::Button("Pause", ImVec2(gui_w - gui_p, 0))) { pauseSimulation(viewer); } if (ImGui::Button("Stop", ImVec2(gui_w - gui_p, 0))) { stopSimulation(viewer); } if (ImGui::Button("Adjust offset", ImVec2(gui_w - gui_p, 0))) { clo->setOffset(dist_to_body); } if (ImGui::Button("Load Sim OBJ", ImVec2(gui_w - gui_p, 0))) { string garment_file_name = igl::file_dialog_open(); MatrixXd Vsim; MatrixXi Fsim; igl::readOBJ(garment_file_name, Vsim, Fsim); if (Vsim.rows() == 0 || Fsim.rows() == 0) { fprintf(stderr, "IOError: Could not load garment...\n"); return; } clo->setSimMesh(Vsim); // check if there are several components. If needed, add seam forces vector<vector<int>> L; igl::boundary_loop(Fsim, L); if (L.size() > 1) { vector< pair<int, int> > seam_verts; for (int b1 = 0; b1 < L.size() - 1; b1++) { // TODO do this better with a kd tree or sth similar for (int v1 = 0; v1 < L[b1].size(); v1++) { bool found = false; for (int b2 = b1 + 1; b2 < L.size() && !found; b2++) { for (int v2 = 0; v2 < L[b2].size() && !found; v2++) { if ((Vsim.row(L[b1][v1]) - Vsim.row(L[b2][v2])).norm() == 0 /*< 1e-8*/) { seam_verts.push_back(make_pair(L[b1][v1], L[b2][v2])); found = true; } } } } } clo->setSeamVertices(seam_verts); } } } if (ImGui::CollapsingHeader("Boundaries", ImGuiTreeNodeFlags_DefaultOpen)) { float gui_w = ImGui::GetContentRegionAvailWidth(); float gui_p = ImGui::GetStyle().FramePadding.x; if (ImGui::Button("Start new circle boundary", ImVec2(gui_w - gui_p, 0))) { mouse_mode = SELECTVERTS; } if (ImGui::Button("Close circle boundary", ImVec2(gui_w - gui_p, 0))) { if (!gar_loaded) boundaries->closeBoundary(Vm); else { cut_boundaries->closeBoundary(Vg); } showBoundary(viewer); mouse_mode = NONE; } /*if (ImGui::Button("Start new edge boundary", ImVec2(gui_w - gui_p, 0))) { mouse_mode = SELECTBVERTS1; }*/ if (ImGui::Button("Delete last", ImVec2(gui_w - gui_p, 0))) { if (!gar_loaded) boundaries->deleteLast(); else cut_boundaries->deleteLast(); showBoundary(viewer); } if (ImGui::Button("Delete all", ImVec2(gui_w - gui_p, 0))) { if (!gar_loaded) boundaries->deleteAll(); else cut_boundaries->deleteAll(); showBoundary(viewer); } if (ImGui::Button("Save boundaries", ImVec2(gui_w - gui_p, 0))) { string folder_path = igl::file_dialog_save(); boundaries->saveBoundaries(folder_path); } if (ImGui::Button("Load boundaries", ImVec2(gui_w - gui_p, 0))) { string folder_path = igl::file_dialog_open(); boundaries->loadBoundaries(folder_path); showBoundary(viewer); } if (ImGui::Button("Duplicate boundary", ImVec2(gui_w - gui_p, 0))) { mouse_mode = NEWBOUNDARY; } ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); ImGui::DragFloat("garment refinement", &(garment_refinement), 0.f, 0.0f, 5.0f); ImGui::PopItemWidth(); if (ImGui::Button("Garment from boundaries", ImVec2(gui_w - gui_p, 0))) { viewer.core().is_animating = false; cloth_loaded = false; mouse_mode = SELECTGARMENT; cout << "Click on the body part that needs clothing." << endl; } if (ImGui::Button("Fix garment at boundary", ImVec2(gui_w - gui_p, 0))) { mouse_mode = SELECTBOUNDARY; cout << "Click on the boundary that you want to fix." << endl; } if (ImGui::Button("PAINT", ImVec2(gui_w - gui_p, 0))) { mouse_mode = PAINT; cout << "Paint now." << endl; } }}; // add mouse handling viewer.callback_mouse_down = callback_mouse_down; viewer.callback_mouse_move = callback_mouse_move; viewer.callback_mouse_up = callback_mouse_up; viewer.callback_key_down = callback_key_down; // Plot the mesh viewer.launch(); } void avatarMenu(igl::opengl::glfw::Viewer& viewer) { bool* p_open = new bool; // ;_; *p_open = true; ImGui::SetNextWindowSize(ImVec2(470, 500), ImGuiCond_FirstUseEver); if (!ImGui::Begin("Avatars", p_open)) { ImGui::End(); return; } float gui_w = ImGui::GetContentRegionAvailWidth(); float gui_p = ImGui::GetStyle().FramePadding.x; int images = Images_avatars.size(); for (int i = 0; i < images; i++) { GLuint tex = Images_avatars[i]; //if(i%2 == 1) // ImGui::SameLine(); if (ImGui::ImageButton((void*)(intptr_t)tex, ImVec2(200, 200), ImVec2(0, 0), ImVec2(1.f, 1.f), gui_p, ImColor(0, 0, 0, 255))) { // if we didn't load any of these mannequins yet, just show this one // also if we don't animate a piece of cloth, just switch to the next pose if (!man_of_many_loaded || !simulate) { Vm = V_avatars[i]; Fm = F_avatars[i]; showMannequin(viewer); if (!man_of_many_loaded) boundaries = new GarmentBoundaries(Fm); else showBoundary(viewer); man_loaded = true; man_of_many_loaded = true; if (gar_loaded) setNewGarmentMesh(viewer); } // but if we already loaded one mannequin, interpolate to this one now else { setNewInterpolationMesh(V_avatars[i]); } } } ImGui::End(); delete p_open; } void showGarment(igl::opengl::glfw::Viewer& viewer) { viewer.selected_data_index = 0; viewer.data().clear(); viewer.data().set_mesh(Vg, Fg); viewer.data().uniform_colors(ambient, diffuse, specular); viewer.data().show_texture = false; viewer.data().set_face_based(false); } void showMannequin(igl::opengl::glfw::Viewer& viewer) { viewer.selected_data_index = 1; viewer.data().clear(); viewer.data().set_mesh(Vm, Fm); viewer.data().show_lines = false; viewer.data().uniform_colors(ambient_grey, diffuse_grey, specular); //viewer.core().align_camera_center(viewer.data().V, viewer.data().F); viewer.data().show_texture = false; viewer.data().set_face_based(false); } void showBoundary(igl::opengl::glfw::Viewer& viewer) { MatrixXd Vb; MatrixXi Fb; boundaries->getCylindersAroundBoundaryEdges(Vm, 0.002, Vb, Fb); //if (gar_loaded) { // cut_boundaries->getCylindersAroundBoundaryEdges(Vg, 0.002, Vb, Fb); // only show cut boundaries for now if we have // Vb.col(0).array() += rs_offset; //} viewer.selected_data_index = 2; viewer.data().clear(); viewer.data().set_mesh(Vb, Fb); viewer.data().show_lines = false; viewer.data().show_texture = false; viewer.data().uniform_colors(ambient, Vector3d(1.0, 0.0, 0.0), specular); } void showRestShape(igl::opengl::glfw::Viewer& viewer) { viewer.selected_data_index = 3; viewer.data().clear(); MatrixXd Vrs = Vg; Vrs.col(0).array() += rs_offset; viewer.data().set_mesh(Vrs, Fg); viewer.data().uniform_colors(ambient, diffuse, specular); viewer.data().show_texture = false; viewer.data().set_face_based(false); } void setNewGarmentMesh(igl::opengl::glfw::Viewer& viewer) { Vg_initial = Vg; igl::edges(Fg, Eg); showGarment(viewer); showRestShape(viewer); edge_adjustment.resize(Eg.rows(), 1.); Cpaint.resize(Vg.rows(), 3); for (int j = 0; j < Vg.rows(); j++) Cpaint.row(j) = RowVector3d(1, 1, 0); cut_boundaries = new GarmentBoundaries(Fg); gar_loaded = true; if (man_loaded) { showBoundary(viewer); double k_bnd = K_bend / 1000.; double k_bnd_dmp = K_bend_damping / 1000.; clo = new Cloth(Vg, Fg, Vm, Fm, total_mass, K_stretch, K_stretch_damping, K_shear, K_shear_damping, k_bnd, k_bnd_dmp, dist_to_body, man_loaded); clo->setGravity(gravity); boundaries->createCorrespondences(Vm, Vg, Fg); clo->setConstrainedVertices(boundaries); cloth_loaded = true; } } void setNewInterpolationMesh(MatrixXd& Vm_new) { mesh_interpolator = new MeshInterpolator(Vm, Vm_new, Fm); //mesh_interpolator->precomputeInterpolatedMeshes(avatar_movement_total_frames); avatar_movement_current_frame = avatar_movement_total_frames - 1; move_avatar = true; } void startSimulation(igl::opengl::glfw::Viewer& viewer) { intermediate_frames_count = 0; if (pause_simulation) pause_simulation = false; simulate = true; viewer.core().is_animating = true; } void pauseSimulation(igl::opengl::glfw::Viewer& viewer) { simulate = false; pause_simulation = true; move_avatar = false; viewer.core().is_animating = false; } void stopSimulation(igl::opengl::glfw::Viewer& viewer) { pause_simulation = false; simulate = false; cloth_loaded = false; viewer.core().is_animating = false; Vg = Vg_initial; setNewGarmentMesh(viewer); showGarment(viewer); } bool interpolateAvatar(igl::opengl::glfw::Viewer& viewer) { // get the current interpolation value p // TODO do this with times instead of frames later, when everything runs smoothly double p = float(avatar_movement_total_frames - avatar_movement_current_frame) / float(avatar_movement_total_frames); mesh_interpolator->interpolatedMesh(p, Vm); //mesh_interpolator->getPrecomputedMesh(avatar_movement_current_frame, Vm); showMannequin(viewer); showBoundary(viewer); // updates the boundary vizualization on the moved avatar // update the time value if (avatar_movement_current_frame == 0) move_avatar = false; else avatar_movement_current_frame -= 1; return true; } void getBoundaryCenterAxis(Vector3d& v) { vector<vector<int> > boundaries; igl::boundary_loop(Fg, boundaries); // get coordinates of the clostest boundaries double dist = 1e10; double boundary_id = 0; for (int i = 0; i < boundaries.size(); i++) { for (int j = 0; j < boundaries[i].size(); j++) { double new_dist = (Vg.row(boundaries[i][j]).transpose() - v).norm(); if (new_dist < dist) { dist = new_dist; boundary_id = i; } } } old_boundary = boundaries[boundary_id]; // go along boundary and average vertices and normals center = Vector3d(0, 0, 0); for (int j = 0; j < old_boundary.size(); j++) center += Vg.row(old_boundary[j]); center /= old_boundary.size(); axis = Vector3d(0, 0, 0); avrg_dist_to_center = 0; for (int j = 0; j < old_boundary.size(); j++) { Vector3d to_center = center - Vg.row(old_boundary[j]).transpose(); avrg_dist_to_center += to_center.norm(); Vector3d edge; if (j == 0) edge = Vg.row(old_boundary[j]) - Vg.row(old_boundary[old_boundary.size() - 1]); else edge = Vg.row(old_boundary[j]) - Vg.row(old_boundary[j - 1]); axis += to_center.cross(edge).normalized(); } avrg_dist_to_center /= old_boundary.size(); axis.normalize(); } void duplicateBoundaryAndCreateMesh(const double scaling, const Vector3d& new_center, MatrixXd& Vnew, MatrixXi& Fnew) { // duplicate MatrixXd new_boundary(old_boundary.size(), 3); for (int j = 0; j < old_boundary.size(); j++) { Vector3d to_center = Vg.row(old_boundary[j]).transpose() - center; to_center *= scaling; new_boundary.row(j) = new_center + to_center; } // create triangles between old and new boundary Vnew.resize(old_boundary.size() * 2, 3); Fnew.resize(old_boundary.size() * 2, 3); for (int i = 0; i < old_boundary.size(); i++) { Vnew.row(2 * i) = Vg.row(old_boundary[i]); Vnew.row(2 * i + 1) = new_boundary.row(i); Fnew.row(2 * i) = Vector3i(2 * i, 2 * i + 1, 2 * i + 2); Fnew.row(2 * i + 1) = Vector3i(2 * i + 1, 2 * i + 3, 2 * i + 2); if (i == old_boundary.size() - 1) { Fnew.row(2 * i) = Vector3i(2 * i, 2 * i + 1, 0); Fnew.row(2 * i + 1) = Vector3i(2 * i + 1, 1, 0); } } } bool computePointOnMesh(igl::opengl::glfw::Viewer& viewer, MatrixXd& V, MatrixXi& F, Vector3d& b, int& fid) { double x = viewer.current_mouse_x; double y = viewer.core().viewport(3) - viewer.current_mouse_y; return igl::unproject_onto_mesh(Vector2f(x, y), viewer.core().view, viewer.core().proj, viewer.core().viewport, V, F, fid, b); } int computeClosestVertexOnMesh(Vector3d& b, int& fid, MatrixXi& F) { // get the closest vertex in that face int v_id; if (b(0) > b(1) && b(0) > b(2)) v_id = F(fid, 0); else if (b(1) > b(0) && b(1) > b(2)) v_id = F(fid, 1); else v_id = F(fid, 2); return v_id; } bool callback_mouse_down(igl::opengl::glfw::Viewer& viewer, int button, int modifier) { if (button == (int)igl::opengl::glfw::Viewer::MouseButton::Right) return false; // select vertices for the boundary if (mouse_mode == SELECTVERTS) { int fid; Eigen::Vector3d b; // Boundaries on avatar if (!gar_loaded) { if (computePointOnMesh(viewer, Vm, Fm, b, fid)) { int v_id = computeClosestVertexOnMesh(b, fid, Fm); boundaries->addPointsToBoundary(Vm, v_id); showBoundary(viewer); viewer.data().set_points(Vm.row(v_id), RowVector3d(1.0, 0.0, 0.0)); return true; } } // Boundaries on garment else { MatrixXd Vrs = Vg; Vrs.col(0).array() += rs_offset; if (computePointOnMesh(viewer, Vrs, Fg, b, fid)) { int v_id = computeClosestVertexOnMesh(b, fid, Fg); cut_boundaries->addPointsToBoundary(Vrs, v_id); showBoundary(viewer); viewer.data().set_points(Vrs.row(v_id), RowVector3d(1.0, 0.0, 0.0)); return true; } } } // select an edge to edge boundary // unused at the moment if (mouse_mode == SELECTBVERTS1) { int fid; Eigen::Vector3d b; if (computePointOnMesh(viewer, Vg, Fg, b, fid)) { int v_id = computeClosestVertexOnMesh(b, fid, Fg); // TODO find closest boundary vertex OR just check if it is one cut_boundaries->addPointsToBoundary(Vg, v_id); viewer.data().set_points(Vg.row(v_id), RowVector3d(1.0, 0.0, 0.0)); mouse_mode = SELECTBVERTS2; return true; } } if (mouse_mode == SELECTBVERTS2) { int fid; Eigen::Vector3d b; if (computePointOnMesh(viewer, Vg, Fg, b, fid)) { int v_id = computeClosestVertexOnMesh(b, fid, Fg); // TODO find closest boundary vertex OR just check if it is one cut_boundaries->addPointsToBoundary(Vg, v_id); cut_boundaries->endBoundary(Vg); showBoundary(viewer); mouse_mode = SELECTBVERTS2; return true; } } // select a region that becomes be a garment if (mouse_mode == SELECTGARMENT) { int fid; Eigen::Vector3d b; if (computePointOnMesh(viewer, Vm, Fm, b, fid)) { int v_id = computeClosestVertexOnMesh(b, fid, Fm); boundaries->garmentFromBoundaries(Vm, v_id, Vg, Fg, garment_refinement); setNewGarmentMesh(viewer); mouse_mode = NONE; return true; } } // mark a boundary as fixed if (mouse_mode == SELECTBOUNDARY) { int fid; Vector3d b; if (computePointOnMesh(viewer, Vm, Fm, b, fid)) { Vector3d p = b(0) * Vm.row(Fm(fid, 0)) + b(1) * Vm.row(Fm(fid, 1)) + b(2) * Vm.row(Fm(fid, 2)); boundaries->markClosestBoundaryAsFixed(Vm, p); // TODO show boundary as blue mouse_mode = NONE; return true; } } // paint more cloth if (mouse_mode == PAINT) { cout << "paintstart" << endl; paint = true; igl::adjacency_matrix(Fg, Ag_mat); createVertexEdgeAdjecencyList(Eg, Ag_ve); mouse_mode = NONE; } // select a boundary of the garment that should be duplicated ... if (mouse_mode == NEWBOUNDARY) { cout << "click on the garment near a bounary that needs extending" << endl; int fid; Eigen::Vector3d b; if (computePointOnMesh(viewer, Vm, Fm, b, fid)) { Vector3d p = b(0) * Vm.row(Fm(fid, 0)) + b(1) * Vm.row(Fm(fid, 1)) + b(2) * Vm.row(Fm(fid, 2)); getBoundaryCenterAxis(p); place_boundary = true; mouse_mode = NONE; } return true; } // ...and duplicate the boundary to create a bigger garment if (place_boundary) { cout << "create new boundary" << endl; // get click axis Vector3d s, dir; double x = viewer.current_mouse_x; double y = viewer.core().viewport(3) - viewer.current_mouse_y; igl::unproject_ray(Vector2f(x, y), viewer.core().view, viewer.core().proj, viewer.core().viewport, s, dir); // get distance to boundary axis Vector3d n = dir.cross(axis); double distance = n.dot(center - s) / n.norm(); Vector3d n1 = dir.cross(n); Vector3d new_center = center + (s - center).dot(n1) * axis / axis.dot(n1); double scaling = abs(distance / avrg_dist_to_center); // add new boundary MatrixXd Vnew; MatrixXi Fnew; duplicateBoundaryAndCreateMesh(scaling, new_center, Vnew, Fnew); // add to Vm MatrixXd Vmerged(Vg.rows() + Vnew.rows(), 3); MatrixXi Fmerged(Fg.rows() + Fnew.rows(), 3); Vmerged.block(0, 0, Vg.rows(), 3) = Vg; Vmerged.block(Vg.rows(), 0, Vnew.rows(), 3) = Vnew; Fmerged.block(0, 0, Fg.rows(), 3) = Fg; Fmerged.block(Fg.rows(), 0, Vnew.rows(), 3) = Fnew; for (int f = Fg.rows(); f < Fmerged.rows(); f++) Fmerged.row(f) += RowVector3i(1, 1, 1) * Vg.rows(); // remove duplicate vertices to make into single connected mesh MatrixXd SV; MatrixXi SF; VectorXi SVI, SVJ; igl::remove_duplicate_vertices(Vmerged, Fmerged, 1e-7, SV, SVI, SVJ, SF); // remesh double area_old = 1., area_new = 1.; for (int f = 0; f < Fg.rows(); f++) { Vector3d v1 = Vg.row(Fg(f, 1)) - Vg.row(Fg(f, 0)); Vector3d v2 = Vg.row(Fg(f, 2)) - Vg.row(Fg(f, 0)); area_old += v1.cross(v2).norm(); } for (int f = 0; f < Fnew.rows(); f++) { Vector3d v1 = Vnew.row(Fnew(f, 1)) - Vnew.row(Fnew(f, 0)); Vector3d v2 = Vnew.row(Fnew(f, 2)) - Vnew.row(Fnew(f, 0)); area_old += v1.cross(v2).norm(); } double remesh_factor = (area_new + area_old) / area_old; remesh(SV, SF, Vg, Fg, remesh_factor); setNewGarmentMesh(viewer); place_boundary = false; return true; } return false; } bool callback_mouse_move(igl::opengl::glfw::Viewer& viewer, int mouse_x, int mouse_y) { // paint the garment if (paint && gar_loaded) { int fid; Eigen::Vector3d b; MatrixXd U; if (cloth_loaded) U = clo->getMesh(); else U = Vg; if (computePointOnMesh(viewer, U, Fg, b, fid)) { Vector3d point = b(0) * U.row(Fg(fid, 0)) + b(1) * U.row(Fg(fid, 1)) + b(2) * U.row(Fg(fid, 2)); int v_id = computeClosestVertexOnMesh(b, fid, Fg); // do breadth first search to mark close edges with the paintbrush vector<int> d, predecessors; // d: indices of vertices in discovery order, p: indices of predecessors (-1 is root), //p[i] is the index of the vertex v which preceded d[i] in the breadth first traversal igl::bfs(Ag_mat, v_id, d, predecessors); // go through edges int i = 0; vector<bool> edge_visited(Eg.rows(), false); double vertex_dist = 0.; while (vertex_dist < 2. * paint_outer_radius && i < d.size()) { int v = d[i]; // get next vertex id vector<int> adjacent_edges = Ag_ve[v]; // get all adjacent edges (mark those that were already visited) for (int j = 0; j < adjacent_edges.size(); j++) { int e = adjacent_edges[j]; if (!edge_visited[e]) { // get distance from point (middle of edge) int v1 = Eg(e, 0); int v2 = Eg(e, 1); Vector3d middle = 0.5 * (U.row(v1) + U.row(v2)); double dist = (middle - point).norm(); double value; if (dist < paint_inner_radius) value = 1.; else if (dist > paint_outer_radius) value = 0.; else value = 1. - (dist - paint_inner_radius) / paint_outer_radius; value *= max_edge_adjustment * 0.33; // don't use full saturation basically /*edge_adjustment[e] = max(value, edge_adjustment[e]); if (value > 0.) edge_adjustment_needed = true;*/ value += 1.; // make it a factor edge_adjustment[e] = max(value, edge_adjustment[e]); if (value > 0.) edge_adjustment_needed = true; // color Cpaint(v1, 1) = max(0., Cpaint(v1, 1) - (edge_adjustment[e] - 1.) / Ag_ve[v1].size()); Cpaint(v2, 1) = max(0., Cpaint(v2, 1) - (edge_adjustment[e] - 1.) / Ag_ve[v2].size()); // assign a value in (0,1) to this edge edge_visited[e] = true; } } // get distance of the vert is bigger than a threshold -> stop vertex_dist = (U.row(v).transpose() - point).norm(); i++; } // render viewer.selected_data_index = 0; viewer.data().clear(); viewer.data().set_mesh(U, Fg); viewer.data().uniform_colors(ambient, diffuse, specular); viewer.data().set_colors(Cpaint); viewer.data().show_texture = false; return true; } } return false; } bool callback_mouse_up(igl::opengl::glfw::Viewer& viewer, int button, int modifier) { if (paint) { paint = false; cout << "paint stop" << endl; return true; } return false; }; bool callback_key_down(igl::opengl::glfw::Viewer& viewer, unsigned char key, int modifiers) { bool handled = false; if (key == 'L') { show_wiregrid = !show_wiregrid; viewer.selected_data_index = 0; viewer.data().show_lines = show_wiregrid; viewer.selected_data_index = 3; viewer.data().show_lines = !show_wiregrid; handled = true; } if (key == 'S') { pauseSimulation(viewer); handled = true; } return handled; }
38.790437
135
0.567884
[ "mesh", "render", "shape", "vector" ]
bcf4f084a0cfcad9f497dca5e8b6735d2a264a4a
8,165
cpp
C++
src/Renderer.cpp
SirKoto/L-system
b0067e6e230807804c8b6afd1729e9bcbd06d782
[ "MIT" ]
null
null
null
src/Renderer.cpp
SirKoto/L-system
b0067e6e230807804c8b6afd1729e9bcbd06d782
[ "MIT" ]
null
null
null
src/Renderer.cpp
SirKoto/L-system
b0067e6e230807804c8b6afd1729e9bcbd06d782
[ "MIT" ]
null
null
null
#include "Renderer.hpp" #include <iostream> #include <glad/glad.h> const char* GetGLErrorStr(GLenum err) { switch (err) { case GL_NO_ERROR: return "No error"; case GL_INVALID_ENUM: return "Invalid enum"; case GL_INVALID_VALUE: return "Invalid value"; case GL_INVALID_OPERATION: return "Invalid operation"; //case GL_STACK_OVERFLOW: return "Stack overflow"; //case GL_STACK_UNDERFLOW: return "Stack underflow"; case GL_OUT_OF_MEMORY: return "Out of memory"; default: return "Unknown error"; } } void CheckGLError() { while (true) { const GLenum err = glGetError(); if (GL_NO_ERROR == err) break; std::cout << "GL Error: " << GetGLErrorStr(err) << std::endl; } } static const char* VERTEX_SHADER = "#version 330 core\n" "#extension GL_ARB_explicit_uniform_location : enable\n" "layout(location = 0) in vec3 aPos;\n" "layout(location = 1) in float aWidth;\n" "layout(location = 0) uniform mat4 MVP;\n" "void main()\n" "{\n" " gl_Position = MVP * vec4(aPos, 1.0);\n" "}\n"; static const char* FRAGMENT_SHADER = "#version 330 core\n" "out vec4 FragColor;\n" "#extension GL_ARB_explicit_uniform_location : enable\n" "layout(location = 1) uniform vec3 color;\n" "void main()\n" "{\n" " FragColor = vec4(color, 1.0);\n" "}\n"; static const char* VERTEX_SHADER_C = "#version 330 core\n" "layout(location = 0) in vec3 aPos;\n" "layout(location = 1) in float aWidth;\n" "out VS_OUT {\n" " float width;\n" "} vs_out;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos, 1.0);\n" " vs_out.width = aWidth;\n" "}\n"; // Extracted from https://github.com/torbjoern/polydraw_scripts/blob/master/geometry/drawcone_geoshader.pss static const char* GEOMETRY_SHADER_C = "#version 330 core\n" "#extension GL_ARB_explicit_uniform_location : enable\n" "layout(lines) in;\n" "layout(triangle_strip, max_vertices = 32) out;\n" "layout(location = 0) uniform mat4 MVP;\n" "layout(location = 2) uniform float widthScale;\n" "in VS_OUT {\n" " float width;\n" "} gs_in[];\n" "out vec3 normal;\n" "vec3 createPerp(vec3 p1, vec3 p2)" "{" " vec3 invec = normalize(p2 - p1);" " vec3 ret = cross(invec, vec3(0.0, 0.0, 1.0));" " if (length(ret) == 0.0)" " {" " ret = cross(invec, vec3(0.0, 1.0, 0.0));" " }" " return ret;" "}" "void main()\n" "{\n" "float r1 = widthScale * gs_in[0].width;" "float r2 = widthScale * gs_in[1].width;" "vec3 axis = gl_in[1].gl_Position.xyz - gl_in[0].gl_Position.xyz;" "vec3 perpx = createPerp(gl_in[1].gl_Position.xyz, gl_in[0].gl_Position.xyz);" "vec3 perpy = cross(normalize(axis), perpx);" "int segs = 16;" "for (int i = 0; i < segs; i++) {" " float a = i / float(segs - 1) * 2.0 * 3.14159;" " float ca = cos(a); float sa = sin(a);" " normal = vec3(ca * perpx.x + sa * perpy.x," " ca * perpx.y + sa * perpy.y," " ca * perpx.z + sa * perpy.z);" " vec3 p1 = gl_in[0].gl_Position.xyz + r1 * normal;" " vec3 p2 = gl_in[1].gl_Position.xyz + r2 * normal;" " gl_Position = MVP * vec4(p1, 1.0); EmitVertex();" " gl_Position = MVP * vec4(p2, 1.0); EmitVertex();" "}" "EndPrimitive();" "}\n"; static const char* FRAGMENT_SHADER_C = "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 normal;\n" "void main()\n" "{\n" " FragColor = vec4(.5+.5*normal,1);\n" "}\n"; static const char* FRAGMENT_SHADER_C_COLOR = "#version 330 core\n" "#extension GL_ARB_explicit_uniform_location : enable\n" "out vec4 FragColor;\n" "layout(location = 1) uniform vec3 color;\n" "in vec3 normal;\n" "const vec3 lightSource = normalize(vec3(0.5,0.5,5));\n" "void main()\n" "{\n" " float d = 0.4f + 0.6f * max(0,dot(normal, lightSource));\n" " FragColor = vec4(d * color,1);\n" "}\n"; Renderer::Renderer() : mNumPrimitives(0) { glGenVertexArrays(1, &mVAO); glGenBuffers(1, &mVBO); uint32_t vertexS = loadShader(VERTEX_SHADER, GL_VERTEX_SHADER); uint32_t fragmentS = loadShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER); uint32_t vertexC = loadShader(VERTEX_SHADER_C, GL_VERTEX_SHADER); uint32_t geometryC = loadShader(GEOMETRY_SHADER_C, GL_GEOMETRY_SHADER); uint32_t fragmentCN = loadShader(FRAGMENT_SHADER_C, GL_FRAGMENT_SHADER); uint32_t fragmentC = loadShader(FRAGMENT_SHADER_C_COLOR, GL_FRAGMENT_SHADER); CheckGLError(); { mLineProgram = glCreateProgram(); glAttachShader(mLineProgram, vertexS); glAttachShader(mLineProgram, fragmentS); glLinkProgram(mLineProgram); //there should not be linking errors.... int32_t success; glGetProgramiv(mLineProgram, GL_LINK_STATUS, &success); assert(success); } { mCylinderProgram = glCreateProgram(); glAttachShader(mCylinderProgram, vertexC); glAttachShader(mCylinderProgram, geometryC); glAttachShader(mCylinderProgram, fragmentC); glLinkProgram(mCylinderProgram); //there should not be linking errors.... int32_t success; glGetProgramiv(mCylinderProgram, GL_LINK_STATUS, &success); assert(success); } { mCylinderProgramNormal = glCreateProgram(); glAttachShader(mCylinderProgramNormal, vertexC); glAttachShader(mCylinderProgramNormal, geometryC); glAttachShader(mCylinderProgramNormal, fragmentCN); glLinkProgram(mCylinderProgramNormal); //there should not be linking errors.... int32_t success; glGetProgramiv(mCylinderProgramNormal, GL_LINK_STATUS, &success); assert(success); } CheckGLError(); glDeleteShader(vertexS); glDeleteShader(fragmentS); glDeleteShader(vertexC); glDeleteShader(fragmentC); glDeleteShader(geometryC); CheckGLError(); } Renderer::~Renderer() { glDeleteProgram(mLineProgram); glDeleteVertexArrays(1, &mVAO); glDeleteBuffers(1, &mVBO); } void Renderer::setupPrimitivesToRender(const std::vector<lParser::Cylinder>& cylinders) { glBindVertexArray(mVAO); glBindBuffer(GL_ARRAY_BUFFER, mVBO); struct Data { glm::vec3 pos; float width; }; std::vector<Data> vertData; vertData.reserve(2 * cylinders.size()); for (const lParser::Cylinder& c : cylinders) { vertData.push_back(Data{ c.init, c.width }); vertData.push_back(Data{ c.end, c.width }); } mNumPrimitives = (uint32_t)vertData.size(); glBufferData(GL_ARRAY_BUFFER, vertData.size() * sizeof(Data), vertData.data(), GL_STATIC_DRAW); CheckGLError(); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Data), (void*)offsetof(Data, pos)); glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, sizeof(Data), (void*)offsetof(Data, width)); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindVertexArray(0); CheckGLError(); } void Renderer::render(const glm::mat4& projView, uint32_t mode) const { if (mNumPrimitives == 0) { return; } if (mode == 0) { glUseProgram(mLineProgram); glLineWidth(2); glUniform3f(1, mColor.x, mColor.y, mColor.z); CheckGLError(); } else if(mode == 1) { glUseProgram(mCylinderProgram); CheckGLError(); glUniform3f(1, mColor.x, mColor.y, mColor.z); glUniform1f(2, mCylinderWidthMultiplier); CheckGLError(); } else { glUseProgram(mCylinderProgramNormal); CheckGLError(); glUniform1f(2, mCylinderWidthMultiplier); CheckGLError(); } glUniformMatrix4fv(0, 1, GL_FALSE, &projView[0][0]); CheckGLError(); glBindVertexArray(mVAO); glDrawArrays(GL_LINES, 0, mNumPrimitives); CheckGLError(); glBindVertexArray(0); } uint32_t Renderer::loadShader(const char* c_str, uint32_t shaderType) { uint32_t shader = glCreateShader(shaderType); glShaderSource(shader, 1, &c_str, nullptr); glCompileShader(shader); // check for errors int32_t success; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { int32_t len; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len); std::vector<char> errMessage(len, 0); glGetShaderInfoLog(shader, len, NULL, errMessage.data()); std::cerr << "Compilation error:\n" << errMessage.data() << std::endl; glDeleteShader(shader); return 0; } CheckGLError(); return shader; }
28.058419
108
0.67275
[ "geometry", "render", "vector" ]
bcf7a4b6c1483777f46d7a3f0f2637fa13c3b495
5,928
cpp
C++
Examples/Deprecated.GlipStudio/src/compilationTab.cpp
headupinclouds/GLIP-Lib
e0315e9c5b7ceda6280be8c33734e1dcdc04de8e
[ "MIT" ]
null
null
null
Examples/Deprecated.GlipStudio/src/compilationTab.cpp
headupinclouds/GLIP-Lib
e0315e9c5b7ceda6280be8c33734e1dcdc04de8e
[ "MIT" ]
null
null
null
Examples/Deprecated.GlipStudio/src/compilationTab.cpp
headupinclouds/GLIP-Lib
e0315e9c5b7ceda6280be8c33734e1dcdc04de8e
[ "MIT" ]
null
null
null
#include "compilationTab.hpp" // ModuleDocumentation : ModuleDocumentation::ModuleDocumentation(QWidget* parent) : Window(parent), layout(this), title("Module : "), comboBox(this), description(this, false) { frame.titleBar().setWindowTitle("Module Documentation"); title.setAlignment(Qt::AlignRight | Qt::AlignVCenter); title.setSizePolicy( QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum) ); comboBox.setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum) ); comboBox.setEditable(false); moduleChoiceLine.addWidget(&title); moduleChoiceLine.addWidget(&comboBox); layout.addLayout(&moduleChoiceLine); layout.addWidget(&description); description.setReadOnly(true); connect(&comboBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(updateDocumentationDisplay(const QString&))); setMinimumWidth(512); } ModuleDocumentation::~ModuleDocumentation(void) { } void ModuleDocumentation::updateDocumentationDisplay(const QString& moduleName) { int id = moduleNames.indexOf(moduleName); if(id>=0) description.setPlainText( tr("%1\nMANUAL :\n%2").arg(moduleInfo[id], moduleManuals[id]) ); } bool ModuleDocumentation::isDocumented(const QString& moduleName) const { return moduleNames.contains(moduleName); } bool ModuleDocumentation::isEmpty(void) const { return moduleNames.empty(); } void ModuleDocumentation::update(const LayoutLoader& loader) { std::vector<std::string> modulesNamesList = loader.listModules(); for(std::vector<std::string>::iterator it=modulesNamesList.begin(); it!=modulesNamesList.end(); it++) { if(!isDocumented( (*it).c_str() )) { const LayoutLoaderModule& module = loader.module(*it); // Create the data : QString info; if(module.getMinNumArguments()==0) info += tr("Minimum number of arguments : No arguments allowed.\n"); else if(module.getMinNumArguments()<0) info += tr("Minimum number of arguments : Unlimited.\n"); else info += tr("Minimum number of arguments : %1\n").arg(module.getMinNumArguments()); if(module.getMaxNumArguments()==0) info += tr("Maximum number of arguments : No arguments allowed.\n"); else if(module.getMaxNumArguments()<0) info += tr("Maximum number of arguments : Unlimited.\n"); else info += tr("Maximum number of arguments : %1\n").arg(module.getMaxNumArguments()); if(module.bodyPresenceTest()<0) info += tr("Body : Cannot have a body.\n"); else if(module.bodyPresenceTest()==0) info += tr("Body : Body is optional.\n"); else info += tr("Body : Must have a body.\n"); // Append : moduleNames.append( module.getName().c_str() ); moduleInfo.append( info ); moduleManuals.append( module.getManual().c_str() ); // Combo box : comboBox.addItem( module.getName().c_str() ); } } } // Compilation Tab : CompilationTab::CompilationTab(ControlModule& _masterModule, QWidget* parent) : Module(_masterModule, parent), layout(this), data(this), openSaveInterface("CompilationPannel", "File", "*.ppl, *.txt") { openSaveInterface.enableOpen(false); openSaveInterface.enableSave(false); showDocumentationAction = menuBar.addAction("Modules Documentation", this, SLOT(showDocumentation())); showDocumentationAction->setEnabled(false); dumpPipelineCodeAction = menuBar.addAction("Save Pipeline Code As...", this, SLOT(dumpPipelineCode())); dumpPipelineCodeAction->setEnabled(false); layout.addWidget(&menuBar); layout.addWidget(&data); data.setAlternatingRowColors(true); int fid = QFontDatabase::addApplicationFont("Fonts/SourceCodePro-Regular.ttf"); if( fid < 0) std::cerr << "Could not locate the font!" << std::endl; QFontDatabase db; data.setFont( db.font("Source Code Pro", "Regular", data.font().pointSize()) ); cleanCompilationTab(true); updateDocumentation(_masterModule.loader()); } CompilationTab::~CompilationTab(void) { cleanCompilationTab(false); } void CompilationTab::updateDocumentation(const LayoutLoader& loader) { documentation.update(loader); if(documentation.isEmpty()) { documentation.hide(); showDocumentationAction->setEnabled(false); } else showDocumentationAction->setEnabled(true); } void CompilationTab::cleanCompilationTab(bool writeNoPipeline) { while(data.count()>0) { QListWidgetItem* item = data.takeItem(0); delete item; } if(writeNoPipeline) { data.addItem("No Pipeline..."); data.item(0)->setFont(QFont("", -1, -1, true)); } } void CompilationTab::preparePipelineLoading(LayoutLoader& loader, const LayoutLoader::PipelineScriptElements& infos) { updateDocumentation(loader); } void CompilationTab::pipelineWasCreated(void) { cleanCompilationTab(false); // Add OK message : data.addItem("Compilation succeeded..."); data.item(0)->setFont(QFont("", -1, -1, true)); dumpPipelineCodeAction->setEnabled(true); } void CompilationTab::pipelineCompilationFailed(const Exception& e) { cleanCompilationTab(false); // Add errors : Exception err = e; err.hideHeader(true); std::string line; std::istringstream stream(err.what()); while( std::getline(stream, line) ) data.addItem( line.c_str() ); dumpPipelineCodeAction->setEnabled(false); } void CompilationTab::showDocumentation(void) { documentation.show(); } void CompilationTab::dumpPipelineCode(void) { if(pipelineExists()) { QString filename = openSaveInterface.saveAsDialog(tr("Save Raw Pipeline Code for %1").arg(pipeline().getFullName().c_str())); if(!filename.isEmpty()) { // Get the code : LayoutWriter writer; writer.writeToFile(pipeline(), filename.toStdString()); } } } void CompilationTab::closeEvent(QCloseEvent *event) { documentation.close(); }
26.702703
128
0.694669
[ "vector" ]
bcfeb5099b22206f601b340ee2b63e60f5a864d2
2,619
cpp
C++
Generator/Generator.cpp
jambolo/Sudoku
786499bfd6a8c948e91a1cfff7d65d38330b9efb
[ "MIT" ]
1
2021-12-24T07:29:41.000Z
2021-12-24T07:29:41.000Z
Generator/Generator.cpp
jambolo/Sudoku
786499bfd6a8c948e91a1cfff7d65d38330b9efb
[ "MIT" ]
1
2021-12-24T07:45:37.000Z
2021-12-24T08:40:57.000Z
Generator/Generator.cpp
jambolo/Sudoku
786499bfd6a8c948e91a1cfff7d65d38330b9efb
[ "MIT" ]
null
null
null
#include "Generator.h" #include "Board/Board.h" #include "Solver/Solver.h" #include <algorithm> #include <cassert> #include <numeric> #include <vector> #if !defined(XCODE_COMPATIBLE_ASSERT) #if defined(_DEBUG) #define XCODE_COMPATIBLE_ASSERT assert #else #define XCODE_COMPATIBLE_ASSERT(...) #endif #endif // !defined(XCODE_COMPATIBLE_ASSERT) Board Generator::generate(int difficulty /* = 0*/) { if (difficulty <= 0) difficulty = Board::NUM_CELLS; // Generate a random solved board Board board = generateSolvedBoard(); // Randomly remove as many cells as possible until no unique solution can be found std::vector<int> indexes = randomizedIndexes(); for (int i : indexes) { // Try to remove a cell int x = board.get(i); board.set(i, Board::EMPTY); // If the new puzzle doesn't have a unique solution, then undo and try again if (!Solver::hasUniqueSolution(board)) { board.set(i, x); // Skip this one continue; } // If enough values have been removed, then we are done if (--difficulty <= 0) break; } return board; } Board Generator::generateSolvedBoard() { Board board; bool successful = attempt(board, 0); XCODE_COMPATIBLE_ASSERT(successful); return board; } bool Generator::attempt(Board & board, int i) { // This function attempts to find a solution recursively by attempting all possible values for the specified cell in random order // until values can be found for all of the following cells. // If there are no remaining cells to try, then the board has been generated if (i >= Board::NUM_CELLS) return true; // Generate all the candidates for this cell. If there are none, then the board is not viable. std::vector<int> possibleValues = board.candidates(i); if (possibleValues.empty()) return false; std::random_shuffle(possibleValues.begin(), possibleValues.end()); for (int x : possibleValues) { board.set(i, x); // Try to fill in the remaining cells. If that succeeds, then the board has been generated if (attempt(board, i + 1)) return true; } // None of the candidates for this cell worked, so it isn't viable board.set(i, Board::EMPTY); // Undo any attempt in this cell return false; } std::vector<int> Generator::randomizedIndexes() { std::vector<int> indexes(Board::NUM_CELLS); std::iota(indexes.begin(), indexes.end(), 0); std::random_shuffle(indexes.begin(), indexes.end()); return indexes; }
28.16129
133
0.655594
[ "vector" ]
4c037cfc1ea9704e11b0e1539a7eeb7aa17fd6c7
14,455
cc
C++
Code/Components/Services/ingest/current/ingestpipeline/phasetracktask/FrtHWAndDrx.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Services/ingest/current/ingestpipeline/phasetracktask/FrtHWAndDrx.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Services/ingest/current/ingestpipeline/phasetracktask/FrtHWAndDrx.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file FrtHWAndDrx.cc /// /// @copyright (c) 2010 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Max Voronkov <maxim.voronkov@csiro.au> // Local package includes #include "ingestpipeline/phasetracktask/FrtHWAndDrx.h" // Include package level header file #include "askap_cpingest.h" // ASKAPsoft includes #include "askap/AskapLogging.h" #include "askap/AskapError.h" #include "askap/AskapUtil.h" #include <casacore/casa/Arrays/Vector.h> // std includes #include <string> #include <map> ASKAP_LOGGER(logger, ".FrtHWAndDrx"); namespace askap { namespace cp { namespace ingest { /// @brief Constructor. /// @param[in] parset the configuration parameter set. // @param[in] config configuration FrtHWAndDrx::FrtHWAndDrx(const LOFAR::ParameterSet& parset, const Configuration& config) : itsFrtComm(parset, config), itsDRxDelayTolerance(static_cast<int>(parset.getUint32("drxdelaystep",0u))), itsFRPhaseRateTolerance(static_cast<int>(parset.getUint32("frratestep",20u))), itsDRxMidPoint(parset.getInt32("drxmidpoint",2048)), itsFlagOutOfRangeHW(parset.getBool("flagoutofrange",true)), itsTm(config.antennas().size(),0.), itsPhases(config.antennas().size(),0.), itsUpdateTimeOffset(static_cast<int32_t>(parset.getInt32("updatetimeoffset"))) { if (itsDRxDelayTolerance == 0) { ASKAPLOG_INFO_STR(logger, "DRx delays will be updated every time the delay changes by 1.3 ns"); } else { ASKAPLOG_INFO_STR(logger, "DRx delays will be updated when the required delay diverges more than " << itsDRxDelayTolerance << " 1.3ns steps"); } if (itsFRPhaseRateTolerance == 0) { ASKAPLOG_INFO_STR(logger, "FR phase rate will be updated every time the rate changes by 0.0248 deg/s"); } else { ASKAPLOG_INFO_STR(logger, "FR phase rate will be updated every time the setting diverges more than " << itsFRPhaseRateTolerance <<" 0.0248 deg/s steps"); } ASKAPLOG_INFO_STR(logger, "DRx delay midpoint will be "<<itsDRxMidPoint); if (itsFlagOutOfRangeHW) { ASKAPLOG_INFO_STR(logger, "Antennas with DRx or FR setting out of range will be flagged"); } else { ASKAPLOG_INFO_STR(logger, "Out of HW range delay will be corrected in software (with potentially degraded performance"); } if (itsUpdateTimeOffset == 0) { ASKAPLOG_INFO_STR(logger, "The reported BAT of the fringe rotator parameter update will be used as is without any adjustment"); } else { ASKAPLOG_INFO_STR(logger, "The reported BAT of the fringe rotator parameter update will be shifted by "<<itsUpdateTimeOffset<<" microseconds"); } const std::vector<Antenna> antennas = config.antennas(); const size_t nAnt = antennas.size(); const casa::String refName = casa::downcase(parset.getString("refant")); itsRefAntIndex = nAnt; for (casa::uInt ant=0; ant<nAnt; ++ant) { if (casa::downcase(antennas.at(ant).name()) == refName) { itsRefAntIndex = ant; break; } } ASKAPCHECK(itsRefAntIndex < nAnt, "Reference antenna "<<refName<<" is not found in the configuration"); ASKAPLOG_INFO_STR(logger, "Will use "<<refName<<" (antenna index "<<itsRefAntIndex<<") as the reference antenna"); // can set up the reference antenna now to save time later itsFrtComm.setDRxAndFRParameters(itsRefAntIndex, itsDRxMidPoint, 0, 0, 0); } /// Process a VisChunk. /// /// This method is called once for each correlator integration. /// /// @param[in] chunk a shared pointer to a VisChunk object. The /// VisChunk contains all the visibilities and associated /// metadata for a single correlator integration. This method /// is expected to correct visibilities in this VisChunk /// as required (some methods may not need to do any correction at all) /// @param[in] delays matrix with delays for all antennas (rows) and beams (columns) in seconds /// @param[in] rates matrix with phase rates for all antennas (rows) and /// beams (columns) in radians per second /// @param[in] effLO effective LO frequency in Hz void FrtHWAndDrx::process(const askap::cp::common::VisChunk::ShPtr& chunk, const casa::Matrix<double> &delays, const casa::Matrix<double> &rates, const double effLO) { ASKAPDEBUGASSERT(delays.ncolumn() > 0); ASKAPDEBUGASSERT(itsRefAntIndex < delays.nrow()); ASKAPDEBUGASSERT(delays.ncolumn() == rates.ncolumn()); ASKAPDEBUGASSERT(delays.nrow() == rates.nrow()); // signal about new timestamp (there is no much point to mess around with threads // as actions are tide down to correlator cycles itsFrtComm.newTimeStamp(chunk->time()); const double samplePeriod = 1./768e6; // sample rate is 768 MHz // HW phase rate units are 2^{-28} turns per FFB sample of 54 microseconds const double phaseRateUnit = 2. * casa::C::pi / 268435456. / 54e-6; const double integrationTime = chunk->interval(); ASKAPASSERT(integrationTime > 0); // flags that HW (DRx or FR) setting is in range std::vector<bool> hwInRange(delays.nrow(),true); for (casa::uInt ant = 0; ant < delays.nrow(); ++ant) { bool outOfRange = false; // negate the sign here because we want to compensate the delay const double diffDelay = (delays(itsRefAntIndex,0) - delays(ant,0))/samplePeriod; // ideal delay ASKAPLOG_INFO_STR(logger, "delays between "<<ant<<" and ref="<<itsRefAntIndex<<" are " <<diffDelay*samplePeriod*1e9<<" ns"); casa::Int drxDelay = static_cast<casa::Int>(itsDRxMidPoint + diffDelay); if (drxDelay < 0) { ASKAPLOG_WARN_STR(logger, "DRx delay for antenna "<<ant<<" is out of range (below 0)"); drxDelay = 0; outOfRange = true; } if (drxDelay > 4095) { ASKAPLOG_WARN_STR(logger, "DRx delay for antenna "<<ant<<" is out of range (exceeds 4095)"); drxDelay = 4095; outOfRange = true; } // differential rate, negate the sign because we want to compensate here casa::Int diffRate = static_cast<casa::Int>((rates(itsRefAntIndex,0) - rates(ant,0))/phaseRateUnit); /* if (ant == 0) { const double interval = itsTm[ant]>0 ? (chunk->time().getTime("s").getValue() - itsTm[ant]) : 0; //diffRate = (int(interval/240) % 2 == 0 ? +1. : -1) * static_cast<casa::Int>(casa::C::pi / 100. / phaseRateUnit); const casa::Int rates[11] = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8,10}; const double addRate = rates[int(interval/180) % 11]; diffRate = addRate; if (int((interval - 5.)/180) % 11 != int(interval/180) % 11) { ASKAPLOG_DEBUG_STR(logger,"Invalidating ant="<<ant); itsFrtComm.invalidate(ant); } ASKAPLOG_DEBUG_STR(logger, "Interval = "<<interval<<" seconds, rate = "<<diffRate<<" for ant = "<<ant<<" addRate="<<addRate); } else { diffRate = 0.;} if (itsTm[ant]<=0) { itsTm[ant] = chunk->time().getTime("s").getValue(); } */ if (diffRate > 131071) { ASKAPLOG_WARN_STR(logger, "Phase rate for antenna "<<ant<<" is outside the range (exeeds 131071)"); diffRate = 131071; outOfRange = true; } if (diffRate < -131070) { ASKAPLOG_WARN_STR(logger, "Phase rate for antenna "<<ant<<" is outside the range (below -131070)"); diffRate = -131070; outOfRange = true; } if (itsFlagOutOfRangeHW && outOfRange) { ASKAPLOG_WARN_STR(logger, "Flagging antenna "<<ant); ASKAPDEBUGASSERT(ant < hwInRange.size()); hwInRange[ant] = false; // don't even bother setting the hardware in this case as we flag the data anyway continue; } if ((abs(diffRate - itsFrtComm.requestedFRPhaseRate(ant)) > itsFRPhaseRateTolerance) || itsFrtComm.isUninitialised(ant)) { if ((abs(drxDelay - itsFrtComm.requestedDRxDelay(ant)) > itsDRxDelayTolerance) || itsFrtComm.isUninitialised(ant)) { ASKAPLOG_INFO_STR(logger, "Set DRx delays for antenna "<<ant<<" to "<<drxDelay<<" and phase rate to "<<diffRate); itsFrtComm.setDRxAndFRParameters(ant, drxDelay, diffRate,0,0); } else { ASKAPLOG_INFO_STR(logger, "Set phase rate for antenna "<<ant<<" to "<<diffRate); itsFrtComm.setFRParameters(ant,diffRate,0,0); } itsPhases[ant] = 0.; } else { if ((abs(drxDelay - itsFrtComm.requestedDRxDelay(ant)) > itsDRxDelayTolerance) || itsFrtComm.isUninitialised(ant)) { ASKAPLOG_INFO_STR(logger, "Set DRx delays for antenna "<<ant<<" to "<<drxDelay); itsFrtComm.setDRxDelay(ant, drxDelay); } } ASKAPDEBUGASSERT(ant < itsTm.size()) /* if (itsTm[ant] > 0) { itsPhases[ant] += (chunk->time().getTime("s").getValue() - itsTm[ant]) * phaseRateUnit * itsFrtComm.requestedFRPhaseRate(ant); } */ if (itsFrtComm.hadFRUpdate(ant)) { // 25000 microseconds is the offset before event trigger and the application of phase rates/accumulator reset (specified in the osl script) // on top of this we have a user defined fudge offset (see #5736) const int32_t triggerOffset = 25000 + itsUpdateTimeOffset; const uint64_t lastReportedFRUpdateBAT = itsFrtComm.lastFRUpdateBAT(ant); ASKAPCHECK(static_cast<int64_t>(lastReportedFRUpdateBAT) > static_cast<int64_t>(triggerOffset), "The FR trigger offset "<<triggerOffset<< " microseconds is supposed to be small compared to BAT="<<lastReportedFRUpdateBAT<<", ant="<<ant); const uint64_t lastFRUpdateBAT = lastReportedFRUpdateBAT + triggerOffset; const uint64_t currentBAT = epoch2bat(casa::MEpoch(chunk->time(),casa::MEpoch::UTC)); if (currentBAT > lastFRUpdateBAT) { const uint64_t elapsedTime = currentBAT - lastFRUpdateBAT; const double etInCycles = double(elapsedTime + itsUpdateTimeOffset) / integrationTime / 1e6; ASKAPLOG_DEBUG_STR(logger, "Antenna "<<ant<<": elapsed time since last FR update "<<double(elapsedTime)/1e6<<" s ("<<etInCycles<<" cycles)"); itsPhases[ant] = double(elapsedTime) * 1e-6 * phaseRateUnit * itsFrtComm.requestedFRPhaseRate(ant); } else { ASKAPLOG_DEBUG_STR(logger, "Still processing old data before FR update event trigger for antenna "<<ant); } } // if FR had an update for a given antenna } // loop over antennas // for (casa::uInt row = 0; row < chunk->nRow(); ++row) { // slice to get this row of data const casa::uInt ant1 = chunk->antenna1()[row]; const casa::uInt ant2 = chunk->antenna2()[row]; ASKAPDEBUGASSERT(ant1 < delays.nrow()); ASKAPDEBUGASSERT(ant2 < delays.nrow()); ASKAPDEBUGASSERT(ant1 < hwInRange.size()); ASKAPDEBUGASSERT(ant2 < hwInRange.size()); if (itsFrtComm.isValid(ant1) && itsFrtComm.isValid(ant2) && hwInRange[ant1] && hwInRange[ant2]) { // desired delays are set and applied, do phase rotation casa::Matrix<casa::Complex> thisRow = chunk->visibility().yzPlane(row); const double appliedDelay = samplePeriod * (itsFrtComm.requestedDRxDelay(ant2)-itsFrtComm.requestedDRxDelay(ant1)); // attempt to correct for residual delays in software const casa::uInt beam1 = chunk->beam1()[row]; const casa::uInt beam2 = chunk->beam2()[row]; ASKAPDEBUGASSERT(beam1 < delays.ncolumn()); ASKAPDEBUGASSERT(beam2 < delays.ncolumn()); // actual delay, note the sign is flipped because we're correcting the delay here const double thisRowDelay = delays(ant1,beam1) - delays(ant2,beam2); const double residualDelay = thisRowDelay - appliedDelay; // actual rate //const double thisRowRate = rates(ant1,beam1) - rates(ant2,beam2); const double phaseDueToAppliedDelay = 2. * casa::C::pi * effLO * appliedDelay; const double phaseDueToAppliedRate = itsPhases[ant1] - itsPhases[ant2]; const casa::Vector<casa::Double>& freq = chunk->frequency(); ASKAPDEBUGASSERT(freq.nelements() == thisRow.nrow()); for (casa::uInt chan = 0; chan < thisRow.nrow(); ++chan) { //casa::Vector<casa::Complex> thisChan = thisRow.row(chan); const float phase = static_cast<float>(phaseDueToAppliedDelay + phaseDueToAppliedRate + 2. * casa::C::pi * freq[chan] * residualDelay); const casa::Complex phasor(cos(phase), sin(phase)); // actual rotation (same for all polarisations) for (casa::uInt pol = 0; pol < thisRow.ncolumn(); ++pol) { thisRow(chan,pol) *= phasor; } //thisChan *= phasor; } } else { // the parameters for these antennas are being changed, flag the data casa::Matrix<casa::Bool> thisFlagRow = chunk->flag().yzPlane(row); thisFlagRow.set(casa::True); } } } } // namespace ingest } // namespace cp } // namespace askap
49.166667
156
0.641301
[ "object", "vector" ]
4c04655806dd67e510f16dc35b1d277644e8da23
1,750
hpp
C++
include/rainbow/views/vector.hpp
Manu343726/rainbow
a125bbf04b0b94686fe0bd4149a097c56df02732
[ "MIT" ]
3
2021-05-10T21:18:32.000Z
2021-05-24T02:46:30.000Z
include/rainbow/views/vector.hpp
Manu343726/rainbow
a125bbf04b0b94686fe0bd4149a097c56df02732
[ "MIT" ]
null
null
null
include/rainbow/views/vector.hpp
Manu343726/rainbow
a125bbf04b0b94686fe0bd4149a097c56df02732
[ "MIT" ]
null
null
null
#ifndef RAINBOW_VIEWS_VECTOR_HPP #define RAINBOW_VIEWS_VECTOR_HPP #include <rainbow/memory/block.hpp> #include <rainbow/object.hpp> #include <rainbow/object/iterator.hpp> #include <rainbow/type.hpp> #include <utility> namespace rainbow::views { namespace raw { class Vector { public: Vector(const rainbow::Type* type, rainbow::memory::Block storage); std::size_t size() const; rainbow::memory::Block::Iterator begin() const; rainbow::memory::Block::Iterator end() const; rainbow::memory::Block at(const std::size_t i) const; rainbow::memory::Block operator[](const std::size_t i) const; rainbow::memory::Block front() const; rainbow::memory::Block back() const; bool empty() const; private: const rainbow::Type* _type; rainbow::memory::Block _storage; }; } // namespace raw template<typename T> class Vector : public raw::Vector { public: Vector(rainbow::memory::Block storage) : raw::Vector{rainbow::type_of<T>(), std::move(storage)} { } const T& at(const std::size_t i) const { return *rainbow::Object<T>{raw::Vector::at(i)}.get(); } T& at(const std::size_t i) { return *rainbow::Object<T>{raw::Vector::at(i)}.get(); } const T& operator[](const std::size_t i) const { return at(i); } T& operator[](const std::size_t i) { return at(i); } rainbow::object::Iterator<T> begin() const { return {raw::Vector::begin()}; } rainbow::object::Iterator<T> end() const { return {raw::Vector::end()}; } }; } // namespace rainbow::views #endif // RAINBOW_VIEWS_VECTOR_HPP
21.875
75
0.598286
[ "object", "vector" ]
4c118e306fbc28e9cbb695e2f8140343ba0ed1b3
346
cpp
C++
LeetCode/204. Count Primes.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
null
null
null
LeetCode/204. Count Primes.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
null
null
null
LeetCode/204. Count Primes.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
1
2020-05-20T18:36:31.000Z
2020-05-20T18:36:31.000Z
class Solution { public: int countPrimes(int n) { int ans = 0; vector<int> a(n, 0); for(int i = 2; i < n; i++) { if (a[i] == 0) { ans++; for (int j = i + i; j < n; j += i) { a[j] = 1; } } } return ans; } };
21.625
52
0.289017
[ "vector" ]
4c1e8bb4aac0ae59c836a3cff07ceef3cb06fb36
2,666
cpp
C++
src/httpd/httpd/json_helper.cpp
qtplatz/socfpga_modules
5f1ecc950bcb46f361970ff50176502c2ff17df1
[ "MIT" ]
null
null
null
src/httpd/httpd/json_helper.cpp
qtplatz/socfpga_modules
5f1ecc950bcb46f361970ff50176502c2ff17df1
[ "MIT" ]
1
2021-12-30T10:06:23.000Z
2021-12-30T10:06:23.000Z
src/httpd/httpd/json_helper.cpp
qtplatz/socfpga_modules
5f1ecc950bcb46f361970ff50176502c2ff17df1
[ "MIT" ]
null
null
null
// -*- C++ -*- /************************************************************************** MIT License Copyright (c) 2021-2022 Toshinobu Hondo 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 "json_helper.hpp" #include <boost/json.hpp> #include <boost/optional.hpp> #include <vector> namespace { struct tokenizer { std::vector< std::string > tokens_; tokenizer( std::string s ) { size_t pos(0); while ( ( pos = s.find( "." ) ) != std::string::npos ) { tokens_.emplace_back( s.substr( 0, pos ) ); s.erase( 0, pos + 1 ); } if ( !s.empty() ) tokens_.emplace_back( s ); } std::vector< std::string >::const_iterator begin() const { return tokens_.begin(); } std::vector< std::string >::const_iterator end() const { return tokens_.end(); } }; } std::optional< boost::json::value > json_helper::parse( const std::string& s ) { boost::system::error_code ec; auto jv = boost::json::parse( s, ec ); if ( ! ec ) return jv; return {}; } std::optional< boost::json::value > json_helper::find( const boost::json::value& jv, const std::string& keys ) // dot delimited key-list { tokenizer tok( keys ); boost::json::value value = jv; for ( const auto& key: tok ) { if ( value.kind() != boost::json::kind::object ) { return {}; // none } if ( auto child = value.as_object().if_contains( key ) ) { value = *child; } else { return {}; } } return value; }
35.078947
100
0.606527
[ "object", "vector" ]
4c2b1153728a005ae064553318cbf6e7819b06cf
200
cpp
C++
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/common/emptydmy.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
471
2019-06-26T09:59:09.000Z
2022-03-30T04:59:42.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/common/emptydmy.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/common/emptydmy.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
// This file exists so that it can be compiled into an object so the linker // will have something to chew on so that builds don't break when a platform // lacks any objects in a particular multilib.
50
76
0.765
[ "object" ]
4c2b9aa48f44ca7ada3aec9fb1e53624208f2f89
9,707
cpp
C++
ptrn_one_one_perturb.cpp
npe9/Netguage
8ab0aa363d238d6726ef04aa4c1beb2ab11faf91
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
ptrn_one_one_perturb.cpp
npe9/Netguage
8ab0aa363d238d6726ef04aa4c1beb2ab11faf91
[ "BSD-3-Clause-Open-MPI" ]
1
2020-07-14T13:42:45.000Z
2020-07-14T14:53:22.000Z
ptrn_one_one_perturb.cpp
npe9/Netguage
8ab0aa363d238d6726ef04aa4c1beb2ab11faf91
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
/* * Copyright (c) 2009 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * * Author(s): Torsten Hoefler <htor@cs.indiana.edu> * */ #include "netgauge.h" #ifdef NG_PTRN_ONE_ONE_PERTURB #include "hrtimer/hrtimer.h" #include <vector> #include <time.h> #include <algorithm> #include "fullresult.h" #include "statistics.h" #include "ng_tools.hpp" extern "C" { extern struct ng_options g_options; /* internal function prototypes */ static void one_one_perturb_do_benchmarks(struct ng_module *module); /** * comm. pattern description and function pointer table */ static struct ng_comm_pattern pattern_one_one_perturb = { pattern_one_one_perturb.name = "one_one_perturb", pattern_one_one_perturb.desc = "measures ping-pong latency&bandwidth", pattern_one_one_perturb.flags = 0, pattern_one_one_perturb.do_benchmarks = one_one_perturb_do_benchmarks }; /** * register this comm. pattern for usage in main * program */ int register_pattern_one_one_perturb() { ng_register_pattern(&pattern_one_one_perturb); return 0; } static void one_one_perturb_do_benchmarks(struct ng_module *module) { /** for collecting statistics */ struct ng_statistics statistics; /** currently tested packet size and maximum */ long data_size; /** number of times to test the current datasize */ long test_count = g_options.testcount; /** counts up to test_count */ int test_round = 0; /** how long does the test run? */ time_t test_time, cur_test_time; /** number of tests run */ int ovr_tests=0, ovr_bytes=0; long max_data_size = ng_min(g_options.max_datasize + module->headerlen, module->max_datasize); /* get needed data buffer memory */ ng_info(NG_VLEV1, "Allocating %d bytes data buffer", max_data_size); char *buffer; // = (char*)module->malloc(max_data_size); NG_MALLOC(module, char*, max_data_size, buffer); ng_info(NG_VLEV2, "Initializing data buffer (make sure it's really allocated)"); for (int i = 0; i < max_data_size; i++) buffer[i] = 0xff; int rank = g_options.mpi_opts->worldrank; g_options.mpi_opts->partner = (rank+1)%2; /* buffer for header ... */ char* txtbuf = (char *)malloc(2048 * sizeof(char)); if (txtbuf == NULL) { ng_error("Could not (re)allocate 2048 byte for output buffer"); ng_exit(10); } memset(txtbuf, '\0', 2048); /* Outer test loop * - geometrically increments data_size (i.e. data_size = data_size * 2) * (- geometrically decrements test_count) not yet implemented */ for(int compute=0; compute<2; compute++) for(int communicate=0; communicate<2; communicate++) { printf("### compute=%i, communicate=%i\n", compute, communicate); for (data_size = g_options.min_datasize; data_size > 0; get_next_testparams(&data_size, &test_count, &g_options, module)) { if(data_size == -1) goto shutdown; ++test_round; // the benchmark results std::vector<double> tcomp, tpost, twait; ng_info(NG_VLEV1, "Round %d: testing %d times with %d bytes:", test_round, test_count, data_size); // if we print dots ... if ( (rank==0) && (NG_VLEV1 & g_options.verbose) ) { printf("# "); } //if (!g_options.server) ng_statistics_start_round(&statistics, data_size); /* Inner test loop * - run the requested number of tests for the current data size * - but only if testtime does not exceed the max. allowed test time * (only if max. test time is not zero) */ test_time = 0; for (int test = -1 /* 1 warmup test */; test < test_count; test++) { /* first statement to prevent floating exception */ /* TODO: add cool abstract dot interface ;) */ if ( rank == 0 && (NG_VLEV1 & g_options.verbose) && ( test_count < NG_DOT_COUNT || !(test % (int)(test_count / NG_DOT_COUNT)) )) { printf("."); fflush(stdout); } /* call the appropriate client or server function */ if (rank==1) { cur_test_time = time(NULL); /* do the server stuff basically a simple receive and send to * mirror the data in a ping-pong fashion ... this is not in a * subfunction since this may be performance critical. The * send and receive functions are also macros */ /* Phase 1: receive data (wait for data - blocking) */ MPI_Recv(buffer, data_size, MPI_BYTE, 0 /*src*/, 0 /*tag*/, MPI_COMM_WORLD, MPI_STATUS_IGNORE); /* Phase 2: send data back */ MPI_Send(buffer, data_size, MPI_BYTE, 0 /*dst*/, 0 /*tag*/, MPI_COMM_WORLD); test_time += time(NULL) - cur_test_time; } else { MPI_Request req[2]; /* wait some time for the server to get ready */ usleep(10); cur_test_time = time(NULL); /* do the client stuff ... take time, send message, wait for * reply and take time ... simple ping-pong scheme */ HRT_TIMESTAMP_T t[4]; unsigned long long tipost, ticomp, tiwait; /* init statistics (TODO: what does this do?) */ ng_statistics_test_begin(&statistics); HRT_GET_TIMESTAMP(t[0]); if(communicate) { MPI_Isend(buffer, data_size, MPI_BYTE, 0 /*dst*/, 0 /*tag*/, MPI_COMM_WORLD, &req[0]); MPI_Irecv(buffer, data_size, MPI_BYTE, 0 /*src*/, 0 /*tag*/, MPI_COMM_WORLD, &req[1]); } /* get after-posting time */ HRT_GET_TIMESTAMP(t[1]); if(compute) { register int x=0; for(int i=0; i<1e6; i++) {x++;} } /* get after-computation time */ HRT_GET_TIMESTAMP(t[2]); /* phase 2: receive returned data */ if(communicate) MPI_Waitall(2, &req[0], MPI_STATUSES_IGNORE); /* after wait time */ HRT_GET_TIMESTAMP(t[3]); HRT_GET_ELAPSED_TICKS(t[0],t[1],&tipost); HRT_GET_ELAPSED_TICKS(t[1],t[2],&ticomp); HRT_GET_ELAPSED_TICKS(t[2],t[3],&tiwait); /* calculate results */ if(test >= 0) { tpost.push_back(HRT_GET_USEC(tipost)); tcomp.push_back(HRT_GET_USEC(ticomp)); twait.push_back(HRT_GET_USEC(tiwait)); } test_time += time(NULL) - cur_test_time; } /* calculate overall statistics */ ovr_tests++; ovr_bytes += data_size; /* measure test time and quit test if * test time exceeds max. test time * but not if the max. test time is zero */ if ( (g_options.max_testtime > 0) && (test_time > g_options.max_testtime) ) { ng_info(NG_VLEV2, "Round %d exceeds %d seconds (duration %d seconds)", test_round, g_options.max_testtime, test_time); ng_info(NG_VLEV2, "Test stopped at %d tests", test); break; } } /* end inner test loop */ if (rank==0) { /* add linebreak if we made dots ... */ if ( (NG_VLEV1 & g_options.verbose) ) { ng_info(NG_VLEV1, "\n"); } /* output statistics - compute time */ double tcomp_avg = std::accumulate(tcomp.begin(), tcomp.end(), (double)0)/(double)tcomp.size(); double tcomp_min = *min_element(tcomp.begin(), tcomp.end()); double tcomp_max = *max_element(tcomp.begin(), tcomp.end()); std::vector<double>::iterator nthblock = tcomp.begin()+tcomp.size()/2; nth_element(tcomp.begin(), nthblock, tcomp.end()); double tcomp_med = *nthblock; double tcomp_var = standard_deviation(tcomp.begin(), tcomp.end(), tcomp_avg); int tcomp_fail = count_range(tcomp.begin(), tcomp.end(), tcomp_avg-tcomp_var*2, tcomp_avg+tcomp_var*2); /* output statistics - wait time */ double twait_avg = std::accumulate(twait.begin(), twait.end(), (double)0)/(double)twait.size(); double twait_min = *min_element(twait.begin(), twait.end()); double twait_max = *max_element(twait.begin(), twait.end()); nthblock = twait.begin()+twait.size()/2; nth_element(twait.begin(), nthblock, twait.end()); double twait_med = *nthblock; double twait_var = standard_deviation(twait.begin(), twait.end(), twait_avg); int twait_fail = count_range(twait.begin(), twait.end(), twait_avg-twait_var*2, twait_avg+twait_var*2); /* output statistics - post time */ double tpost_avg = std::accumulate(tpost.begin(), tpost.end(), (double)0)/(double)tpost.size(); double tpost_min = *min_element(tpost.begin(), tpost.end()); double tpost_max = *max_element(tpost.begin(), tpost.end()); std::vector<double>::iterator nthrtt = tpost.begin()+tpost.size()/2; std::nth_element(tpost.begin(), nthrtt, tpost.end()); double tpost_med = *nthrtt; double tpost_var = standard_deviation(tpost.begin(), tpost.end(), tpost_avg); int tpost_fail = count_range(tpost.begin(), tpost.end(), tpost_avg-tpost_var*2, tpost_avg+tpost_var*2); memset(txtbuf, '\0', 2048); snprintf(txtbuf, 2047, "%ld bytes \t -> %.2lf us, %.2lf us. %.2lf us\n", data_size, /* packet size */ tpost_med, /* minimum RTT time */ tcomp_med, /* minimum RTT time */ twait_med /* minimum RTT time */ ); printf("%s", txtbuf); } ng_info(NG_VLEV1, "\n"); fflush(stdout); /* only a client does the stats stuff */ //if (!g_options.server) // ng_statistics_finish_round(&statistics); } } /* end outer test loop */ shutdown: if(txtbuf) free(txtbuf); } } /* extern C */ #else extern "C" { int register_pattern_one_one_perturb(void) {return 0;}; } #endif
35.043321
135
0.627073
[ "vector" ]
4c2cbc02453dd151d455aa8dcc48f7589bf52371
13,931
cpp
C++
src/qpid/client/ConnectionImpl.cpp
irinabov/debian-qpid-cpp-1.35.0
98b0597071c0a5f0cc407a35d5a4690d9189065e
[ "Apache-2.0" ]
1
2017-11-29T09:19:02.000Z
2017-11-29T09:19:02.000Z
src/qpid/client/ConnectionImpl.cpp
irinabov/debian-qpid-cpp-1.35.0
98b0597071c0a5f0cc407a35d5a4690d9189065e
[ "Apache-2.0" ]
null
null
null
src/qpid/client/ConnectionImpl.cpp
irinabov/debian-qpid-cpp-1.35.0
98b0597071c0a5f0cc407a35d5a4690d9189065e
[ "Apache-2.0" ]
null
null
null
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ #include "qpid/client/ConnectionImpl.h" #include "qpid/client/LoadPlugins.h" #include "qpid/client/Connector.h" #include "qpid/client/ConnectionSettings.h" #include "qpid/client/SessionImpl.h" #include "qpid/log/Statement.h" #include "qpid/Url.h" #include "qpid/framing/enum.h" #include "qpid/framing/reply_exceptions.h" #include "qpid/sys/Poller.h" #include "qpid/sys/SystemInfo.h" #include "qpid/Options.h" #include <boost/bind.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #include <limits> #include <vector> #include "config.h" namespace qpid { namespace client { using namespace qpid::framing; using namespace qpid::framing::connection; using namespace qpid::sys; using namespace qpid::framing::connection;//for connection error codes namespace { // Maybe should amalgamate the singletons into a single client singleton // Get timer singleton Timer& theTimer() { static Mutex timerInitLock; ScopedLock<Mutex> l(timerInitLock); static qpid::sys::Timer t; return t; } struct IOThreadOptions : public qpid::Options { int maxIOThreads; IOThreadOptions(int c) : Options("IO threading options"), maxIOThreads(c) { addOptions() ("max-iothreads", optValue(maxIOThreads, "N"), "Maximum number of io threads to use"); } }; // IO threads class IOThread { int maxIOThreads; int ioThreads; int connections; Mutex threadLock; std::vector<Thread> t; Poller::shared_ptr poller_; public: void add() { ScopedLock<Mutex> l(threadLock); ++connections; if (!poller_) poller_.reset(new Poller); if (ioThreads < connections && ioThreads < maxIOThreads) { QPID_LOG(debug, "Created IO thread: " << ioThreads); ++ioThreads; t.push_back( Thread(poller_.get()) ); } } void sub() { ScopedLock<Mutex> l(threadLock); --connections; } Poller::shared_ptr poller() const { assert(poller_); return poller_; } // Here is where the maximum number of threads is set IOThread(int c) : ioThreads(0), connections(0) { CommonOptions common("", "", QPIDC_CONF_FILE); IOThreadOptions options(c); common.parse(0, 0, common.clientConfig, true); options.parse(0, 0, common.clientConfig, true); maxIOThreads = (options.maxIOThreads != -1) ? options.maxIOThreads : 1; } // We can't destroy threads one-by-one as the only // control we have is to shutdown the whole lot // and we can't do that before we're unloaded as we can't // restart the Poller after shutting it down ~IOThread() { if (SystemInfo::threadSafeShutdown()) { std::vector<Thread> threads; { ScopedLock<Mutex> l(threadLock); if (poller_) poller_->shutdown(); t.swap(threads); } for (std::vector<Thread>::iterator i = threads.begin(); i != threads.end(); ++i) { i->join(); } } } }; IOThread& theIO() { static IOThread io(SystemInfo::concurrency()); return io; } class HeartbeatTask : public TimerTask { ConnectionImpl& timeout; void fire() { // If we ever get here then we have timed out QPID_LOG(debug, "Traffic timeout"); timeout.timeout(); } public: HeartbeatTask(Duration p, ConnectionImpl& t) : TimerTask(p,"Heartbeat"), timeout(t) {} }; } void ConnectionImpl::init() { // Ensure that the plugin modules have been loaded // This will make sure that any plugin protocols are available theModuleLoader(); // Ensure the IO threads exist: // This needs to be called in the Connection constructor // so that they will still exist at last connection destruction (void) theIO(); } boost::shared_ptr<ConnectionImpl> ConnectionImpl::create(framing::ProtocolVersion version, const ConnectionSettings& settings) { boost::shared_ptr<ConnectionImpl> instance(new ConnectionImpl(version, settings), boost::bind(&ConnectionImpl::release, _1)); return instance; } ConnectionImpl::ConnectionImpl(framing::ProtocolVersion v, const ConnectionSettings& settings) : Bounds(settings.maxFrameSize * settings.bounds), handler(settings, v, *this), version(v), nextChannel(1), shutdownComplete(false), released(false) { handler.in = boost::bind(&ConnectionImpl::incoming, this, _1); handler.out = boost::bind(&Connector::handle, boost::ref(connector), _1); handler.onClose = boost::bind(&ConnectionImpl::closed, this, CLOSE_CODE_NORMAL, std::string()); //only set error handler once open handler.onError = boost::bind(&ConnectionImpl::closed, this, _1, _2); handler.getSecuritySettings = boost::bind(&Connector::getSecuritySettings, boost::ref(connector)); } const uint16_t ConnectionImpl::NEXT_CHANNEL = std::numeric_limits<uint16_t>::max(); ConnectionImpl::~ConnectionImpl() { if (heartbeatTask) heartbeatTask->cancel(); theIO().sub(); } void ConnectionImpl::addSession(const boost::shared_ptr<SessionImpl>& session, uint16_t channel) { Mutex::ScopedLock l(lock); for (uint16_t i = 0; i < NEXT_CHANNEL; i++) { //will at most search through channels once uint16_t c = channel == NEXT_CHANNEL ? nextChannel++ : channel; boost::weak_ptr<SessionImpl>& s = sessions[c]; boost::shared_ptr<SessionImpl> ss = s.lock(); if (!ss) { //channel is free, we can assign it to this session session->setChannel(c); s = session; return; } else if (channel != NEXT_CHANNEL) { //channel is taken and was requested explicitly so don't look for another throw SessionBusyException(QPID_MSG("Channel " << ss->getChannel() << " attached to " << ss->getId())); } //else channel is busy, but we can keep looking for a free one } // If we get here, we didn't find any available channel. throw ResourceLimitExceededException("There are no channels available"); } void ConnectionImpl::handle(framing::AMQFrame& frame) { handler.outgoing(frame); } void ConnectionImpl::incoming(framing::AMQFrame& frame) { boost::shared_ptr<SessionImpl> s; { Mutex::ScopedLock l(lock); s = sessions[frame.getChannel()].lock(); } if (!s) { QPID_LOG(info, *this << " dropping frame received on invalid channel: " << frame); } else { s->in(frame); } } bool ConnectionImpl::isOpen() const { return handler.isOpen(); } void ConnectionImpl::open() { const std::string& protocol = handler.protocol; const std::string& host = handler.host; int port = handler.port; theIO().add(); connector.reset(Connector::create(protocol, theIO().poller(), version, handler, this)); connector->setInputHandler(&handler); connector->setShutdownHandler(this); try { std::string p = boost::lexical_cast<std::string>(port); connector->connect(host, p); } catch (const std::exception& e) { QPID_LOG(debug, "Failed to connect to " << protocol << ":" << host << ":" << port << " " << e.what()); connector.reset(); throw TransportFailure(e.what()); } connector->init(); // Enable heartbeat if requested uint16_t heartbeat = static_cast<ConnectionSettings&>(handler).heartbeat; if (heartbeat) { // Set connection timeout to be 2x heart beat interval and setup timer heartbeatTask = new HeartbeatTask(heartbeat * 2 * TIME_SEC, *this); handler.setRcvTimeoutTask(heartbeatTask); theTimer().add(heartbeatTask); } // If the connect fails then the connector is cleaned up either when we try to connect again // - in that case in connector.reset() above; // - or when we are deleted try { handler.waitForOpen(); QPID_LOG(info, *this << " connected to " << protocol << ":" << host << ":" << port); } catch (const Exception&) { connector->checkVersion(version); throw; } // If the SASL layer has provided an "operational" userId for the connection, // put it in the negotiated settings. const std::string& userId(handler.getUserId()); if (!userId.empty()) handler.username = userId; //enable security layer if one has been negotiated: std::auto_ptr<SecurityLayer> securityLayer = handler.getSecurityLayer(); if (securityLayer.get()) { QPID_LOG(debug, *this << " activating security layer"); connector->activateSecurityLayer(securityLayer); } else { QPID_LOG(debug, *this << " no security layer in place"); } } void ConnectionImpl::timeout() { connector->abort(); } void ConnectionImpl::close() { if (heartbeatTask) heartbeatTask->cancel(); // close() must be idempotent and no-throw as it will often be called in destructors. if (handler.isOpen()) { try { handler.close(); closed(CLOSE_CODE_NORMAL, "Closed by client"); } catch (...) {} } assert(!handler.isOpen()); } template <class F> void ConnectionImpl::closeInternal(const F& f) { if (heartbeatTask) { heartbeatTask->cancel(); } { Mutex::ScopedUnlock u(lock); connector->close(); } //notifying sessions of failure can result in those session being //deleted which in turn results in a call to erase(); this can //even happen on this thread, when 's' goes out of scope //below. Using a copy prevents the map being modified as we //iterate through. SessionMap copy; sessions.swap(copy); for (SessionMap::iterator i = copy.begin(); i != copy.end(); ++i) { boost::shared_ptr<SessionImpl> s = i->second.lock(); if (s) f(s); } } void ConnectionImpl::closed(uint16_t code, const std::string& text) { Mutex::ScopedLock l(lock); setException(new ConnectionException(ConnectionHandler::convert(code), text)); closeInternal(boost::bind(&SessionImpl::connectionClosed, _1, code, text)); } void ConnectionImpl::shutdown() { if (!handler.isClosed()) { failedConnection(); } bool canDelete; { Mutex::ScopedLock l(lock); //association with IO thread is now ended shutdownComplete = true; //If we have already been released, we can now delete ourselves canDelete = released; } if (canDelete) delete this; } void ConnectionImpl::release() { bool isActive; { Mutex::ScopedLock l(lock); isActive = connector && !shutdownComplete; } //If we are still active - i.e. associated with an IO thread - //then we cannot delete ourselves yet, but must wait for the //shutdown callback which we can trigger by calling //connector.close() if (isActive) { connector->close(); bool canDelete; { Mutex::ScopedLock l(lock); released = true; canDelete = shutdownComplete; } if (canDelete) delete this; } else { delete this; } } static const std::string CONN_CLOSED("Connection closed"); void ConnectionImpl::failedConnection() { if ( failureCallback ) failureCallback(); if (handler.isClosed()) return; bool isClosing = handler.isClosing(); bool isOpen = handler.isOpen(); std::ostringstream msg; msg << *this << " closed"; // FIXME aconway 2008-06-06: exception use, amqp0-10 does not seem to have // an appropriate close-code. connection-forced is not right. handler.fail(msg.str());//ensure connection is marked as failed before notifying sessions // At this point if the object isn't open and isn't closing it must have failed to open // so we can't do the rest of the cleanup if (!isClosing && !isOpen) return; Mutex::ScopedLock l(lock); closeInternal(boost::bind(&SessionImpl::connectionBroke, _1, msg.str())); setException(new TransportFailure(msg.str())); } void ConnectionImpl::erase(uint16_t ch) { Mutex::ScopedLock l(lock); sessions.erase(ch); } const ConnectionSettings& ConnectionImpl::getNegotiatedSettings() { return handler; } std::vector<qpid::Url> ConnectionImpl::getInitialBrokers() { return handler.knownBrokersUrls; } boost::shared_ptr<SessionImpl> ConnectionImpl::newSession(const std::string& name, uint32_t timeout, uint16_t channel) { boost::shared_ptr<SessionImpl> simpl(new SessionImpl(name, shared_from_this())); addSession(simpl, channel); simpl->open(timeout); return simpl; } std::ostream& operator<<(std::ostream& o, const ConnectionImpl& c) { if (c.connector) return o << "Connection " << c.connector->getIdentifier(); else return o << "Connection <not connected>"; } void shutdown() { theIO().poller()->shutdown(); } }} // namespace qpid::client
30.550439
129
0.646257
[ "object", "vector" ]
4c2fe20af7c70df61b7e70aa0c3f9c66734b4724
1,840
cpp
C++
src/Barra.cpp
IgVelasco/Marvel_Vs_Capcom
a714453d1cba9596c1fdc99383a0228e62334cf7
[ "MIT" ]
null
null
null
src/Barra.cpp
IgVelasco/Marvel_Vs_Capcom
a714453d1cba9596c1fdc99383a0228e62334cf7
[ "MIT" ]
null
null
null
src/Barra.cpp
IgVelasco/Marvel_Vs_Capcom
a714453d1cba9596c1fdc99383a0228e62334cf7
[ "MIT" ]
1
2020-05-06T23:30:36.000Z
2020-05-06T23:30:36.000Z
/* * Barra.cpp * * Created on: 21 jun. 2019 * Author: caropistillo */ #include "Barra.h" #include<iostream> const int WIDTH_BAR = 259; const int HEIGHT_BAR = 17; const int POS_X_LEFT = 88; const int POS_X_RIGHT = 453; const int POS_Y_CURRENT = 88; const int POS_Y_SECONDARY = 61; const Uint8 SECONDARY_RED = 255; const Uint8 SECONDARY_GREEN = 200; const Uint8 SECONDARY_BLUE = 000; Barra::Barra() { this->width = WIDTH_BAR; this->height = HEIGHT_BAR; this->health = 1; } Barra::~Barra() { // TODO Auto-generated destructor stub } void Barra::render(SDL_Renderer* m_Renderer, SDL_Color frontColor, SDL_Color backColor) { health = health > 1.f ? 1.f : health < 0.f ? 0.f : health; SDL_Color old; SDL_GetRenderDrawColor(m_Renderer, &old.r, &old.g, &old.g, &old.a); SDL_Rect bgrect = { posX, posY, width, height }; SDL_SetRenderDrawColor(m_Renderer, backColor.r, backColor.g, backColor.b, backColor.a); SDL_RenderFillRect(m_Renderer, &bgrect); SDL_SetRenderDrawColor(m_Renderer, frontColor.r, frontColor.g, frontColor.b, frontColor.a); SDL_Rect fgrect = { hx, posY, hw, height }; SDL_RenderFillRect(m_Renderer, &fgrect); SDL_SetRenderDrawColor(m_Renderer, old.r, old.g, old.b, old.a); } SDL_Color Barra::color(Uint8 r, Uint8 g, Uint8 b, Uint8 a) { SDL_Color col = {r,g,b,a}; return col; } void Barra::update(float life) { this->health = life/100; this->hw = (int) ((float) width * health); } void Barra::setBarra(bool left, bool isCurrent) { this->hw = (int) ((float) width * health); if(left) { this->posX = POS_X_LEFT; this->hx = this->posX; if(isCurrent) this->posY = POS_Y_CURRENT; else this->posY = POS_Y_SECONDARY; } else { this->posX = POS_X_RIGHT; this->hx = posX + (width - hw); if(isCurrent) this->posY = POS_Y_CURRENT; else this->posY = POS_Y_SECONDARY; } }
21.904762
92
0.688587
[ "render" ]
4c346e44b92be68957f040523b19ee097f91e4b4
2,066
cpp
C++
aws-cpp-sdk-directconnect/source/model/GatewayType.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-directconnect/source/model/GatewayType.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-directconnect/source/model/GatewayType.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/directconnect/model/GatewayType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace DirectConnect { namespace Model { namespace GatewayTypeMapper { static const int virtualPrivateGateway_HASH = HashingUtils::HashString("virtualPrivateGateway"); static const int transitGateway_HASH = HashingUtils::HashString("transitGateway"); GatewayType GetGatewayTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == virtualPrivateGateway_HASH) { return GatewayType::virtualPrivateGateway; } else if (hashCode == transitGateway_HASH) { return GatewayType::transitGateway; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<GatewayType>(hashCode); } return GatewayType::NOT_SET; } Aws::String GetNameForGatewayType(GatewayType enumValue) { switch(enumValue) { case GatewayType::virtualPrivateGateway: return "virtualPrivateGateway"; case GatewayType::transitGateway: return "transitGateway"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace GatewayTypeMapper } // namespace Model } // namespace DirectConnect } // namespace Aws
29.098592
104
0.632139
[ "model" ]
4c36e09f418700f0b7a67497460754c344008bdb
8,230
cpp
C++
promethee/fast/promethee_fast.cpp
FMota0/PrometheeOptimization
6f6cd936e61d9d25e9bc0bb57d002506445a62cf
[ "MIT" ]
9
2018-09-17T03:09:38.000Z
2021-11-12T12:25:28.000Z
promethee/fast/promethee_fast.cpp
FMota0/PrometheeOptimization
6f6cd936e61d9d25e9bc0bb57d002506445a62cf
[ "MIT" ]
20
2018-08-16T11:53:12.000Z
2020-04-09T21:08:06.000Z
promethee/fast/promethee_fast.cpp
FMota0/PrometheeOptimization
6f6cd936e61d9d25e9bc0bb57d002506445a62cf
[ "MIT" ]
3
2018-08-06T19:53:31.000Z
2018-08-10T12:32:43.000Z
#include "promethee_fast.h" #include "../normalize.h" #include <iostream> #include "../inputreader.h" #include "../outputwriter.h" #include "../plibtiff.h" #include "../parse_directory.h" #include "../parse_args.h" void PrometheeFast::init(vector<string> args, int divideBy){ this->divideBy = divideBy; // Get type of function string type = getCmdOption(args, "-type"); if(!type.size() || (type != "linear" && type != "linearWithIndifference")){ cerr << "Error: incorrect arguments." << endl; exit(0); } this->isMax = hasFlag(args, "-ismax"); // args[0] should be the filename by now, since there is no more flags this->filename = args[0]; // args[1] is the weight this->weight = atof(args[1].c_str()); string chunkSize = getCmdOption(args, "-size"); if(!chunkSize.size()){ cerr << "Arguments is missing!" << endl; exit(1); } string start = getCmdOption(args, "-start"); if(!start.size()){ this->start = -1; }else{ this->start = atoi(start.c_str()); } string end = getCmdOption(args, "-end"); if(!end.size()){ this->end = 1e9; }else{ this->end = atoi(end.c_str()); } // the remaining args are function args vector<ldouble> params; for(int i = 2; i < args.size(); i++) params.push_back(atof(args[i].c_str())); if(type == "linear"){ this->p = params[0]; this->q = 0; }else{ this->p = params[0]; this->q = params[1]; } std::cout << "End of Promethee Initialization" << std::endl; } void PrometheeFast::findFirst(PixelReader &pr, int &beginLine, int &beginColunm, ldouble const& firstValue){ bool found = false; int atualLine = this->start - 1; while(!found && atualLine >= 0){ TIFFReadScanline(this->input, pr.buffer, atualLine); int ini = 0, fim = this->width - 1; while(ini <= fim){ int m = (ini + fim) / 2; if(pr.readPixel(m) + this->p < firstValue){ ini = m + 1; found = true; }else{ beginLine = atualLine; beginColunm = m; fim = m - 1; } } atualLine--; } } void PrometheeFast::findLast(PixelReader &pr, int &beginLine, int &beginColunm, ldouble const& firstValue){ bool found = false; int atualLine = this->start; while(!found && atualLine < this->height){ TIFFReadScanline(this->input, pr.buffer, atualLine); int ini = 0, fim = this->width - 1; while(ini <= fim){ int m = (ini + fim) / 2; if(firstValue < pr.readPixel(m) - this->q){ fim = m - 1; found = true; }else{ beginLine = atualLine; beginColunm = m; ini = m + 1; } } atualLine++; } } void PrometheeFast::fillBuffer(ldouble buffer[], PixelReader &pr, int line){ TIFFReadScanline(this->input, pr.buffer, line); for(register int i = 0; i < this->width; i++) buffer[i] = pr.readPixel(i); } void PrometheeFast::process() { // Open input and get fields need to create similar file for output this->input = TIFFOpen(this->filename.c_str(), "rm"); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &this->width); TIFFGetField(input, TIFFTAG_IMAGELENGTH, &this->height); TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &this->sampleFormat); TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &this->samplePerPixel); std::cout << "Open file" << std::endl; // Define correct start/end this->start = max(0, min(this->start, this->height)); this->end = max(this->start, min(this->end, this->height)); // Create PixelReader Interface unsigned short byte_size = TIFFScanlineSize(input) / this->width; tdata_t line = _TIFFmalloc(TIFFScanlineSize(input)); PixelReader pr = PixelReader(this->sampleFormat, byte_size, line); TIFFReadScanline(input, line, this->start); // Creating initial -p and q ldouble totalSumMinus = 0, totalSumPlus = 0; int beginLine = this->start, beginColunm = 0; int lastLine = this->start, lastColunm = 0; ldouble startValue = pr.readPixel(0); findFirst(pr, beginLine, beginColunm, startValue); findLast(pr, lastLine, lastColunm, startValue); int begin2Line = beginLine, begin2Colunm = beginColunm; int last2Line = lastLine, last2Colunm = lastColunm; int qtdMinus = 0; int qtdPlus = 0; // Setup output files string interval = to_string(this->start) + "-" + to_string(this->end); TIFF *output = TIFFOpen(("out." + interval + "." + this->filename).c_str(), "w8m"); TIFFSetField(output, TIFFTAG_IMAGEWIDTH , this->width); TIFFSetField(output, TIFFTAG_IMAGELENGTH , end - start); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE , 64); TIFFSetField(output, TIFFTAG_SAMPLEFORMAT , 3); TIFFSetField(output, TIFFTAG_COMPRESSION , 1); TIFFSetField(output, TIFFTAG_PHOTOMETRIC , 1); TIFFSetField(output, TIFFTAG_ORIENTATION , 1); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, 1); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP , 1); TIFFSetField(output, TIFFTAG_RESOLUTIONUNIT , 1); TIFFSetField(output, TIFFTAG_XRESOLUTION , 1); TIFFSetField(output, TIFFTAG_YRESOLUTION , 1); TIFFSetField(output, TIFFTAG_PLANARCONFIG , PLANARCONFIG_CONTIG ); // Pointer to buffers int minusQPointer = begin2Line; int minusPPointer = beginLine; int plusQPointer = last2Line; int plusPPointer = lastLine; // Creating buffers ldouble output_line[this->width]; ldouble bufferMinusQ[this->width]; ldouble bufferMinusP[this->width]; ldouble bufferPlusQ[this->width]; ldouble bufferPlusP[this->width]; ldouble bufferInput[this->width]; fillBuffer(bufferMinusQ, pr, minusQPointer); fillBuffer(bufferMinusP, pr, minusPPointer); fillBuffer(bufferPlusQ, pr, plusQPointer); fillBuffer(bufferPlusP, pr, plusPPointer); std::cout << "Prepare to run" << std::endl; // Start 4-pointer strategy for(int i = this->start; i < this->end; i++){ fillBuffer(bufferInput, pr, i); for(int j = 0; j < this->width; j++){ // Go foward with -q pointer if(minusQPointer < this->height){ while(bufferMinusQ[begin2Colunm] + this->q < bufferInput[j]){ totalSumMinus += bufferMinusQ[begin2Colunm]; qtdMinus++; begin2Colunm++; if(begin2Colunm == this->width){ begin2Colunm = 0; minusQPointer++; if(minusQPointer == this->height)break; fillBuffer(bufferMinusQ, pr, minusQPointer); } } } // Go foward with -p pointer if(minusPPointer < this->height){ while(bufferMinusP[beginColunm] + this->p < bufferInput[j]){ totalSumMinus -= bufferMinusP[beginColunm]; qtdMinus--; beginColunm++; if(beginColunm == this->width){ beginColunm = 0; minusPPointer++; if(minusPPointer == this->height)break; fillBuffer(bufferMinusP, pr, minusPPointer); } } } // Go foward with q pointer if(plusQPointer < this->height){ while(bufferPlusQ[last2Colunm] - this->q < bufferInput[j]){ totalSumPlus -= bufferPlusQ[last2Colunm]; qtdPlus--; last2Colunm++; if(last2Colunm == this->width){ last2Colunm = 0; plusQPointer++; if(plusQPointer == this->height)break; fillBuffer(bufferPlusQ, pr, plusQPointer); } } } // Go foward with p pointer if(plusPPointer < this->height){ while(bufferPlusP[lastColunm] - this->p < bufferInput[j]){ totalSumPlus += bufferPlusP[lastColunm]; qtdPlus++; lastColunm++; if(lastColunm == this->width){ lastColunm = 0; plusPPointer++; if(plusPPointer == this->height)break; fillBuffer(bufferPlusP, pr, plusPPointer); } } } // After update all pointer, time to calculate flow ldouble plusFlow = ((minusPPointer * this->width) + (beginColunm)); plusFlow += ((abs(totalSumMinus - (qtdMinus * bufferInput[j])) - (this->q * (ldouble)qtdMinus)) / ((ldouble)this->p - this->q)); ldouble minusFlow = (this->height - plusPPointer) * (this->width) - (lastColunm + (plusPPointer != this->height)); minusFlow += ((abs(totalSumPlus - (qtdPlus * bufferInput[j])) - (this->q * (ldouble)qtdPlus)) / ((ldouble)this->p - this->q)); output_line[j] = ((plusFlow - minusFlow) * this->weight * (this->isMax ? 1.0 : -1.0)) / ((this->height * this->width) - 1.0); } TIFFWriteScanline(output, output_line, i - this->start); } std::cout << "Done promethee" << std::endl; TIFFClose(output); TIFFClose(input); }
30.481481
132
0.655043
[ "vector" ]
4c37d9605ca3d437bb3f971012490722b5911849
3,694
hpp
C++
include/tardisdb/semanticAnalyser/SemanticAnalyser.hpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
5
2021-01-15T16:59:59.000Z
2022-02-28T15:41:00.000Z
include/tardisdb/semanticAnalyser/SemanticAnalyser.hpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
null
null
null
include/tardisdb/semanticAnalyser/SemanticAnalyser.hpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
1
2021-06-22T04:53:38.000Z
2021-06-22T04:53:38.000Z
#include <string> #include <memory> #include <unordered_map> #include <unordered_set> #include "algebra/logical/operators.hpp" #include "foundations/Database.hpp" #include "semanticAnalyser/AnalyzingContext.hpp" #include "semanticAnalyser/ParserResult.hpp" #include "semanticAnalyser/JoinGraph.hpp" using namespace Algebra::Logical; namespace semanticalAnalysis { struct semantic_sql_error : std::runtime_error { //semantic or syntactic errors using std::runtime_error::runtime_error; }; class SemanticAnalyser { public: SemanticAnalyser(AnalyzingContext &context) : _context(context) {} virtual ~SemanticAnalyser() {}; virtual void verify() = 0; virtual void constructTree() = 0; protected: AnalyzingContext &_context; public: static std::unique_ptr<SemanticAnalyser> getSemanticAnalyser(AnalyzingContext &context); protected: static void construct_scans(AnalyzingContext& context, Relation &relation) { std::vector<Relation> relations; relations.push_back(relation); construct_scans(context,relations); } static void construct_scans(AnalyzingContext& context, std::vector<Relation> &relations); static void construct_selects(AnalyzingContext& context, std::vector<std::pair<Column,std::string>> &selections); }; // // StatementTypeAnalyser // class SelectAnalyser : public SemanticAnalyser { public: SelectAnalyser(AnalyzingContext &context) : SemanticAnalyser(context) {} void verify() override; void constructTree() override; private: static void construct_joins(AnalyzingContext & context); static void construct_join_graph(AnalyzingContext & context, SelectStatement *stmt); static void construct_join(AnalyzingContext &context, std::string &vertexName); }; class InsertAnalyser : public SemanticAnalyser { public: InsertAnalyser(AnalyzingContext &context) : SemanticAnalyser(context) {} void verify() override; void constructTree() override; }; class UpdateAnalyser : public SemanticAnalyser { public: UpdateAnalyser(AnalyzingContext &context) : SemanticAnalyser(context) {} void verify() override; void constructTree() override; }; class DeleteAnalyser : public SemanticAnalyser { public: DeleteAnalyser(AnalyzingContext &context) : SemanticAnalyser(context) {} void verify() override; void constructTree() override; }; class CreateTableAnalyser : public SemanticAnalyser { public: CreateTableAnalyser(AnalyzingContext &context) : SemanticAnalyser(context) {} void verify() override; void constructTree() override; }; class CreateBranchAnalyser : public SemanticAnalyser { public: CreateBranchAnalyser(AnalyzingContext &context) : SemanticAnalyser(context) {} void verify() override; void constructTree() override; }; class BranchAnalyser : public SemanticAnalyser { public: BranchAnalyser(AnalyzingContext &context) : SemanticAnalyser(context) {} void verify() override; void constructTree() override; std::string returnJSON(); }; class CopyTableAnalyser : public SemanticAnalyser { public: CopyTableAnalyser(AnalyzingContext &context) : SemanticAnalyser(context) {} void verify() override; void constructTree() override; static void dumpCallbackCSV(Native::Sql::SqlTuple *tuple); static void dumpCallbackTBL(Native::Sql::SqlTuple *tuple); }; }
31.305085
121
0.686519
[ "vector" ]
4c421bfbd03b613513e91023eb5498ba76e07d69
8,014
cpp
C++
GrpNVMDatasetMgmtCmd/prp1PRP2NR_r10b.cpp
jli860/tnvme
208943be96c0fe073ed97a7098c0b00a2776ebf9
[ "Apache-2.0" ]
34
2015-03-09T17:54:24.000Z
2022-02-03T03:40:08.000Z
GrpNVMDatasetMgmtCmd/prp1PRP2NR_r10b.cpp
jli860/tnvme
208943be96c0fe073ed97a7098c0b00a2776ebf9
[ "Apache-2.0" ]
13
2015-05-20T02:21:09.000Z
2019-02-13T19:57:20.000Z
GrpNVMDatasetMgmtCmd/prp1PRP2NR_r10b.cpp
jli860/tnvme
208943be96c0fe073ed97a7098c0b00a2776ebf9
[ "Apache-2.0" ]
53
2015-03-13T02:46:24.000Z
2021-11-17T07:34:04.000Z
/* * Copyright (c) 2011, Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/format.hpp> #include "prp1PRP2NR_r10b.h" #include "globals.h" #include "grpDefs.h" #include "../Queues/iocq.h" #include "../Queues/iosq.h" #include "../Queues/ce.h" #include "../Utils/io.h" #include "../Cmds/datasetMgmt.h" #define OUTER_LOOP_MAX 4096 #define INNER_LOOP_MAX 256 namespace GrpNVMDatasetMgmtCmd { PRP1PRP2NR_r10b::PRP1PRP2NR_r10b( string grpName, string testName) : Test(grpName, testName, SPECREV_10b) { // 63 chars allowed: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx mTestDesc.SetCompliance("revision 1.0b, section 6"); mTestDesc.SetShort( "Verify all combos of PRP1, PRP2, and Number of Ranges (NR)"); // No string size limit for the long description mTestDesc.SetLong( "For all namspcs from Identify.NN, issue multiple dataset mgmt cmds " "with DW11 = 0, and vary the following cmd parameters. Outer loop must " "iterate from 0 to 4KB representing the offset into the 1st memory " "page of the data payload. An inner loop will iterate from 0 to 255 " "representing the DW10.NR field for each cmd. Each buffer will " "initialize all ranges in the data payload identically, where every " "context attribute = 0, and the starting LBA plus the LBA length of " "each range must be divided equally to consume the entire address " "space of the current namspc spec'd by Identify.NCAP. Expect success " "for all cmds. NOTE: Before sending each cmd to dnvme, preset PRP2 to " "a random 64b number. If the buffer does not require usage of PRP2 the " "random number will be issued to the DUT, otherwise it will contain a " "valid ptr to memory. If PRP2 is not needed it is considered a rsvd " "field. All rsvd fields are treated identical and the recipient shall " "not check their value. Always initiate the random gen with seed 97 " "before this test starts."); } PRP1PRP2NR_r10b::~PRP1PRP2NR_r10b() { /////////////////////////////////////////////////////////////////////////// // Allocations taken from the heap and not under the control of the // RsrcMngr need to be freed/deleted here. /////////////////////////////////////////////////////////////////////////// } PRP1PRP2NR_r10b:: PRP1PRP2NR_r10b(const PRP1PRP2NR_r10b &other) : Test(other) { /////////////////////////////////////////////////////////////////////////// // All pointers in this object must be NULL, never allow shallow or deep // copies, see Test::Clone() header comment. /////////////////////////////////////////////////////////////////////////// } PRP1PRP2NR_r10b & PRP1PRP2NR_r10b::operator=(const PRP1PRP2NR_r10b &other) { /////////////////////////////////////////////////////////////////////////// // All pointers in this object must be NULL, never allow shallow or deep // copies, see Test::Clone() header comment. /////////////////////////////////////////////////////////////////////////// Test::operator=(other); return *this; } Test::RunType PRP1PRP2NR_r10b::RunnableCoreTest(bool preserve) { /////////////////////////////////////////////////////////////////////////// // All code contained herein must never permanently modify the state or // configuration of the DUT. Permanence is defined as state or configuration // changes that will not be restored after a cold hard reset. /////////////////////////////////////////////////////////////////////////// ConstSharedIdentifyPtr idCtrlrCap = gInformative->GetIdentifyCmdCtrlr(); uint64_t oncs = idCtrlrCap->GetValue(IDCTRLRCAP_ONCS); if ((oncs & ONCS_SUP_DSM_CMD) == 0) return RUN_FALSE; preserve = preserve; // Suppress compiler error/warning return RUN_TRUE; // This test is never destructive } void PRP1PRP2NR_r10b::RunCoreTest() { /** \verbatim * Assumptions: * 1) Test CreateResources_r10b has run prior. * \endverbatim */ string work; LOG_NRM("Initialize random seed"); srand(97); // Lookup objs which were created in a prior test within group SharedIOSQPtr iosq = CAST_TO_IOSQ(gRsrcMngr->GetObj(IOSQ_GROUP_ID)); SharedIOCQPtr iocq = CAST_TO_IOCQ(gRsrcMngr->GetObj(IOCQ_GROUP_ID)); LOG_NRM("Create memory to contain 256 dataset range defs"); SharedMemBufferPtr rangeMem = SharedMemBufferPtr(new MemBuffer()); send_64b_bitmask prpBitmask = (send_64b_bitmask)(MASK_PRP1_PAGE | MASK_PRP2_PAGE); SharedDatasetMgmtPtr datasetMgmtCmd = SharedDatasetMgmtPtr(new DatasetMgmt()); ConstSharedIdentifyPtr idCtrlr = gInformative->GetIdentifyCmdCtrlr(); for (uint64_t i = 1; i <= idCtrlr->GetValue(IDCTRLRCAP_NN); i++) { LOG_NRM("Processing namspc %ld", i); datasetMgmtCmd->SetNSID(i); ConstSharedIdentifyPtr idNamspc = gInformative->GetIdentifyCmdNamspc(i); uint64_t nsze = idNamspc->GetValue(IDNAMESPC_NSZE); for (int64_t pgOff = 0; pgOff < OUTER_LOOP_MAX; pgOff += 4) { // pow2 = {1, 2, 4, 8, 16, 32, 64, ...} for (uint64_t pow2 = 2; pow2 <= INNER_LOOP_MAX; pow2 <<= 1) { // nr = {(1, 2, 3), (3, 4, 5), (7, 8, 9), ...} for (uint32_t nr = (pow2 - 1); (nr <= (pow2 + 1)) && (nr <= pow2); nr++) { LOG_NRM("Issue dataset mgmt cmd for %d ranges", nr); datasetMgmtCmd->SetNR(nr - 1); // convert to 0-based rangeMem->InitOffset1stPage((nr * sizeof(RangeDef)), pgOff, true); datasetMgmtCmd->SetPrpBuffer(prpBitmask, rangeMem); LOG_NRM("Set random value for PRP2; dnvme could overwrite"); datasetMgmtCmd->SetDword(rand(), 8); datasetMgmtCmd->SetDword(rand(), 9); uint16_t timeout; if (gCmdLine.setAD) { datasetMgmtCmd->SetAD(true); timeout = 1000; } else timeout = 1; uint64_t slba = 0; RangeDef *rangePtr = (RangeDef *)rangeMem->GetBuffer(); for (uint32_t idx = 1; idx <= nr; idx++, rangePtr++) { rangePtr->slba = slba; slba += (nsze / nr); if ((idx == nr) && (nsze % nr)) { LOG_NRM("Handle odd number of namspc's"); rangePtr->length = ((nsze / nr) + (nsze % nr)); } else { rangePtr->length = (nsze / nr); } } bool enableLog = false; if ((pgOff % 512) == 0) enableLog = true; work = str(boost::format("offset%d.nr%d ") % pgOff % nr); // Spec does not explicitly state that the cmd must succeed CEStat status = IO::SendAndReapCmdIgnore(mGrpName, mTestName, CALC_TIMEOUT_ms(timeout), iosq, iocq, datasetMgmtCmd, work, enableLog); ProcessCE::PrintStatus(status); } } } } } } // namespace
39.673267
92
0.559521
[ "object" ]
4c49da7827bca450053ee535645ff09c2b274201
14,571
cpp
C++
cpp/test/src/Assert.cpp
julian-becker/moskito
fce92dec01a6015b4ea887fb416eb149d9117580
[ "BSL-1.0" ]
1
2015-11-11T12:54:32.000Z
2015-11-11T12:54:32.000Z
cpp/test/src/Assert.cpp
julian-becker/moskito
fce92dec01a6015b4ea887fb416eb149d9117580
[ "BSL-1.0" ]
3
2015-11-12T14:06:00.000Z
2015-11-12T14:06:40.000Z
cpp/test/src/Assert.cpp
simon-bourne/CppUnitTest
d8347f3b4cfe84f12893107757b4d26f8d6a6116
[ "BSL-1.0" ]
null
null
null
// // Copyright Simon Bourne 2015. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include "Enhedron/Test.h" #include "Enhedron/Assertion.h" #include "Enhedron/Util/Optional.h" #include <utility> #include <string> #include <vector> #include <stdexcept> #include <functional> #include <algorithm> namespace Enhedron { using Test::context; using Test::given; using Test::Check; using std::string; using std::vector; using std::move; using std::forward; using std::exception; using std::runtime_error; using std::logical_and; using std::logic_error; using std::is_same; using std::reference_wrapper; using std::count; using Util::optional; using namespace Assertion; class RecordFailures final: public FailureHandler { public: struct Failure { string expressionText; vector<Variable> variableList; }; private: optional<Failure> failure_; public: virtual ~RecordFailures() override {} virtual bool notifyPassing() const override { return false; } virtual void pass(optional<string> description, const string &expressionText, const vector <Variable> &variableList) override { } virtual void fail(optional<string> description, const string& expressionText, const vector<Variable>& variableList) override { if (failure_) { throw runtime_error("Multiple failures"); } failure_ = Failure{expressionText, variableList}; } const optional<Failure>& failure() { return failure_; } }; template<typename Exception, typename Expression, typename... ContextVariableList> void testAssertThrows( Out<FailureHandler> failureHandler, Expression &&expression, ContextVariableList &&... contextVariableList ) { CheckThrowsWithFailureHandler<Exception>(failureHandler, move(expression), move(contextVariableList)...); } class MoveTracker final: public NoCopy { public: MoveTracker() = default; MoveTracker(const MoveTracker&) = default; MoveTracker& operator=(const MoveTracker&) = default; MoveTracker(MoveTracker&& source) : moved_(source.moved_) { source.moved_ = true; } MoveTracker& operator=(MoveTracker&& source) { moved_ = source.moved_; source.moved_ = true; return *this; } bool moved() const { return moved_; } private: bool moved_ = false; }; template<typename Expression> void expectFailure(Check& check, Expression expression, const char* expressionText = nullptr) { RecordFailures recordFailures; try { CheckWithFailureHandler(out(recordFailures), move(expression)); auto& failure = recordFailures.failure(); if (check(VAR(bool(failure))) && expressionText) { check(VAR(failure->expressionText) == expressionText); } } catch (const exception& e){ check.fail(VAR(e.what())); } } template<typename Operator, typename Value> void testBooleanOperator(Check& check, Value lhs, Value rhs) { Operator op; bool result = op(lhs, rhs); if (result) { check(op(VAR(lhs), VAR(rhs))); check(op(lhs, VAR(rhs))); check(op(VAR(lhs), rhs)); } else { expectFailure(check, op(VAR(lhs), VAR(rhs))); expectFailure(check, op(lhs, VAR(rhs))); expectFailure(check, op(VAR(lhs), rhs)); } } template<typename Operator> void testBooleanOperator(Check& check) { testBooleanOperator<Operator>(check, false, false); testBooleanOperator<Operator>(check, false, true); testBooleanOperator<Operator>(check, true, false); testBooleanOperator<Operator>(check, true, true); } template<typename Operator, typename Value> void testOperator(Check& check, Value lhs, Value rhs) { Operator op; auto result = op(lhs, rhs); check(op(VAR(lhs), VAR(rhs)) == result); check(op(lhs, VAR(rhs)) == result); check(op(VAR(lhs), rhs) == result); } template<typename Operator> void testNumericOperator(Check& check) { for (int i = -10; i < 10; ++i) { for (int j = -10; j < 10; ++j) { testOperator<Operator>(check, i, j); } } } template<typename Operator> void testNonZeroDenominator(Check& check) { for (int i = -10; i < 10; ++i) { for (int j = -10; j < -1; ++j) { testOperator<Operator>(check, i, j); } for (int j = 1; j < 10; ++j) { testOperator<Operator>(check, i, j); } } } template<typename Exception, typename Expression> void expectException(Check& check, Expression expression, const char* expressionText) { RecordFailures recordFailures; try { testAssertThrows<Exception>(out(recordFailures), move(expression)); auto& failure = recordFailures.failure(); if (check(VAR(bool(failure))) && expressionText) { check(VAR(failure->expressionText) == expressionText); } } catch (const exception& e) { check.fail(VAR(e.what())); } } int sum3(int x, int y, int z) { return x + y + z; } int overloaded(int x) { return x; } double overloaded(double x) { return x + 1.0; } template<typename... Args> auto overloadedProxy(Args&&... args) { return makeFunction( "overloaded", [] (auto&&... args) { return overloaded(forward<decltype(args)>(args)...); } )(forward<Args>(args)...); } int id(int x) { return x; } bool equals0(int x) { return x == 0; } bool equals1(int x) { return x == 1; } static Test::Suite s("Assert", given("Success", [] (Check& check) { check(VAR(true)); check(! VAR(false)); check(! VAR(false) && !VAR(false)); check(VAR(sum3)(1, 2, 3) == 6); }), given("Failure", [] (Check& check) { expectFailure(check, VAR(false), "false"); expectFailure(check, VAR(false) || VAR(false), "(false || false)"); int a = 1; expectFailure(check, VAR(sum3)(VAR(a), 2, 3) == 7, "(sum3(a, 2, 3) == 7)"); }), given("Overloaded", [] (Check& check) { check(overloadedProxy(1) == overloaded(1)); check(overloadedProxy(1.0) == overloaded(1.0)); int a = 1; expectFailure(check, overloadedProxy(VAR(a)) == 2, "(overloaded(a) == 2)"); }), given("countMatching, check it works with lambda predicates", [] (Check& check) { vector<int> intVec{ 1, 2, 3 }; auto zeroMatcher = [] (const int value) { return value == 0; }; check(countMatching(intVec, [] (const int& value) { return value == 1; }) == VAR(1)); check(countMatching(intVec, zeroMatcher) == VAR(0)); expectFailure( check, countMatching(intVec, VAR(zeroMatcher)) == VAR(1), "(countMatching([1, 2, 3], zeroMatcher) == 1)" ); }), given("containerUtils", [] (Check& check) { const vector<int> intVec{ 1, 2, 3 }; const vector<int> constVec{ 1, 1, 1, 1 }; check.when("countEqual", [&] { check(countEqual(intVec, 1) == VAR(1)); check(countEqual(intVec, 0) == VAR(0)); expectFailure(check, countEqual(intVec, 0) == VAR(1), "(countEqual([1, 2, 3], 0) == 1)"); }); check.when("countMatching", [&] { check(countMatching(intVec, equals1) == VAR(1)); check(countMatching(intVec, equals0) == VAR(0)); expectFailure( check, countMatching(intVec, VAR(equals0)) == VAR(1), "(countMatching([1, 2, 3], equals0) == 1)" ); }); check.when("allAnyOrNone", [&] { check(allOf(constVec, VAR(equals1))); expectFailure(check, allOf(intVec, VAR(equals1)), "allOf([1, 2, 3], equals1)"); check(anyOf(intVec, VAR(equals1))); expectFailure(check, anyOf(intVec, VAR(equals0)), "anyOf([1, 2, 3], equals0)"); check(noneOf(intVec, VAR(equals0))); expectFailure(check, noneOf(intVec, VAR(equals1)), "noneOf([1, 2, 3], equals1)"); }); check.when("length", [&] { check(length(VAR(intVec)) == 3u); check(length(VAR(constVec)) == 4u); expectFailure(check, length(VAR(intVec)) == 0u, "(length(intVec) == 0)"); }); check.when("equalRanges", [&] { const vector<int> start{1, 2}; const vector<int> last{2, 3}; const vector<int> larger{1, 2, 3, 4}; const vector<int> smaller{0}; check.when("startsWith", [&] { check(startsWith(intVec, intVec)); check(startsWith(intVec, start)); check(!startsWith(intVec, last)); check(!startsWith(intVec, larger)); expectFailure(check, startsWith(intVec, VAR(smaller)), "startsWith([1, 2, 3], smaller)"); }); check.when("endsWith", [&] { check(endsWith(intVec, intVec)); check(!endsWith(intVec, start)); check(endsWith(intVec, last)); check(!endsWith(intVec, larger)); expectFailure(check, endsWith(intVec, VAR(smaller)), "endsWith([1, 2, 3], smaller)"); }); check.when("contains", [&] { check(contains(intVec, intVec)); check(contains(intVec, start)); check(contains(intVec, last)); check(!contains(intVec, larger)); expectFailure(check, contains(intVec, VAR(smaller)), "contains([1, 2, 3], smaller)"); }); }); }), given("ValueSemantics", [] (Check& check) { MoveTracker moveTracker; VAR(moveTracker); check("We don't steal the expression object", ! VAR(moveTracker.moved())); VAR([] (const MoveTracker&) {}) (moveTracker); check("We don't steal function arguments", ! VAR(moveTracker.moved())); // gcc sanitizers will hopefully pick up any stored refs to temporaries int a = 1; int b = 1; check("We don't store refs to temporaries", VAR(a + b) == 2); const int c = 1; check("Const is preserved on lvalue refs", VAR(c) == 1); namespace Conf = Assertion::Impl::Configurable; static_assert( is_same<decltype(VAR(a + b)), Conf::VariableValueExpression<int>>::value, "Temporaries are stored by value" ); static_assert( is_same<decltype(VAR(a)), Conf::VariableRefExpression<int>>::value, "Variables are stored by reference" ); const auto aConst = a; static_assert( is_same<decltype(VAR(aConst)), Conf::VariableRefExpression<const int>>::value, "const is preserved" ); static_assert( is_same< decltype(VAR(id)(a + b)), Conf::FunctionValue<reference_wrapper<int(int)>, int> >::value, "Temporaries are stored by value" ); static_assert( is_same< decltype(VAR(id)(a)), Conf::FunctionValue<reference_wrapper<int(int)>, int&> >::value, "Values are stored by reference" ); }), given("ThrowSucceeds", [] (Check& check) { RecordFailures recordFailures; testAssertThrows<exception>(out(recordFailures), VAR([] { throw runtime_error("test"); })()); testAssertThrows<runtime_error>(out(recordFailures), VAR([] { throw runtime_error("test"); })()); check( ! VAR(bool(recordFailures.failure()))); }), given("ThrowFails", [] (Check& check) { expectException<logic_error>( check, VAR([] { throw runtime_error("test"); })(), "[] { throw runtime_error(\"test\"); }() threw \"test\"" ); expectException<runtime_error>( check, VAR([] {} )(), "[] {}()" ); }), given("BinaryBoolean", [] (Check& check) { testBooleanOperator<std::logical_and<void>>(check); testBooleanOperator<std::logical_or<void>>(check); }), given("Comparison", [] (Check& check) { testNumericOperator<std::equal_to<void>>(check); testNumericOperator<std::not_equal_to<void>>(check); testNumericOperator<std::less<void>>(check); testNumericOperator<std::less_equal<void>>(check); testNumericOperator<std::greater<void>>(check); testNumericOperator<std::greater_equal<void>>(check); }), given("Arithmetic", [] (Check& check) { testNumericOperator<std::plus<void>>(check); testNumericOperator<std::minus<void>>(check); testNumericOperator<std::multiplies<void>>(check); testNonZeroDenominator<std::modulus<void>>(check); testNonZeroDenominator<std::divides<void>>(check); }), given("Bitwise", [] (Check& check) { testNumericOperator<std::bit_and<void>>(check); testNumericOperator<std::bit_or<void>>(check); testNumericOperator<std::bit_xor<void>>(check); }) ); }
35.280872
137
0.529545
[ "object", "vector" ]
4c4a4e6b5b55459ce297101a02a0b967de7fef01
1,165
hpp
C++
Scene/ObjectBvh2.hpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
null
null
null
Scene/ObjectBvh2.hpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
null
null
null
Scene/ObjectBvh2.hpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
null
null
null
#pragma once #include <Scene/Object.hpp> #ifdef GetObject #undef GetObject #endif class ObjectBvh2 { public: struct Primitive { AABB mBounds; Object* mObject; }; struct Node { AABB mBounds; // index of the first primitive inside this node uint32_t mStartIndex; // number of primitives inside this node uint32_t mCount; uint32_t mRightOffset; // 1st child is at node[index + 1], 2nd child is at node[index + mRightOffset] }; inline ObjectBvh2() {}; inline ~ObjectBvh2() {} const std::vector<Node>& Nodes() const { return mNodes; } Object* GetObject(uint32_t index) const { return mPrimitives[index].mObject; } inline AABB Bounds() { return mNodes.size() ? mNodes[0].mBounds : AABB(); } ENGINE_EXPORT void Build(Object** objects, uint32_t objectCount); ENGINE_EXPORT void FrustumCheck(const float4 frustum[6], std::vector<Object*>& objects, uint32_t mask); ENGINE_EXPORT Object* Intersect(const Ray& ray, float* t, bool any, uint32_t mask); ENGINE_EXPORT void DrawGizmos(CommandBuffer* commandBuffer, Camera* camera, Scene* scene); private: std::vector<Node> mNodes; std::vector<Primitive> mPrimitives; uint32_t mLeafSize; };
27.093023
104
0.733047
[ "object", "vector" ]
4c4acdb0e23c5f9bb94824210955cfd55a76528f
6,805
cpp
C++
Plugin/NodOSVRPlugin.cpp
Khwaab/OSVR-Nod
7624e4229961ddd0f152308161f3b1d964762e48
[ "Apache-2.0" ]
5
2015-11-04T04:03:08.000Z
2021-07-05T16:26:03.000Z
Plugin/NodOSVRPlugin.cpp
Khwaab/OSVR-Nod
7624e4229961ddd0f152308161f3b1d964762e48
[ "Apache-2.0" ]
5
2015-11-04T00:04:29.000Z
2016-06-29T20:59:33.000Z
Plugin/NodOSVRPlugin.cpp
Khwaab/OSVR-Nod
7624e4229961ddd0f152308161f3b1d964762e48
[ "Apache-2.0" ]
2
2015-11-05T01:03:54.000Z
2016-06-29T20:51:49.000Z
/** @file @brief Nod Plugin Implementation for OSVR Enables Nod Data to be sent from the Nod service into the OSVR server and used as an osvr object Exposes: 3 analog (joystick x, joystick y, trigger) 10 buttons 1 Pose (x, y and z are still in development but orientation works) these are exposed one per a nod device that this plugin detects. Note: currently hardware detection does not refresh, please pair your Nod devices before running the OSVR server. @date 2015 @author Nod, Inc <http://www.nod.com/> */ // Copyright 2015 Nod, 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. // Internal Includes #include <osvr/PluginKit/PluginKit.h> #include <osvr/PluginKit/AnalogInterfaceC.h> #include <osvr/PluginKit/ButtonInterfaceC.h> #include <osvr/PluginKit/TrackerInterfaceC.h> // Generated JSON header file #include "NodOSVR.h" #include "NodPlugin.h" #pragma comment(lib, "OpenSpatialDll.lib") // Library/third-party includes // - none // Standard includes #include <iostream> #define _USE_MATH_DEFINES #include <math.h> // Anonymous namespace to avoid symbol collision namespace { void euler(const float& pitch, const float& roll, const float& yaw, OSVR_OrientationState* state) { const float sinHalfYaw = (float)sin(yaw / 2.0f); const float cosHalfYaw = (float)cos(yaw / 2.0f); const float sinHalfPitch = (float)sin(pitch / 2.0f); const float cosHalfPitch = (float)cos(pitch / 2.0f); const float sinHalfRoll = (float)sin(roll / 2.0f); const float cosHalfRoll = (float)cos(roll / 2.0f); //W state->data[0] = cosHalfRoll * cosHalfPitch * cosHalfYaw + sinHalfRoll * sinHalfPitch * sinHalfYaw; //X state->data[1] = cosHalfRoll * sinHalfPitch * sinHalfYaw + cosHalfPitch * cosHalfYaw * sinHalfRoll; //Y state->data[2] = cosHalfRoll * cosHalfPitch * sinHalfYaw - sinHalfRoll * cosHalfYaw * sinHalfPitch; //Z state->data[3] = cosHalfYaw*sinHalfPitch*cosHalfRoll - sinHalfYaw*cosHalfPitch*sinHalfRoll; } class Backspin { public: Backspin(OSVR_PluginRegContext ctx, int deviceNumber) { /// Create the initialization options OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx); /// config channels osvrDeviceAnalogConfigure(opts, &m_analog, 3); osvrDeviceButtonConfigure(opts, &m_button, 10); osvrDeviceTrackerConfigure(opts, &m_orientation); /// Create the device token with the options m_dev.initAsync(ctx, std::to_string(deviceNumber).c_str(), opts); /// Send JSON descriptor m_dev.sendJsonDescriptor(NodOSVR); } osvr::pluginkit::DeviceToken m_dev; OSVR_AnalogDeviceInterface m_analog; OSVR_ButtonDeviceInterface m_button; OSVR_TrackerDeviceInterface m_orientation; OSVR_OrientationState lastOrientation; OSVR_PositionState lastPosition; }; std::vector<Backspin*> devices; void OpenSpatialEventFired(NodEvent ev) { if (ev.type == EventType::ServiceReady) { std::cout << "[NOD PLUGIN] Service Ready" << std::endl; for (int i = 0; i < NodNumRings(); i++) { NodSubscribe(Modality::GameControlMode, NodGetRingName(i)); NodSubscribe(Modality::ButtonMode, NodGetRingName(i)); NodSubscribe(Modality::EulerMode, NodGetRingName(i)); } NodSubscribe(Modality::TranslationMode, NodGetRingName(0)); } if (ev.type == EventType::AnalogData) { Backspin* dev = devices.at(ev.sender); OSVR_AnalogState analogval[3]; analogval[0] = ev.trigger; analogval[1] = ev.x; analogval[2] = ev.y; osvrDeviceAnalogSetValues(dev->m_dev, dev->m_analog, analogval, 3); } if (ev.type == EventType::Button) { Backspin* dev = devices.at(ev.sender); int index = ev.buttonID; int val = (ev.buttonState == UP) ? 0 : 1; osvrDeviceButtonSetValue(dev->m_dev, dev->m_button, val, index); } if (ev.type == EventType::EulerAngles) { Backspin* dev = devices.at(ev.sender); OSVR_OrientationState orientationval; euler(-ev.roll, -ev.pitch, ev.yaw, &orientationval); OSVR_Pose3 pose; pose.rotation = orientationval; pose.translation = dev->lastPosition; dev->lastOrientation = orientationval; osvrDeviceTrackerSendPose(dev->m_dev, dev->m_orientation, &pose, 0); } if (ev.type == EventType::Translation) { Backspin* dev = devices.at(0); OSVR_PositionState positionval; positionval.data[0] = -1*ev.xf/1000; positionval.data[1] = ev.yf/1000; positionval.data[2] = -1*ev.zf/1000; OSVR_Pose3 pose; pose.translation = positionval; pose.rotation = dev->lastOrientation; dev->lastPosition = positionval; osvrDeviceTrackerSendPose(dev->m_dev, dev->m_orientation, &pose, 0); } } class HardwareDetection { public: HardwareDetection() : m_found(false) { NodInitialize(OpenSpatialEventFired); } OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { std::cout << "[NOD PLUGIN] Got a hardware detection request" << std::endl; if (!m_found) { if (NodNumRings() > 0) { std::cout << "[NOD PLUGIN] found device" << std::endl; for (int i = 0; i < NodNumRings(); i++) { Backspin* dev = new Backspin(ctx, i); devices.push_back(dev); osvr::pluginkit::registerObjectForDeletion( ctx, dev); m_found = true; } } else { std::cout << "[NOD PLUGIN]: no devices found" << std::endl; } } return OSVR_RETURN_SUCCESS; } private: /// @brief Have we found our device yet? (this limits the plugin to one /// instance) bool m_found; }; } // namespace OSVR_PLUGIN(com_osvr_example_selfcontained) { osvr::pluginkit::PluginContext context(ctx); /// Register a detection callback function object. context.registerHardwareDetectCallback(new HardwareDetection()); return OSVR_RETURN_SUCCESS; }
32.874396
97
0.646877
[ "object", "vector" ]
4c553cd9f01a0409a689802f1edc6fffee7f52af
7,295
cpp
C++
demos/omicron/src/mesh_helpers.cpp
bcrist/omicron
9a2917f0bc8d550f471c2b4a19ef6eb91a894717
[ "MIT" ]
null
null
null
demos/omicron/src/mesh_helpers.cpp
bcrist/omicron
9a2917f0bc8d550f471c2b4a19ef6eb91a894717
[ "MIT" ]
null
null
null
demos/omicron/src/mesh_helpers.cpp
bcrist/omicron
9a2917f0bc8d550f471c2b4a19ef6eb91a894717
[ "MIT" ]
null
null
null
#include "mesh_helpers.hpp" #include "mesh_manager.hpp" #include <cassert> namespace o { ////////////////////////////////////////////////////////////////////////////// void update_verts(Buf<Vertex> verts, const TextureRegion& region, RGBA color, F32 depth) { Vertex* v = verts.get(); assert(verts.size() >= 4); vec2 down = unit_axis(region.down); vec2 right = unit_axis(region.right); vec2 center = region.tex_bounds.center(); vec2 dim = region.tex_bounds.dim * 0.5f; v[0].color = color; v[0].tc = center + down * dim.y + right * -dim.x; v[0].pos = vec3(region.display_bounds.top_left(), depth); v[1].color = color; v[1].tc = center + down * -dim.y + right * -dim.x; v[1].pos = vec3(region.display_bounds.bottom_left(), depth); v[2].color = color; v[2].tc = center + down * -dim.y + right * dim.x; v[2].pos = vec3(region.display_bounds.bottom_right(), depth); v[3].color = color; v[3].tc = center + down * dim.y + right * dim.x; v[3].pos = vec3(region.display_bounds.top_right(), depth); } ////////////////////////////////////////////////////////////////////////////// void update_verts(Buf<Vertex> verts, const TextureRegion& region, vec2 baked_offset, F32 baked_scale, RGBA color, F32 depth) { update_verts(std::move(verts), region, vec3(baked_offset, depth), baked_scale, color); } ////////////////////////////////////////////////////////////////////////////// void update_verts(Buf<Vertex> verts, const TextureRegion& region, vec2 baked_offset, vec2 baked_scale, RGBA color, F32 depth) { update_verts(std::move(verts), region, vec3(baked_offset, depth), baked_scale, color); } ////////////////////////////////////////////////////////////////////////////// void update_verts(Buf<Vertex> verts, const TextureRegion& region, vec3 baked_offset, F32 baked_scale, RGBA color) { Vertex* v = verts.get(); assert(verts.size() >= 4); vec2 down = unit_axis(region.down); vec2 right = unit_axis(region.right); vec2 center = region.tex_bounds.center(); vec2 dim = region.tex_bounds.dim * 0.5f; v[0].color = color; v[0].tc = center + down * dim.y + right * -dim.x; v[0].pos = baked_offset + vec3(baked_scale * region.display_bounds.top_left(), 0); v[1].color = color; v[1].tc = center + down * -dim.y + right * -dim.x; v[1].pos = baked_offset + vec3(baked_scale * region.display_bounds.bottom_left(), 0); v[2].color = color; v[2].tc = center + down * -dim.y + right * dim.x; v[2].pos = baked_offset + vec3(baked_scale * region.display_bounds.bottom_right(), 0); v[3].color = color; v[3].tc = center + down * dim.y + right * dim.x; v[3].pos = baked_offset + vec3(baked_scale * region.display_bounds.top_right(), 0); } ////////////////////////////////////////////////////////////////////////////// void update_verts(Buf<Vertex> verts, const TextureRegion& region, vec3 baked_offset, vec2 baked_scale, RGBA color) { Vertex* v = verts.get(); assert(verts.size() >= 4); vec2 down = unit_axis(region.down); vec2 right = unit_axis(region.right); vec2 center = region.tex_bounds.center(); vec2 dim = region.tex_bounds.dim * 0.5f; v[0].color = color; v[0].tc = center + down * dim.y + right * -dim.x; v[0].pos = baked_offset + vec3(baked_scale * region.display_bounds.top_left(), 0); v[1].color = color; v[1].tc = center + down * -dim.y + right * -dim.x; v[1].pos = baked_offset + vec3(baked_scale * region.display_bounds.bottom_left(), 0); v[2].color = color; v[2].tc = center + down * -dim.y + right * dim.x; v[2].pos = baked_offset + vec3(baked_scale * region.display_bounds.bottom_right(), 0); v[3].color = color; v[3].tc = center + down * dim.y + right * dim.x; v[3].pos = baked_offset + vec3(baked_scale * region.display_bounds.top_right(), 0); } ////////////////////////////////////////////////////////////////////////////// Mesh text_mesh(MeshManager& mm, const Texture& tex, const S& text, RGBA color, vec2 offset, F32 scale, F32 depth) { Mesh mesh = mm.obtain(( U32 ) text.size()); mesh.texture_glid(tex.glid()); text_mesh_append(mesh, tex, text, color, offset, scale, depth); return mesh; } ////////////////////////////////////////////////////////////////////////////// Mesh text_mesh(MeshManager& mm, const Texture& tex, const S& text, RGBA color, vec2 offset, vec2 scale, F32 depth) { Mesh mesh = mm.obtain(( U32 ) text.size()); text_mesh_append(mesh, tex, text, color, offset, scale, depth); return mesh; } ////////////////////////////////////////////////////////////////////////////// std::pair<rect, rect> text_mesh_append(Mesh& mesh, const Texture& tex, const S& text, RGBA color, vec2 offset, F32 scale, F32 depth) { Buf<Vertex> verts = mesh.verts(); assert(mesh.texture_glid() == 0 || mesh.texture_glid() == tex.glid()); assert(verts.size() >= mesh.size() + 4 * text.size()); mesh.texture_glid(tex.glid()); rect em_box_bounds; rect glyph_bounds; em_box_bounds.offset = offset; if (!text.empty()) { std::size_t vi = mesh.size(); vec3 baked_offset = vec3(offset, depth); for (auto c : text) { TextureRegion region = tex.region(Id(( U8 ) c)); update_verts(sub_buf(verts, vi), region, baked_offset, scale, color, depth); baked_offset += vec3(scale * region.advance, 0); if (c == '\n') { baked_offset.x = offset.x; } vi += 4; em_box_bounds = em_box_bounds.union_bounds(baked_offset); } Vertex* v = verts.get() + mesh.size(); glyph_bounds = glyph_bounds.union_bounds(v->pos); ++v; for (std::size_t i = 1, end = 4 * text.size(); i < end; ++i) { glyph_bounds = glyph_bounds.union_bounds(v->pos); ++v; } } mesh.size(mesh.size() + 4 * ( U32 ) text.size()); return std::make_pair(em_box_bounds, glyph_bounds); } ////////////////////////////////////////////////////////////////////////////// std::pair<rect, rect> text_mesh_append(Mesh& mesh, const Texture& tex, const S& text, RGBA color, vec2 offset, vec2 scale, F32 depth) { Buf<Vertex> verts = mesh.verts(); assert(mesh.texture_glid() == 0 || mesh.texture_glid() == tex.glid()); assert(verts.size() >= mesh.size() + 4 * text.size()); mesh.texture_glid(tex.glid()); rect em_box_bounds; rect glyph_bounds; em_box_bounds.offset = offset; if (!text.empty()) { std::size_t vi = 4 * mesh.size(); vec3 baked_offset = vec3(offset, depth); for (auto c : text) { TextureRegion region = tex.region(Id(c)); update_verts(sub_buf(verts, vi), region, baked_offset, scale, color, depth); baked_offset += vec3(scale * region.advance, 0); if (c == '\n') { baked_offset.x = offset.x; } vi += 4; em_box_bounds = em_box_bounds.union_bounds(baked_offset); } Vertex* v = verts.get() + mesh.size(); glyph_bounds = glyph_bounds.union_bounds(v->pos); ++v; for (std::size_t i = 1, end = 4 * text.size(); i < end; ++i) { glyph_bounds = glyph_bounds.union_bounds(v->pos); ++v; } } mesh.size(mesh.size() + 4 * ( U32 ) text.size()); return std::make_pair(em_box_bounds, glyph_bounds); } } // o
37.030457
135
0.569157
[ "mesh" ]
4c574927337dd5a98ba0c6fb06fe415b8ea11396
2,959
cpp
C++
solutions/LeetCode/C++/546.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/546.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/546.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 8 ms submission class Solution { public: struct CNode{ int color; int n; CNode(int c, int num) : color(c), n(num) {}; }; int getRemovePoints(CNode preNode, int l, int r,vector<CNode> &cnVec, vector<vector<int>> &points) { int n = cnVec.size(); if(r >= n || l > r) return preNode.n * preNode.n; if(preNode.n == 0) { if(points[l][r] != -1) return points[l][r]; preNode.color = cnVec[l].color; preNode.n = cnVec[l].n; points[l][r] = getRemovePoints(preNode, l+1, r, cnVec, points); return points[l][r]; } if(preNode.color == cnVec[l].color) { preNode.n += cnVec[l].n; return getRemovePoints(preNode, l+1, r, cnVec, points); } //pre color != first color int maxp = preNode.n * preNode.n + getRemovePoints(CNode(0,0), l, r, cnVec, points); for(int i=l+1; i<=r; ++i) { if(preNode.color == cnVec[i].color) { maxp = max(maxp, getRemovePoints(preNode, i, r, cnVec, points) + getRemovePoints(CNode(0,0), l, i-1, cnVec, points)); } } return maxp; } int removeBoxes(vector<int>& boxes) { vector<CNode> cnVec; int curColor = 0; int nc = 0; for(int i=0; i < boxes.size(); ++i) { if(boxes[i] != curColor) { if(nc > 0) { CNode node(curColor, nc); cnVec.push_back(node); } nc = 1; curColor = boxes[i]; }else{ ++nc; } } CNode node(curColor, nc); cnVec.push_back(node); CNode preNode(0, 0); int n = cnVec.size(); vector<vector<int>> points(n, vector<int>(n, -1)); return getRemovePoints(preNode, 0, n-1, cnVec, points); } }; __________________________________________________________________________________________________ sample 13200 kb submission const int maxn = 101; class Solution { private: public: int dfs(vector<int>& boxes,int (&d)[maxn][maxn][maxn],int i, int j, int k) { if (d[i][j][k]>0) return d[i][j][k]; if (i > j) return 0; while (i<j && boxes[i+1]==boxes[i]) i++,k++; d[i][j][k]=(k+1)*(k+1)+dfs(boxes,d,i+1,j,0); for (int m=i+1; m<=j; ++m) { if (boxes[i]!=boxes[m]) continue; d[i][j][k]=max(d[i][j][k],dfs(boxes,d,i+1,m-1,0)+dfs(boxes,d,m,j,k+1)); } return d[i][j][k]; } int removeBoxes(vector<int>& boxes) { int n = boxes.size(); int d[maxn][maxn][maxn]={}; return dfs(boxes,d,0, n-1, 0); } }; __________________________________________________________________________________________________
32.877778
133
0.526191
[ "vector" ]
4c59110b1b56a62b1e37edf9aa0d5856e1f0109c
4,213
cpp
C++
src/main.cpp
TaskForce47/TF47-Insurgency-Intercept
e6ac8218371fa47f7e90213af049be4dc5fb6c96
[ "MIT" ]
null
null
null
src/main.cpp
TaskForce47/TF47-Insurgency-Intercept
e6ac8218371fa47f7e90213af049be4dc5fb6c96
[ "MIT" ]
null
null
null
src/main.cpp
TaskForce47/TF47-Insurgency-Intercept
e6ac8218371fa47f7e90213af049be4dc5fb6c96
[ "MIT" ]
null
null
null
#pragma once #include "intercept.hpp" #include "sector.hpp" #include "sector_manager.hpp" #include "../json/single_include/nlohmann/json.hpp" using namespace intercept; intercept::types::registered_sqf_function nular_func_example; intercept::types::registered_sqf_function nular_func_start; intercept::types::registered_sqf_function binary_func_generate_sectors; intercept::types::registered_sqf_function nular_func_cleanup_sectors; intercept::types::registered_sqf_function unary_func_generate_sectors; intercept::types::registered_sqf_function binary_func_get_adjacent_sectors; bool enableFrameNumbers = false; mission::sector_manager manager; int intercept::api_version() { //This is required for the plugin to work. return INTERCEPT_SDK_API_VERSION; } void intercept::register_interfaces() { } void intercept::on_frame() { if(enableFrameNumbers) sqf::system_chat(fmt::format("Frame number {}", sqf::diag_frameno())); } void intercept::post_init() { sqf::diag_log(fmt::format("Game world is: {} and its size is", sqf::world_name(), sqf::world_size())); } game_value generate_sectors(game_value_parameter sector_length, game_value_parameter building_threshold) { intercept::sqf::system_chat(fmt::format("length: {}, threshold: {}", static_cast<int>(sector_length), static_cast<int>(building_threshold))); manager.generate_sectors(); return "Done!"; } game_value cleanup_sectors() { manager.cleanup(); return "Done!"; } game_value find_closest_sector(game_value_parameter pos) { mission::sector* result = manager.find_nearest_sector(pos); return {result->pos->x, result->pos->y}; } game_value get_adjacent_sectors(game_state& gs, game_value_parameter left, game_value_parameter right) { if (right.size() < 2) throw; const vector3 left_arg = left; auto result = manager.find_adjacent_sectors(vector2_base<int>(left_arg.x, left_arg.y), right[0], right[1]); std::vector<vector3> output; for (auto value : result) { output.push_back(*value->pos); } return output; } game_value test_nular_fnc() { enableFrameNumbers = !enableFrameNumbers; if (enableFrameNumbers) return "enabled"; else return "disabled"; } game_value start_scan() { return manager.start_sector_scanner(); } void intercept::pre_start() { nular_func_example = intercept::client::host::register_sqf_command( "enableFrameDiag", "Enables or disables the output of the current frame number", userFunctionWrapper<test_nular_fnc>, intercept::types::GameDataType::STRING); nular_func_cleanup_sectors = intercept::client::host::register_sqf_command( "missionCleanupSectors", "cleans up all sector markers", userFunctionWrapper<cleanup_sectors>, game_data_type::STRING ); binary_func_generate_sectors = intercept::client::host::register_sqf_command( "missionGenerateSectors", "Generates new sectors", userFunctionWrapper<generate_sectors>, game_data_type::STRING, game_data_type::SCALAR, game_data_type::SCALAR ); unary_func_generate_sectors = intercept::client::host::register_sqf_command( "missionFindClosestSector", "finds the closest sector to a passed position", userFunctionWrapper<find_closest_sector>, game_data_type::ARRAY, game_data_type::ARRAY ); binary_func_get_adjacent_sectors = intercept::client::host::register_sqf_command( "missionGenerateSectors", "Generates new sectors", get_adjacent_sectors, game_data_type::ARRAY, game_data_type::ARRAY, game_data_type::ARRAY ); nular_func_start = intercept::client::host::register_sqf_command( "missionStartScan", "start background scan for sector activation", userFunctionWrapper<start_scan>, game_data_type::BOOL ); /* * _binary_func_get_adjacent_sectors = client::host::register_sqf_command( "missionGetAdjacentSectors", "Get all adjacent sectors in range passed", get_adjacent_sectors, game_data_type::ARRAY, game_data_type::ARRAY );*/ }
31.440299
142
0.717778
[ "vector" ]
4c62d5dea0073bc9e0af6abfa107f0b6310ac7bc
244
cpp
C++
render/render.cpp
AutoCraftProject/AutoCraft_Console
0477b234408a1262477db4e6ec0cf19ab909d221
[ "MIT" ]
1
2021-06-13T09:22:17.000Z
2021-06-13T09:22:17.000Z
render/render.cpp
AutoCraftProject/AutoCraft_Console
0477b234408a1262477db4e6ec0cf19ab909d221
[ "MIT" ]
null
null
null
render/render.cpp
AutoCraftProject/AutoCraft_Console
0477b234408a1262477db4e6ec0cf19ab909d221
[ "MIT" ]
null
null
null
#include "render.h" namespace Render { Renderer::Renderer() { buff = ""; } void Renderer::write(std::string word) { buff += word; } void Renderer::doRender(std::ostream& stream) { system("cls"); stream << buff; buff = ""; } }
14.352941
48
0.598361
[ "render" ]
4c674e50fc44304133666be21f5c557e332808f2
8,911
cpp
C++
Source/core/paint/SVGFilterPainter.cpp
prepare/Blink_only_permissive_lic_files
8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4
[ "BSD-3-Clause" ]
null
null
null
Source/core/paint/SVGFilterPainter.cpp
prepare/Blink_only_permissive_lic_files
8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4
[ "BSD-3-Clause" ]
null
null
null
Source/core/paint/SVGFilterPainter.cpp
prepare/Blink_only_permissive_lic_files
8b3acc51c7ae8b074d2e2b610d0d9295d9a1ecb4
[ "BSD-3-Clause" ]
null
null
null
// 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 "config.h" #include "core/paint/SVGFilterPainter.h" #include "core/layout/svg/LayoutSVGResourceFilter.h" #include "core/paint/CompositingRecorder.h" #include "core/paint/LayoutObjectDrawingRecorder.h" #include "core/paint/TransformRecorder.h" #include "platform/graphics/filters/SkiaImageFilterBuilder.h" #include "platform/graphics/filters/SourceGraphic.h" #include "platform/graphics/paint/CompositingDisplayItem.h" #include "platform/graphics/paint/DisplayItemList.h" #include "platform/graphics/paint/DrawingDisplayItem.h" namespace blink { static GraphicsContext* beginRecordingContent(GraphicsContext* context, FilterData* filterData) { ASSERT(filterData->m_state == FilterData::Initial); // For slimming paint we need to create a new context so the contents of the // filter can be drawn and cached. if (RuntimeEnabledFeatures::slimmingPaintEnabled()) { filterData->m_displayItemList = DisplayItemList::create(); filterData->m_context = adoptPtr(new GraphicsContext(filterData->m_displayItemList.get())); context = filterData->m_context.get(); } else { context->beginRecording(filterData->filter->filterRegion()); } filterData->m_state = FilterData::RecordingContent; return context; } static void endRecordingContent(GraphicsContext* context, FilterData* filterData) { ASSERT(filterData->m_state == FilterData::RecordingContent); // FIXME: maybe filterData should just hold onto SourceGraphic after creation? SourceGraphic* sourceGraphic = static_cast<SourceGraphic*>(filterData->builder->getEffectById(SourceGraphic::effectName())); ASSERT(sourceGraphic); // For slimming paint we need to use the context that contains the filtered // content. if (RuntimeEnabledFeatures::slimmingPaintEnabled()) { ASSERT(filterData->m_displayItemList); ASSERT(filterData->m_context); context = filterData->m_context.get(); context->beginRecording(filterData->filter->filterRegion()); filterData->m_displayItemList->commitNewDisplayItemsAndReplay(*context); } sourceGraphic->setPicture(context->endRecording()); // Content is cached by the source graphic so temporaries can be freed. if (RuntimeEnabledFeatures::slimmingPaintEnabled()) { filterData->m_displayItemList = nullptr; filterData->m_context = nullptr; } filterData->m_state = FilterData::ReadyToPaint; } static void paintFilteredContent(GraphicsContext* context, FilterData* filterData, SVGFilterElement* filterElement) { ASSERT(filterData->m_state == FilterData::ReadyToPaint); ASSERT(filterData->builder->getEffectById(SourceGraphic::effectName())); filterData->m_state = FilterData::PaintingFilter; SkiaImageFilterBuilder builder; RefPtr<SkImageFilter> imageFilter = builder.build(filterData->builder->lastEffect(), ColorSpaceDeviceRGB); FloatRect boundaries = filterData->filter->filterRegion(); context->save(); // Clip drawing of filtered image to the minimum required paint rect. FilterEffect* lastEffect = filterData->builder->lastEffect(); context->clipRect(lastEffect->determineAbsolutePaintRect(lastEffect->maxEffectRect())); if (filterElement->hasAttribute(SVGNames::filterResAttr)) { // Get boundaries in device coords. // FIXME: See crbug.com/382491. Is the use of getCTM OK here, given it does not include device // zoom or High DPI adjustments? FloatSize size = context->getCTM().mapSize(boundaries.size()); // Compute the scale amount required so that the resulting offscreen is exactly filterResX by filterResY pixels. float filterResScaleX = filterElement->filterResX()->currentValue()->value() / size.width(); float filterResScaleY = filterElement->filterResY()->currentValue()->value() / size.height(); // Scale the CTM so the primitive is drawn to filterRes. context->scale(filterResScaleX, filterResScaleY); // Create a resize filter with the inverse scale. AffineTransform resizeMatrix; resizeMatrix.scale(1 / filterResScaleX, 1 / filterResScaleY); imageFilter = builder.buildTransform(resizeMatrix, imageFilter.get()); } // See crbug.com/382491. if (!RuntimeEnabledFeatures::slimmingPaintEnabled()) { // If the CTM contains rotation or shearing, apply the filter to // the unsheared/unrotated matrix, and do the shearing/rotation // as a final pass. AffineTransform ctm = context->getCTM(); if (ctm.b() || ctm.c()) { AffineTransform scaleAndTranslate; scaleAndTranslate.translate(ctm.e(), ctm.f()); scaleAndTranslate.scale(ctm.xScale(), ctm.yScale()); ASSERT(scaleAndTranslate.isInvertible()); AffineTransform shearAndRotate = scaleAndTranslate.inverse(); shearAndRotate.multiply(ctm); context->setCTM(scaleAndTranslate); imageFilter = builder.buildTransform(shearAndRotate, imageFilter.get()); } } context->beginLayer(1, SkXfermode::kSrcOver_Mode, &boundaries, ColorFilterNone, imageFilter.get()); context->endLayer(); context->restore(); filterData->m_state = FilterData::ReadyToPaint; } GraphicsContext* SVGFilterPainter::prepareEffect(LayoutObject& object, GraphicsContext* context) { ASSERT(context); m_filter.clearInvalidationMask(); if (FilterData* filterData = m_filter.getFilterDataForLayoutObject(&object)) { // If the filterData already exists we do not need to record the content // to be filtered. This can occur if the content was previously recorded // or we are in a cycle. if (filterData->m_state == FilterData::PaintingFilter) filterData->m_state = FilterData::PaintingFilterCycleDetected; if (filterData->m_state == FilterData::RecordingContent) filterData->m_state = FilterData::RecordingContentCycleDetected; return nullptr; } OwnPtrWillBeRawPtr<FilterData> filterData = FilterData::create(); FloatRect targetBoundingBox = object.objectBoundingBox(); SVGFilterElement* filterElement = toSVGFilterElement(m_filter.element()); FloatRect filterRegion = SVGLengthContext::resolveRectangle<SVGFilterElement>(filterElement, filterElement->filterUnits()->currentValue()->enumValue(), targetBoundingBox); if (filterRegion.isEmpty()) return nullptr; // Create the SVGFilter object. FloatRect drawingRegion = object.strokeBoundingBox(); drawingRegion.intersect(filterRegion); bool primitiveBoundingBoxMode = filterElement->primitiveUnits()->currentValue()->enumValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX; filterData->filter = SVGFilter::create(enclosingIntRect(drawingRegion), targetBoundingBox, filterRegion, primitiveBoundingBoxMode); // Create all relevant filter primitives. filterData->builder = m_filter.buildPrimitives(filterData->filter.get()); if (!filterData->builder) return nullptr; FilterEffect* lastEffect = filterData->builder->lastEffect(); if (!lastEffect) return nullptr; lastEffect->determineFilterPrimitiveSubregion(ClipToFilterRegion); FilterData* data = filterData.get(); m_filter.setFilterDataForLayoutObject(&object, filterData.release()); return beginRecordingContent(context, data); } void SVGFilterPainter::finishEffect(LayoutObject& object, GraphicsContext* context) { ASSERT(context); FilterData* filterData = m_filter.getFilterDataForLayoutObject(&object); if (filterData) { // A painting cycle can occur when an FeImage references a source that // makes use of the FeImage itself. This is the first place we would hit // the cycle so we reset the state and continue. if (filterData->m_state == FilterData::PaintingFilterCycleDetected) filterData->m_state = FilterData::PaintingFilter; // Check for RecordingContent here because we may can be re-painting // without re-recording the contents to be filtered. if (filterData->m_state == FilterData::RecordingContent) endRecordingContent(context, filterData); if (filterData->m_state == FilterData::RecordingContentCycleDetected) filterData->m_state = FilterData::RecordingContent; } LayoutObjectDrawingRecorder recorder(*context, object, DisplayItem::SVGFilter, LayoutRect::infiniteIntRect()); if (recorder.canUseCachedDrawing()) return; if (filterData && filterData->m_state == FilterData::ReadyToPaint) paintFilteredContent(context, filterData, toSVGFilterElement(m_filter.element())); } }
44.333333
175
0.724049
[ "object" ]
4c68fc87a47cab7ce4356f112170625ab455b3b2
4,182
cpp
C++
src/std/builtins/typechecks.cpp
kalinochkind/scheme
5be2d1fa229adcda2959a8ce120beb153e00e521
[ "MIT" ]
null
null
null
src/std/builtins/typechecks.cpp
kalinochkind/scheme
5be2d1fa229adcda2959a8ce120beb153e00e521
[ "MIT" ]
1
2018-11-01T23:14:50.000Z
2019-04-19T15:41:33.000Z
src/std/builtins/typechecks.cpp
kalinochkind/scheme
5be2d1fa229adcda2959a8ce120beb153e00e521
[ "MIT" ]
null
null
null
#include <set> #include "std.h" static FunctionPackage package( { {"pair?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemePair>(l.front()); return (p && p != scheme_nil) ? scheme_true : scheme_false; }}}, {"symbol?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeSymbol>(l.front()); return p ? scheme_true : scheme_false; }}}, {"string?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeString>(l.front()); return p ? scheme_true : scheme_false; }}}, {"char?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeChar>(l.front()); return p ? scheme_true : scheme_false; }}}, {"number?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p1 = std::dynamic_pointer_cast<SchemeInt>(l.front()); if(p1) return scheme_true; auto p2 = std::dynamic_pointer_cast<SchemeFloat>(l.front()); return p2 ? scheme_true : scheme_false; }}}, {"environment?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeEnvironment>(l.front()); return p ? scheme_true : scheme_false; }}}, {"boolean?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeBool>(l.front()); return p ? scheme_true : scheme_false; }}}, {"vector?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeVector>(l.front()); return p ? scheme_true : scheme_false; }}}, {"procedure?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeProcedure>(l.front()); return p ? scheme_true : scheme_false; }}}, {"compound-procedure?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeCompoundProcedure>(l.front()); return p ? scheme_true : scheme_false; }}}, {"primitive-procedure?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemePrimitiveProcedure>(l.front()); return p ? scheme_true : scheme_false; }}}, {"list?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemePair>(l.front()); return p && p->list_length() >= 0 ? scheme_true : scheme_false; }}}, {"cell?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeCell>(l.front()); return p ? scheme_true : scheme_false; }}}, {"promise?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemePromise>(l.front()); return p ? scheme_true : scheme_false; }}}, {"weak-pair?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemeWeakPair>(l.front()); return p ? scheme_true : scheme_false; }}}, {"input-port?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemePort>(l.front()); return p && (p->type == port_type_t::INPUT || p->type == port_type_t::IO) ? scheme_true : scheme_false; }}}, {"output-port?", {1, 1, [](const std::list<std::shared_ptr<SchemeObject>> &l) { auto p = std::dynamic_pointer_cast<SchemePort>(l.front()); return p && (p->type == port_type_t::OUTPUT || p->type == port_type_t::IO) ? scheme_true : scheme_false; }}}, } );
53.615385
116
0.560976
[ "vector" ]
4c71a22f81201bd4ecd70b1557ae1105622fd09b
4,295
cpp
C++
test/Common/CommandLineArguments.Tests.cpp
HorphGerbInc/gametest
8c91a0823bcc84a0a75f8a70aed6040a92d28027
[ "MIT" ]
null
null
null
test/Common/CommandLineArguments.Tests.cpp
HorphGerbInc/gametest
8c91a0823bcc84a0a75f8a70aed6040a92d28027
[ "MIT" ]
null
null
null
test/Common/CommandLineArguments.Tests.cpp
HorphGerbInc/gametest
8c91a0823bcc84a0a75f8a70aed6040a92d28027
[ "MIT" ]
null
null
null
// Stdlib #include <map> // Test #include <catch.hpp> // Project #include <Common/CommandLineArguments.hpp> char* CStr(char *c ) { return c; } TEST_CASE("Can create on heap", "[CommandLineArguments]") { jerobins::common::CommandLineArguments *cli_ptr = new jerobins::common::CommandLineArguments(); REQUIRE(cli_ptr != nullptr); delete cli_ptr; } TEST_CASE("Can create on stack", "[CommandLineArguments]") { jerobins::common::CommandLineArguments cli; } TEST_CASE("Can create flags", "[CommandLineArguments]") { int argc = 2; char *argv[] = {(char*)"ERROR", (char*)"-debug"}; jerobins::common::CommandLineArguments cli; cli.AddFlag("debug"); REQUIRE(cli.FlagSet("debug") == false); cli.Parse(argc, argv); REQUIRE(cli.FlagSet("debug") == true); } struct CLIRun { std::vector<char *> args; std::vector<std::string> flags; std::vector<std::string> parameters; std::vector<std::string> setFlags; std::map<std::string, std::string> kvps; }; TEST_CASE("Can create parameters", "[CommandLineArguements]") { std::vector<CLIRun> runs = { { {(char*)"ERROR", (char*)"-Filename", (char*)"bob"}, // argv {}, // flags {"Filename"}, // parameters {}, // setFlags {{"Filename", "bob"}} // kvps }, { {(char*)"ERROR", (char*)"-Filename", (char*)"bob"}, // argv {"Debug"}, // flags {"Filename", "Name"}, // parameters {}, // setFlags {{"Filename", "bob"}} // kvps }, { {(char*)"ERROR", (char*)"-Filename", (char*)"bob", (char*)"-debug"}, // argv {"debug"}, // flags {"Filename", "Name"}, // parameters {"debug"}, // setFlags {{"Filename", "bob"}} // kvps }, { {(char*)"ERROR", (char*)"-Filename=bob", (char*)"debug"}, // argv {"debug"}, // flags {"Filename", "Name"}, // parameters {"debug"}, // setFlags {{"Filename", "bob"}} // kvps }, { {(char*)"ERROR", (char*)"Filename", (char*)"bob"}, // argv {}, // flags {"Filename", "Name"}, // parameters {}, // setFlags {{"Filename", "bob"}} // kvps }, { {(char*)"ERROR", (char*)"Filename=bob"}, // argv {}, // flags {"Filename", "Name"}, // parameters {}, // setFlags {{"Filename", "bob"}} // kvps }}; for (auto run : runs) { jerobins::common::CommandLineArguments cli; // Flags for (auto flag : run.flags) { cli.AddFlag(flag); REQUIRE(cli.FlagSet(flag) == false); } for (auto flag : run.flags) { REQUIRE(cli.FlagSet(flag) == false); } // Parameters for (auto parameter : run.parameters) { cli.AddParameter(parameter); REQUIRE(cli.ParameterSet(parameter) == false); for (auto flag : run.flags) { REQUIRE(cli.FlagSet(flag) == false); } } for (auto flag : run.flags) { REQUIRE(cli.FlagSet(flag) == false); } for (auto parameter : run.parameters) { REQUIRE(cli.ParameterSet(parameter) == false); } // Parse cli.Parse((int)run.args.size(), &run.args[0]); // Validate for (auto flag : run.setFlags) { REQUIRE(cli.FlagSet(flag) == true); } for (auto kvp : run.kvps) { REQUIRE(cli.ParameterSet(kvp.first) == true); if (cli.ParameterSet(kvp.first)) { REQUIRE(cli.ParameterValue(kvp.first) == kvp.second); } } for (auto parameter : run.parameters) { if (run.kvps.find(parameter) == run.kvps.end()) { REQUIRE(cli.ParameterSet(parameter) == false); } } } }
30.899281
87
0.460303
[ "vector" ]
4c725c9047e31fe37cf5317b7743aedd3a02a1a2
388
cpp
C++
MonoNative/mscorlib/System/mscorlib_System_ICloneable.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative/mscorlib/System/mscorlib_System_ICloneable.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative/mscorlib/System/mscorlib_System_ICloneable.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
#include <mscorlib/System/mscorlib_System_ICloneable.h> namespace mscorlib { namespace System { //Public Methods mscorlib::System::Object ICloneable::Clone() { MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System", "ICloneable", 0, NULL, "Clone", __mscorlib_System_ICloneable, 0, NULL, NULL, NULL); return mscorlib::System::Object(__result__); } } }
19.4
155
0.713918
[ "object" ]
4c7353a7b1b48545d3b991a3b7c0f3cf36ce0180
11,298
hpp
C++
include/pfs/timer.hpp
semenovf/modulus-lib
85a26b0a4284d91f52a47f8ce7858df9b9ef6b58
[ "MIT" ]
1
2019-12-23T13:50:12.000Z
2019-12-23T13:50:12.000Z
include/pfs/timer.hpp
semenovf/pfs-modulus
85a26b0a4284d91f52a47f8ce7858df9b9ef6b58
[ "MIT" ]
null
null
null
include/pfs/timer.hpp
semenovf/pfs-modulus
85a26b0a4284d91f52a47f8ce7858df9b9ef6b58
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2020 Vladislav Trifochkin // // This file is part of [pfs-modulus](https://github.com/semenovf/pfs-modulus) library. // // This code inspired from: // * https://codereview.stackexchange.com/questions/127552/portable-periodic-one-shot-timer-thread-follow-up // * https://github.com/stella-emu/stella/blob/master/src/common/timer_pool.hxx // * https://github.com/stella-emu/stella/blob/master/src/common/timer_pool.cxx // and adapted to requirements of `modulus` project. // // Changelog: // 2020.01.14 Initial version //////////////////////////////////////////////////////////////////////////////// #pragma once #include <algorithm> #include <atomic> #include <functional> #include <chrono> #include <unordered_map> #include <set> #include <cstdint> #include <thread> #include <mutex> #include <condition_variable> #include <cassert> namespace pfs { template <typename KeyType, typename ValueType> using default_timer_associative_container = std::unordered_map<KeyType, ValueType>; template <template <typename, typename> class AssociativeContainer = default_timer_associative_container , typename BasicLockable = std::mutex , typename ConditionVariable = std::condition_variable , template <typename> class ScopedLocker = std::unique_lock> class timer_pool { public: // Public types using timer_id = uint32_t; // Function object we actually use using callback_type = std::function<void()>; private: // Private types using mutex_type = BasicLockable; using condition_variable_type = ConditionVariable; using locker_type = ScopedLocker<mutex_type>; using clock_type = std::chrono::steady_clock; using time_point_type = std::chrono::time_point<clock_type>; using duration_millis_type = std::chrono::milliseconds; // Timer struct timer_item { timer_id id = 0; time_point_type next; duration_millis_type period; callback_type callback; bool running = false; // You must be holding the 'sync' lock to assign wait_cv std::unique_ptr<condition_variable_type> wait_cv; explicit timer_item (timer_id tid = 0) : id(tid) { } timer_item (timer_item && r) noexcept : id(r.id) , next(r.next) , period(r.period) , callback(std::move(r.callback)) , running(r.running) {} timer_item & operator = (timer_item && r) noexcept; timer_item (timer_id tid , time_point_type tnext , duration_millis_type tperiod , callback_type && func) noexcept : id(tid) , next(tnext) , period(tperiod) , callback(std::move(func)) {} timer_item (timer_item const &) = delete; timer_item & operator = (timer_item const &) = delete; }; // Comparison functor to sort the timer "queue" by Timer::next struct next_active_comparator { bool operator () (timer_item const & a, timer_item const & b) const noexcept { return a.next < b.next; } }; using timer_map = AssociativeContainer<timer_id, timer_item>; // Queue is a set of references to timer_item objects, sorted by next using value_type = std::reference_wrapper<timer_item>; using timer_queue = std::multiset<value_type, next_active_comparator>; private: // Private members // One worker thread for an unlimited number of timers is acceptable // Lazily started when first timer is started // TODO: Implement auto-stopping the timer thread when it is idle for // a configurable period. mutable mutex_type _mtx; std::thread _worker; // Inexhaustible source of unique IDs timer_id _next_id; // The Timer objects are physically stored in this map timer_map _active; // The ordering queue holds references to items in '_active' timer_queue _queue; condition_variable_type _wakeup_cv; std::atomic_bool _done{false}; // Valid IDs are guaranteed not to be this value static timer_id constexpr no_timer = timer_id{0}; public: // Constructor does not start worker until there is a Timer. timer_pool () : _next_id(no_timer + 1) {} // Destructor is thread safe, even if a timer callback is running. // All callbacks are guaranteed to have returned before this // destructor returns. ~timer_pool () { locker_type locker(_mtx); // The worker might not be running if (_worker.joinable()) { _done = true; locker.unlock(); _wakeup_cv.notify_all(); // If a timer callback is running, this // will make sure it has returned before // allowing any deallocations to happen _worker.join(); // Note that any timers still in the queue // will be destructed properly but they // will not be invoked } } /** Create a new timer using milliseconds, and add it to the internal queue. @param delay Callback starts firing this many seconds from now @param period If non-zero, callback is fired again after this period @param func The callback to run at the specified interval @return Id used to identify the timer for later use */ timer_id create (double delay , double period , callback_type && func) { locker_type locker(_mtx); // Lazily start thread when first timer is requested if (!_worker.joinable()) _worker = std::thread(& timer_pool::worker, this); // Assign an ID and insert it into function storage auto id = _next_id++; assert(delay * 1000 <= static_cast<decltype(delay)>(std::numeric_limits<intmax_t>::max())); assert(period * 1000 <= static_cast<decltype(period)>(std::numeric_limits<intmax_t>::max())); auto delay_millis = duration_millis_type(static_cast<intmax_t>(delay * 1000)); auto period_millis = duration_millis_type(static_cast<intmax_t>(period * 1000)); auto iter = _active.emplace(id , timer_item(id , clock_type::now() + delay_millis , period_millis , std::forward<callback_type>(func))); // Insert a reference to the Timer into ordering queue typename timer_queue::iterator place = _queue.emplace(iter.first->second); // We need to notify the timer thread only if we inserted // this timer into the front of the timer queue bool needNotify = (place == _queue.begin()); locker.unlock(); if (needNotify) _wakeup_cv.notify_all(); return id; } /** Destroy the specified timer. Synchronizes with the worker thread if the callback for this timer is running, which guarantees that the callback for that callback is not running before clear() returns. You are not required to clear any timers. You can forget their TimerId if you do not need to cancel them. The only time you need this is when you want to stop a timer that has a repetition period, or you want to cancel a timeout that has not fired yet. */ bool destroy (timer_id id) { locker_type locker(_mtx); auto it = _active.find(id); return destroy_impl(locker, it, true); } /** Destroy all timers, but preserve id uniqueness. This carefully makes sure every timer is not executing its callback before destructing it. */ void destroy_all () { locker_type locker(_mtx); while (!_active.empty()) destroy_impl(locker, _active.begin(), _queue.size() == 1); } std::size_t size () const noexcept { locker_type locker(_mtx); return _active.size(); } bool empty () const noexcept { locker_type locker(_mtx); return _active.empty(); } private: void worker () { locker_type locker(_mtx); while (!_done) { if (_queue.empty()) { // Wait for done or work _wakeup_cv.wait(locker, [this] { return _done || !_queue.empty(); }); continue; } auto queueHead = _queue.begin(); timer_item & timer = *queueHead; auto now = clock_type::now(); if (now >= timer.next) { _queue.erase(queueHead); // Mark it as running to handle racing destroy timer.running = true; // Call the callback outside the lock locker.unlock(); timer.callback(); locker.lock(); if (timer.running) { timer.running = false; // If it is periodic, schedule a new one if (timer.period.count() > 0) { timer.next = timer.next + timer.period; _queue.emplace(timer); } else { // Not rescheduling, destruct it _active.erase(timer.id); } } else { // timer.running changed! // // Running was set to false, destroy was called // for this Timer while the callback was in progress // (this thread was not holding the lock during the callback) // The thread trying to destroy this timer is waiting on // a condition variable, so notify it timer.wait_cv->notify_all(); // The clearTimer call expects us to remove the instance // when it detects that it is racing with its callback _active.erase(timer.id); } } else { // Wait until the timer is ready or a timer creation notifies time_point_type next = timer.next; _wakeup_cv.wait_until(locker, next); } } } bool destroy_impl (locker_type & locker, typename timer_map::iterator it, bool notify) { assert(locker.owns_lock()); if (it == _active.end()) return false; timer_item & timer = it->second; if (timer.running) { // A callback is in progress for this Timer, // so flag it for deletion in the worker timer.running = false; // Assign a condition variable to this timer timer.wait_cv.reset(new condition_variable_type); // Block until the callback is finished if (std::this_thread::get_id() != _worker.get_id()) timer.wait_cv->wait(locker); } else { _queue.erase(timer); _active.erase(it); if (notify) { locker.unlock(); _wakeup_cv.notify_all(); } } return true; } }; } // namespace pfs
32.372493
113
0.585148
[ "object" ]
dbcbe3c05ebdcdc451251f755aa79c734f0a991b
41,783
cpp
C++
libraries/render-utils/src/DeferredLightingEffect.cpp
thoys/hifi
a42bb5f53373f0c4ba7eee2de912d8fed522b46a
[ "Apache-2.0" ]
null
null
null
libraries/render-utils/src/DeferredLightingEffect.cpp
thoys/hifi
a42bb5f53373f0c4ba7eee2de912d8fed522b46a
[ "Apache-2.0" ]
1
2015-09-25T19:11:03.000Z
2015-09-25T22:04:36.000Z
libraries/render-utils/src/DeferredLightingEffect.cpp
thoys/hifi
a42bb5f53373f0c4ba7eee2de912d8fed522b46a
[ "Apache-2.0" ]
null
null
null
// // DeferredLightingEffect.cpp // interface/src/renderer // // Created by Andrzej Kapolka on 9/11/14. // 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 "DeferredLightingEffect.h" #include <GLMHelpers.h> #include <PathUtils.h> #include <ViewFrustum.h> #include <gpu/Batch.h> #include <gpu/Context.h> #include <gpu/StandardShaderLib.h> #include "AbstractViewStateInterface.h" #include "GeometryCache.h" #include "TextureCache.h" #include "FramebufferCache.h" #include "simple_vert.h" #include "simple_textured_frag.h" #include "simple_textured_emisive_frag.h" #include "deferred_light_vert.h" #include "deferred_light_limited_vert.h" #include "deferred_light_spot_vert.h" #include "directional_light_frag.h" #include "directional_light_shadow_map_frag.h" #include "directional_light_cascaded_shadow_map_frag.h" #include "directional_ambient_light_frag.h" #include "directional_ambient_light_shadow_map_frag.h" #include "directional_ambient_light_cascaded_shadow_map_frag.h" #include "directional_skybox_light_frag.h" #include "directional_skybox_light_shadow_map_frag.h" #include "directional_skybox_light_cascaded_shadow_map_frag.h" #include "point_light_frag.h" #include "spot_light_frag.h" static const std::string glowIntensityShaderHandle = "glowIntensity"; struct LightLocations { int shadowDistances; int shadowScale; int radius; int ambientSphere; int lightBufferUnit; int atmosphereBufferUnit; int texcoordMat; int coneParam; int deferredTransformBuffer; }; static void loadLightProgram(const char* vertSource, const char* fragSource, bool lightVolume, gpu::PipelinePointer& program, LightLocationsPtr& locations); gpu::PipelinePointer DeferredLightingEffect::getPipeline(SimpleProgramKey config) { auto it = _simplePrograms.find(config); if (it != _simplePrograms.end()) { return it.value(); } auto state = std::make_shared<gpu::State>(); if (config.isCulled()) { state->setCullMode(gpu::State::CULL_BACK); } else { state->setCullMode(gpu::State::CULL_NONE); } state->setDepthTest(true, true, gpu::LESS_EQUAL); if (config.hasDepthBias()) { state->setDepthBias(1.0f); state->setDepthBiasSlopeScale(1.0f); } state->setBlendFunction(false, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA, gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); gpu::ShaderPointer program = (config.isEmissive()) ? _emissiveShader : _simpleShader; gpu::PipelinePointer pipeline = gpu::PipelinePointer(gpu::Pipeline::create(program, state)); _simplePrograms.insert(config, pipeline); return pipeline; } void DeferredLightingEffect::init(AbstractViewStateInterface* viewState) { auto VS = gpu::ShaderPointer(gpu::Shader::createVertex(std::string(simple_vert))); auto PS = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(simple_textured_frag))); auto PSEmissive = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(simple_textured_emisive_frag))); _simpleShader = gpu::ShaderPointer(gpu::Shader::createProgram(VS, PS)); _emissiveShader = gpu::ShaderPointer(gpu::Shader::createProgram(VS, PSEmissive)); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("normalFittingMap"), DeferredLightingEffect::NORMAL_FITTING_MAP_SLOT)); gpu::Shader::makeProgram(*_simpleShader, slotBindings); gpu::Shader::makeProgram(*_emissiveShader, slotBindings); _viewState = viewState; _directionalLightLocations = std::make_shared<LightLocations>(); _directionalLightShadowMapLocations = std::make_shared<LightLocations>(); _directionalLightCascadedShadowMapLocations = std::make_shared<LightLocations>(); _directionalAmbientSphereLightLocations = std::make_shared<LightLocations>(); _directionalAmbientSphereLightShadowMapLocations = std::make_shared<LightLocations>(); _directionalAmbientSphereLightCascadedShadowMapLocations = std::make_shared<LightLocations>(); _directionalSkyboxLightLocations = std::make_shared<LightLocations>(); _directionalSkyboxLightShadowMapLocations = std::make_shared<LightLocations>(); _directionalSkyboxLightCascadedShadowMapLocations = std::make_shared<LightLocations>(); _pointLightLocations = std::make_shared<LightLocations>(); _spotLightLocations = std::make_shared<LightLocations>(); loadLightProgram(deferred_light_vert, directional_light_frag, false, _directionalLight, _directionalLightLocations); loadLightProgram(deferred_light_vert, directional_light_shadow_map_frag, false, _directionalLightShadowMap, _directionalLightShadowMapLocations); loadLightProgram(deferred_light_vert, directional_light_cascaded_shadow_map_frag, false, _directionalLightCascadedShadowMap, _directionalLightCascadedShadowMapLocations); loadLightProgram(deferred_light_vert, directional_ambient_light_frag, false, _directionalAmbientSphereLight, _directionalAmbientSphereLightLocations); loadLightProgram(deferred_light_vert, directional_ambient_light_shadow_map_frag, false, _directionalAmbientSphereLightShadowMap, _directionalAmbientSphereLightShadowMapLocations); loadLightProgram(deferred_light_vert, directional_ambient_light_cascaded_shadow_map_frag, false, _directionalAmbientSphereLightCascadedShadowMap, _directionalAmbientSphereLightCascadedShadowMapLocations); loadLightProgram(deferred_light_vert, directional_skybox_light_frag, false, _directionalSkyboxLight, _directionalSkyboxLightLocations); loadLightProgram(deferred_light_vert, directional_skybox_light_shadow_map_frag, false, _directionalSkyboxLightShadowMap, _directionalSkyboxLightShadowMapLocations); loadLightProgram(deferred_light_vert, directional_skybox_light_cascaded_shadow_map_frag, false, _directionalSkyboxLightCascadedShadowMap, _directionalSkyboxLightCascadedShadowMapLocations); loadLightProgram(deferred_light_limited_vert, point_light_frag, true, _pointLight, _pointLightLocations); loadLightProgram(deferred_light_spot_vert, spot_light_frag, true, _spotLight, _spotLightLocations); { //auto VSFS = gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS(); //auto PSBlit = gpu::StandardShaderLib::getDrawTexturePS(); auto blitProgram = gpu::StandardShaderLib::getProgram(gpu::StandardShaderLib::getDrawViewportQuadTransformTexcoordVS, gpu::StandardShaderLib::getDrawTexturePS); gpu::Shader::makeProgram(*blitProgram); auto blitState = std::make_shared<gpu::State>(); blitState->setBlendFunction(true, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA, gpu::State::FACTOR_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::ONE); blitState->setColorWriteMask(true, true, true, false); _blitLightBuffer = gpu::PipelinePointer(gpu::Pipeline::create(blitProgram, blitState)); } // Allocate a global light representing the Global Directional light casting shadow (the sun) and the ambient light _globalLights.push_back(0); _allocatedLights.push_back(std::make_shared<model::Light>()); model::LightPointer lp = _allocatedLights[0]; lp->setDirection(-glm::vec3(1.0f, 1.0f, 1.0f)); lp->setColor(glm::vec3(1.0f)); lp->setIntensity(1.0f); lp->setType(model::Light::SUN); lp->setAmbientSpherePreset(gpu::SphericalHarmonics::Preset(_ambientLightMode % gpu::SphericalHarmonics::NUM_PRESET)); } gpu::PipelinePointer DeferredLightingEffect::bindSimpleProgram(gpu::Batch& batch, bool textured, bool culled, bool emmisive, bool depthBias) { SimpleProgramKey config{textured, culled, emmisive, depthBias}; gpu::PipelinePointer pipeline = getPipeline(config); batch.setPipeline(pipeline); gpu::ShaderPointer program = (config.isEmissive()) ? _emissiveShader : _simpleShader; int glowIntensity = program->getUniforms().findLocation("glowIntensity"); batch._glUniform1f(glowIntensity, 1.0f); if (!config.isTextured()) { // If it is not textured, bind white texture and keep using textured pipeline batch.setResourceTexture(0, DependencyManager::get<TextureCache>()->getWhiteTexture()); } batch.setResourceTexture(NORMAL_FITTING_MAP_SLOT, DependencyManager::get<TextureCache>()->getNormalFittingTexture()); return pipeline; } uint32_t toCompactColor(const glm::vec4& color) { uint32_t compactColor = ((int(color.x * 255.0f) & 0xFF)) | ((int(color.y * 255.0f) & 0xFF) << 8) | ((int(color.z * 255.0f) & 0xFF) << 16) | ((int(color.w * 255.0f) & 0xFF) << 24); return compactColor; } static const size_t INSTANCE_TRANSFORM_BUFFER = 0; static const size_t INSTANCE_COLOR_BUFFER = 1; template <typename F> void renderInstances(const std::string& name, gpu::Batch& batch, const Transform& transform, const glm::vec4& color, F f) { { gpu::BufferPointer instanceTransformBuffer = batch.getNamedBuffer(name, INSTANCE_TRANSFORM_BUFFER); glm::mat4 glmTransform; instanceTransformBuffer->append(transform.getMatrix(glmTransform)); gpu::BufferPointer instanceColorBuffer = batch.getNamedBuffer(name, INSTANCE_COLOR_BUFFER); auto compactColor = toCompactColor(color); instanceColorBuffer->append(compactColor); } auto that = DependencyManager::get<DeferredLightingEffect>(); batch.setupNamedCalls(name, [=](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) { auto pipeline = that->bindSimpleProgram(batch); auto location = pipeline->getProgram()->getUniforms().findLocation("Instanced"); batch._glUniform1i(location, 1); f(batch, data); batch._glUniform1i(location, 0); }); } void DeferredLightingEffect::renderSolidSphereInstance(gpu::Batch& batch, const Transform& transform, const glm::vec4& color) { static const std::string INSTANCE_NAME = __FUNCTION__; renderInstances(INSTANCE_NAME, batch, transform, color, [](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) { DependencyManager::get<GeometryCache>()->renderShapeInstances(batch, GeometryCache::Sphere, data._count, data._buffers[INSTANCE_TRANSFORM_BUFFER], data._buffers[INSTANCE_COLOR_BUFFER]); }); } void DeferredLightingEffect::renderWireSphereInstance(gpu::Batch& batch, const Transform& transform, const glm::vec4& color) { static const std::string INSTANCE_NAME = __FUNCTION__; renderInstances(INSTANCE_NAME, batch, transform, color, [](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) { DependencyManager::get<GeometryCache>()->renderWireShapeInstances(batch, GeometryCache::Sphere, data._count, data._buffers[INSTANCE_TRANSFORM_BUFFER], data._buffers[INSTANCE_COLOR_BUFFER]); }); } // Enable this in a debug build to cause 'box' entities to iterate through all the // available shape types, both solid and wireframes //#define DEBUG_SHAPES void DeferredLightingEffect::renderSolidCubeInstance(gpu::Batch& batch, const Transform& transform, const glm::vec4& color) { static const std::string INSTANCE_NAME = __FUNCTION__; #ifdef DEBUG_SHAPES static auto startTime = usecTimestampNow(); renderInstances(INSTANCE_NAME, batch, transform, color, [](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) { auto usecs = usecTimestampNow(); usecs -= startTime; auto msecs = usecs / USECS_PER_MSEC; float seconds = msecs; seconds /= MSECS_PER_SECOND; float fractionalSeconds = seconds - floor(seconds); int shapeIndex = (int)seconds; // Every second we flip to the next shape. static const int SHAPE_COUNT = 5; GeometryCache::Shape shapes[SHAPE_COUNT] = { GeometryCache::Cube, GeometryCache::Tetrahedron, GeometryCache::Sphere, GeometryCache::Icosahedron, GeometryCache::Line, }; shapeIndex %= SHAPE_COUNT; GeometryCache::Shape shape = shapes[shapeIndex]; // For the first half second for a given shape, show the wireframe, for the second half, show the solid. if (fractionalSeconds > 0.5f) { DependencyManager::get<GeometryCache>()->renderShapeInstances(batch, shape, data._count, data._buffers[INSTANCE_TRANSFORM_BUFFER], data._buffers[INSTANCE_COLOR_BUFFER]); } else { DependencyManager::get<GeometryCache>()->renderWireShapeInstances(batch, shape, data._count, data._buffers[INSTANCE_TRANSFORM_BUFFER], data._buffers[INSTANCE_COLOR_BUFFER]); } }); #else renderInstances(INSTANCE_NAME, batch, transform, color, [](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) { DependencyManager::get<GeometryCache>()->renderCubeInstances(batch, data._count, data._buffers[INSTANCE_TRANSFORM_BUFFER], data._buffers[INSTANCE_COLOR_BUFFER]); }); #endif } void DeferredLightingEffect::renderWireCubeInstance(gpu::Batch& batch, const Transform& transform, const glm::vec4& color) { static const std::string INSTANCE_NAME = __FUNCTION__; renderInstances(INSTANCE_NAME, batch, transform, color, [](gpu::Batch& batch, gpu::Batch::NamedBatchData& data) { DependencyManager::get<GeometryCache>()->renderWireCubeInstances(batch, data._count, data._buffers[INSTANCE_TRANSFORM_BUFFER], data._buffers[INSTANCE_COLOR_BUFFER]); }); } void DeferredLightingEffect::renderQuad(gpu::Batch& batch, const glm::vec3& minCorner, const glm::vec3& maxCorner, const glm::vec4& color) { bindSimpleProgram(batch); DependencyManager::get<GeometryCache>()->renderQuad(batch, minCorner, maxCorner, color); } void DeferredLightingEffect::renderLine(gpu::Batch& batch, const glm::vec3& p1, const glm::vec3& p2, const glm::vec4& color1, const glm::vec4& color2) { bindSimpleProgram(batch); DependencyManager::get<GeometryCache>()->renderLine(batch, p1, p2, color1, color2); } void DeferredLightingEffect::addPointLight(const glm::vec3& position, float radius, const glm::vec3& color, float intensity) { addSpotLight(position, radius, color, intensity); } void DeferredLightingEffect::addSpotLight(const glm::vec3& position, float radius, const glm::vec3& color, float intensity, const glm::quat& orientation, float exponent, float cutoff) { unsigned int lightID = _pointLights.size() + _spotLights.size() + _globalLights.size(); if (lightID >= _allocatedLights.size()) { _allocatedLights.push_back(std::make_shared<model::Light>()); } model::LightPointer lp = _allocatedLights[lightID]; lp->setPosition(position); lp->setMaximumRadius(radius); lp->setColor(color); lp->setIntensity(intensity); //lp->setShowContour(quadraticAttenuation); if (exponent == 0.0f && cutoff == PI) { lp->setType(model::Light::POINT); _pointLights.push_back(lightID); } else { lp->setOrientation(orientation); lp->setSpotAngle(cutoff); lp->setSpotExponent(exponent); lp->setType(model::Light::SPOT); _spotLights.push_back(lightID); } } void DeferredLightingEffect::prepare(RenderArgs* args) { gpu::doInBatch(args->_context, [=](gpu::Batch& batch) { batch.enableStereo(false); batch.setStateScissorRect(args->_viewport); auto primaryFbo = DependencyManager::get<FramebufferCache>()->getPrimaryFramebuffer(); batch.setFramebuffer(primaryFbo); // clear the normal and specular buffers batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR1, glm::vec4(0.0f, 0.0f, 0.0f, 0.0f), true); const float MAX_SPECULAR_EXPONENT = 128.0f; batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR2, glm::vec4(0.0f, 0.0f, 0.0f, 1.0f / MAX_SPECULAR_EXPONENT), true); }); } gpu::FramebufferPointer _copyFBO; void DeferredLightingEffect::render(RenderArgs* args) { gpu::doInBatch(args->_context, [=](gpu::Batch& batch) { // Allocate the parameters buffer used by all the deferred shaders if (!_deferredTransformBuffer[0]._buffer) { DeferredTransform parameters; _deferredTransformBuffer[0] = gpu::BufferView(std::make_shared<gpu::Buffer>(sizeof(DeferredTransform), (const gpu::Byte*) &parameters)); _deferredTransformBuffer[1] = gpu::BufferView(std::make_shared<gpu::Buffer>(sizeof(DeferredTransform), (const gpu::Byte*) &parameters)); } // Framebuffer copy operations cannot function as multipass stereo operations. batch.enableStereo(false); // perform deferred lighting, rendering to free fbo auto framebufferCache = DependencyManager::get<FramebufferCache>(); QSize framebufferSize = framebufferCache->getFrameBufferSize(); // binding the first framebuffer _copyFBO = framebufferCache->getFramebuffer(); batch.setFramebuffer(_copyFBO); // Clearing it batch.setViewportTransform(args->_viewport); batch.setStateScissorRect(args->_viewport); batch.clearColorFramebuffer(_copyFBO->getBufferMask(), glm::vec4(0.0f, 0.0f, 0.0f, 0.0f), true); // BInd the G-Buffer surfaces batch.setResourceTexture(0, framebufferCache->getPrimaryColorTexture()); batch.setResourceTexture(1, framebufferCache->getPrimaryNormalTexture()); batch.setResourceTexture(2, framebufferCache->getPrimarySpecularTexture()); batch.setResourceTexture(3, framebufferCache->getPrimaryDepthTexture()); // THe main viewport is assumed to be the mono viewport (or the 2 stereo faces side by side within that viewport) auto monoViewport = args->_viewport; float sMin = args->_viewport.x / (float)framebufferSize.width(); float sWidth = args->_viewport.z / (float)framebufferSize.width(); float tMin = args->_viewport.y / (float)framebufferSize.height(); float tHeight = args->_viewport.w / (float)framebufferSize.height(); // The view frustum is the mono frustum base auto viewFrustum = args->_viewFrustum; // Eval the mono projection mat4 monoProjMat; viewFrustum->evalProjectionMatrix(monoProjMat); // The mono view transform Transform monoViewTransform; viewFrustum->evalViewTransform(monoViewTransform); // THe mono view matrix coming from the mono view transform glm::mat4 monoViewMat; monoViewTransform.getMatrix(monoViewMat); // Running in stero ? bool isStereo = args->_context->isStereo(); int numPasses = 1; mat4 projMats[2]; Transform viewTransforms[2]; ivec4 viewports[2]; vec4 clipQuad[2]; vec2 screenBottomLeftCorners[2]; vec2 screenTopRightCorners[2]; vec4 fetchTexcoordRects[2]; DeferredTransform deferredTransforms[2]; auto geometryCache = DependencyManager::get<GeometryCache>(); if (isStereo) { numPasses = 2; mat4 eyeViews[2]; args->_context->getStereoProjections(projMats); args->_context->getStereoViews(eyeViews); float halfWidth = 0.5f * sWidth; for (int i = 0; i < numPasses; i++) { // In stereo, the 2 sides are layout side by side in the mono viewport and their width is half int sideWidth = monoViewport.z >> 1; viewports[i] = ivec4(monoViewport.x + (i * sideWidth), monoViewport.y, sideWidth, monoViewport.w); deferredTransforms[i].projection = projMats[i]; auto sideViewMat = monoViewMat * glm::inverse(eyeViews[i]); viewTransforms[i].evalFromRawMatrix(sideViewMat); deferredTransforms[i].viewInverse = sideViewMat; deferredTransforms[i].stereoSide = (i == 0 ? -1.0f : 1.0f); clipQuad[i] = glm::vec4(sMin + i * halfWidth, tMin, halfWidth, tHeight); screenBottomLeftCorners[i] = glm::vec2(-1.0f + i * 1.0f, -1.0f); screenTopRightCorners[i] = glm::vec2(i * 1.0f, 1.0f); fetchTexcoordRects[i] = glm::vec4(sMin + i * halfWidth, tMin, halfWidth, tHeight); } } else { viewports[0] = monoViewport; projMats[0] = monoProjMat; deferredTransforms[0].projection = monoProjMat; deferredTransforms[0].viewInverse = monoViewMat; viewTransforms[0] = monoViewTransform; deferredTransforms[0].stereoSide = 0.0f; clipQuad[0] = glm::vec4(sMin, tMin, sWidth, tHeight); screenBottomLeftCorners[0] = glm::vec2(-1.0f, -1.0f); screenTopRightCorners[0] = glm::vec2(1.0f, 1.0f); fetchTexcoordRects[0] = glm::vec4(sMin, tMin, sWidth, tHeight); } auto eyePoint = viewFrustum->getPosition(); float nearRadius = glm::distance(eyePoint, viewFrustum->getNearTopLeft()); for (int side = 0; side < numPasses; side++) { // Render in this side's viewport batch.setViewportTransform(viewports[side]); batch.setStateScissorRect(viewports[side]); // Sync and Bind the correct DeferredTransform ubo _deferredTransformBuffer[side]._buffer->setSubData(0, sizeof(DeferredTransform), (const gpu::Byte*) &deferredTransforms[side]); batch.setUniformBuffer(_directionalLightLocations->deferredTransformBuffer, _deferredTransformBuffer[side]); glm::vec2 topLeft(-1.0f, -1.0f); glm::vec2 bottomRight(1.0f, 1.0f); glm::vec2 texCoordTopLeft(clipQuad[side].x, clipQuad[side].y); glm::vec2 texCoordBottomRight(clipQuad[side].x + clipQuad[side].z, clipQuad[side].y + clipQuad[side].w); // First Global directional light and ambient pass { bool useSkyboxCubemap = (_skybox) && (_skybox->getCubemap()); auto& program = _directionalLight; LightLocationsPtr locations = _directionalLightLocations; // TODO: At some point bring back the shadows... // Setup the global directional pass pipeline { if (useSkyboxCubemap) { program = _directionalSkyboxLight; locations = _directionalSkyboxLightLocations; } else if (_ambientLightMode > -1) { program = _directionalAmbientSphereLight; locations = _directionalAmbientSphereLightLocations; } batch.setPipeline(program); } { // Setup the global lighting auto globalLight = _allocatedLights[_globalLights.front()]; if (locations->ambientSphere >= 0) { gpu::SphericalHarmonics sh = globalLight->getAmbientSphere(); if (useSkyboxCubemap && _skybox->getCubemap()->getIrradiance()) { sh = (*_skybox->getCubemap()->getIrradiance()); } for (int i =0; i <gpu::SphericalHarmonics::NUM_COEFFICIENTS; i++) { batch._glUniform4fv(locations->ambientSphere + i, 1, (const float*) (&sh) + i * 4); } } if (useSkyboxCubemap) { batch.setResourceTexture(5, _skybox->getCubemap()); } if (locations->lightBufferUnit >= 0) { batch.setUniformBuffer(locations->lightBufferUnit, globalLight->getSchemaBuffer()); } if (_atmosphere && (locations->atmosphereBufferUnit >= 0)) { batch.setUniformBuffer(locations->atmosphereBufferUnit, _atmosphere->getDataBuffer()); } } { batch.setModelTransform(Transform()); batch.setProjectionTransform(glm::mat4()); batch.setViewTransform(Transform()); glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); geometryCache->renderQuad(batch, topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight, color); } if (useSkyboxCubemap) { batch.setResourceTexture(5, nullptr); } } auto texcoordMat = glm::mat4(); /* texcoordMat[0] = glm::vec4(sWidth / 2.0f, 0.0f, 0.0f, sMin + sWidth / 2.0f); texcoordMat[1] = glm::vec4(0.0f, tHeight / 2.0f, 0.0f, tMin + tHeight / 2.0f); */ texcoordMat[0] = glm::vec4(fetchTexcoordRects[side].z / 2.0f, 0.0f, 0.0f, fetchTexcoordRects[side].x + fetchTexcoordRects[side].z / 2.0f); texcoordMat[1] = glm::vec4(0.0f, fetchTexcoordRects[side].w / 2.0f, 0.0f, fetchTexcoordRects[side].y + fetchTexcoordRects[side].w / 2.0f); texcoordMat[2] = glm::vec4(0.0f, 0.0f, 1.0f, 0.0f); texcoordMat[3] = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); // enlarge the scales slightly to account for tesselation const float SCALE_EXPANSION = 0.05f; batch.setProjectionTransform(projMats[side]); batch.setViewTransform(viewTransforms[side]); // Splat Point lights if (!_pointLights.empty()) { batch.setPipeline(_pointLight); batch._glUniformMatrix4fv(_pointLightLocations->texcoordMat, 1, false, reinterpret_cast< const float* >(&texcoordMat)); for (auto lightID : _pointLights) { auto& light = _allocatedLights[lightID]; // IN DEBUG: light->setShowContour(true); batch.setUniformBuffer(_pointLightLocations->lightBufferUnit, light->getSchemaBuffer()); float expandedRadius = light->getMaximumRadius() * (1.0f + SCALE_EXPANSION); // TODO: We shouldn;t have to do that test and use a different volume geometry for when inside the vlight volume, // we should be able to draw thre same geometry use DepthClamp but for unknown reason it's s not working... if (glm::distance(eyePoint, glm::vec3(light->getPosition())) < expandedRadius + nearRadius) { Transform model; model.setTranslation(glm::vec3(0.0f, 0.0f, -1.0f)); batch.setModelTransform(model); batch.setViewTransform(Transform()); batch.setProjectionTransform(glm::mat4()); glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); DependencyManager::get<GeometryCache>()->renderQuad(batch, topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight, color); batch.setProjectionTransform(projMats[side]); batch.setViewTransform(viewTransforms[side]); } else { Transform model; model.setTranslation(glm::vec3(light->getPosition().x, light->getPosition().y, light->getPosition().z)); batch.setModelTransform(model.postScale(expandedRadius)); batch._glColor4f(1.0f, 1.0f, 1.0f, 1.0f); geometryCache->renderSphere(batch); } } } // Splat spot lights if (!_spotLights.empty()) { batch.setPipeline(_spotLight); batch._glUniformMatrix4fv(_spotLightLocations->texcoordMat, 1, false, reinterpret_cast< const float* >(&texcoordMat)); for (auto lightID : _spotLights) { auto light = _allocatedLights[lightID]; // IN DEBUG: light->setShowContour(true); batch.setUniformBuffer(_spotLightLocations->lightBufferUnit, light->getSchemaBuffer()); auto eyeLightPos = eyePoint - light->getPosition(); auto eyeHalfPlaneDistance = glm::dot(eyeLightPos, light->getDirection()); const float TANGENT_LENGTH_SCALE = 0.666f; glm::vec4 coneParam(light->getSpotAngleCosSin(), TANGENT_LENGTH_SCALE * tanf(0.5f * light->getSpotAngle()), 1.0f); float expandedRadius = light->getMaximumRadius() * (1.0f + SCALE_EXPANSION); // TODO: We shouldn;t have to do that test and use a different volume geometry for when inside the vlight volume, // we should be able to draw thre same geometry use DepthClamp but for unknown reason it's s not working... if ((eyeHalfPlaneDistance > -nearRadius) && (glm::distance(eyePoint, glm::vec3(light->getPosition())) < expandedRadius + nearRadius)) { coneParam.w = 0.0f; batch._glUniform4fv(_spotLightLocations->coneParam, 1, reinterpret_cast< const float* >(&coneParam)); Transform model; model.setTranslation(glm::vec3(0.0f, 0.0f, -1.0f)); batch.setModelTransform(model); batch.setViewTransform(Transform()); batch.setProjectionTransform(glm::mat4()); glm::vec4 color(1.0f, 1.0f, 1.0f, 1.0f); DependencyManager::get<GeometryCache>()->renderQuad(batch, topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight, color); batch.setProjectionTransform( projMats[side]); batch.setViewTransform(viewTransforms[side]); } else { coneParam.w = 1.0f; batch._glUniform4fv(_spotLightLocations->coneParam, 1, reinterpret_cast< const float* >(&coneParam)); Transform model; model.setTranslation(light->getPosition()); model.postRotate(light->getOrientation()); model.postScale(glm::vec3(expandedRadius, expandedRadius, expandedRadius)); batch.setModelTransform(model); auto mesh = getSpotLightMesh(); batch.setIndexBuffer(mesh->getIndexBuffer()); batch.setInputBuffer(0, mesh->getVertexBuffer()); batch.setInputFormat(mesh->getVertexFormat()); auto& part = mesh->getPartBuffer().get<model::Mesh::Part>(); batch.drawIndexed(model::Mesh::topologyToPrimitive(part._topology), part._numIndices, part._startIndex); } } } } // Probably not necessary in the long run because the gpu layer would unbound this texture if used as render target batch.setResourceTexture(0, nullptr); batch.setResourceTexture(1, nullptr); batch.setResourceTexture(2, nullptr); batch.setResourceTexture(3, nullptr); batch.setUniformBuffer(_directionalLightLocations->deferredTransformBuffer, nullptr); }); // End of the Lighting pass if (!_pointLights.empty()) { _pointLights.clear(); } if (!_spotLights.empty()) { _spotLights.clear(); } } void DeferredLightingEffect::copyBack(RenderArgs* args) { auto framebufferCache = DependencyManager::get<FramebufferCache>(); gpu::doInBatch(args->_context, [=](gpu::Batch& batch) { batch.enableStereo(false); QSize framebufferSize = framebufferCache->getFrameBufferSize(); // TODO why doesn't this blit work? It only seems to affect a small area below the rear view mirror. // auto destFbo = framebufferCache->getPrimaryFramebuffer(); auto destFbo = framebufferCache->getPrimaryFramebufferDepthColor(); // gpu::Vec4i vp = args->_viewport; // batch.blit(_copyFBO, vp, framebufferCache->getPrimaryFramebuffer(), vp); batch.setFramebuffer(destFbo); batch.setViewportTransform(args->_viewport); batch.setProjectionTransform(glm::mat4()); batch.setViewTransform(Transform()); { float sMin = args->_viewport.x / (float)framebufferSize.width(); float sWidth = args->_viewport.z / (float)framebufferSize.width(); float tMin = args->_viewport.y / (float)framebufferSize.height(); float tHeight = args->_viewport.w / (float)framebufferSize.height(); Transform model; batch.setPipeline(_blitLightBuffer); model.setTranslation(glm::vec3(sMin, tMin, 0.0)); model.setScale(glm::vec3(sWidth, tHeight, 1.0)); batch.setModelTransform(model); } batch.setResourceTexture(0, _copyFBO->getRenderBuffer(0)); batch.draw(gpu::TRIANGLE_STRIP, 4); args->_context->render(batch); }); framebufferCache->releaseFramebuffer(_copyFBO); } void DeferredLightingEffect::setupTransparent(RenderArgs* args, int lightBufferUnit) { auto globalLight = _allocatedLights[_globalLights.front()]; args->_batch->setUniformBuffer(lightBufferUnit, globalLight->getSchemaBuffer()); } static void loadLightProgram(const char* vertSource, const char* fragSource, bool lightVolume, gpu::PipelinePointer& pipeline, LightLocationsPtr& locations) { auto VS = gpu::ShaderPointer(gpu::Shader::createVertex(std::string(vertSource))); auto PS = gpu::ShaderPointer(gpu::Shader::createPixel(std::string(fragSource))); gpu::ShaderPointer program = gpu::ShaderPointer(gpu::Shader::createProgram(VS, PS)); gpu::Shader::BindingSet slotBindings; slotBindings.insert(gpu::Shader::Binding(std::string("diffuseMap"), 0)); slotBindings.insert(gpu::Shader::Binding(std::string("normalMap"), 1)); slotBindings.insert(gpu::Shader::Binding(std::string("specularMap"), 2)); slotBindings.insert(gpu::Shader::Binding(std::string("depthMap"), 3)); slotBindings.insert(gpu::Shader::Binding(std::string("shadowMap"), 4)); slotBindings.insert(gpu::Shader::Binding(std::string("skyboxMap"), 5)); const int LIGHT_GPU_SLOT = 3; slotBindings.insert(gpu::Shader::Binding(std::string("lightBuffer"), LIGHT_GPU_SLOT)); const int ATMOSPHERE_GPU_SLOT = 4; slotBindings.insert(gpu::Shader::Binding(std::string("atmosphereBufferUnit"), ATMOSPHERE_GPU_SLOT)); slotBindings.insert(gpu::Shader::Binding(std::string("deferredTransformBuffer"), DeferredLightingEffect::DEFERRED_TRANSFORM_BUFFER_SLOT)); gpu::Shader::makeProgram(*program, slotBindings); locations->shadowDistances = program->getUniforms().findLocation("shadowDistances"); locations->shadowScale = program->getUniforms().findLocation("shadowScale"); locations->radius = program->getUniforms().findLocation("radius"); locations->ambientSphere = program->getUniforms().findLocation("ambientSphere.L00"); locations->texcoordMat = program->getUniforms().findLocation("texcoordMat"); locations->coneParam = program->getUniforms().findLocation("coneParam"); locations->lightBufferUnit = program->getBuffers().findLocation("lightBuffer"); locations->atmosphereBufferUnit = program->getBuffers().findLocation("atmosphereBufferUnit"); locations->deferredTransformBuffer = program->getBuffers().findLocation("deferredTransformBuffer"); auto state = std::make_shared<gpu::State>(); if (lightVolume) { state->setCullMode(gpu::State::CULL_BACK); // No need for z test since the depth buffer is not bound state->setDepthTest(true, false, gpu::LESS_EQUAL); // TODO: We should bind the true depth buffer both as RT and texture for the depth test // TODO: We should use DepthClamp and avoid changing geometry for inside /outside cases state->setDepthClampEnable(true); // additive blending state->setBlendFunction(true, gpu::State::ONE, gpu::State::BLEND_OP_ADD, gpu::State::ONE); } else { state->setCullMode(gpu::State::CULL_BACK); } pipeline.reset(gpu::Pipeline::create(program, state)); } void DeferredLightingEffect::setAmbientLightMode(int preset) { if ((preset >= 0) && (preset < gpu::SphericalHarmonics::NUM_PRESET)) { _ambientLightMode = preset; auto light = _allocatedLights.front(); light->setAmbientSpherePreset(gpu::SphericalHarmonics::Preset(preset % gpu::SphericalHarmonics::NUM_PRESET)); } else { // force to preset 0 setAmbientLightMode(0); } } void DeferredLightingEffect::setGlobalLight(const glm::vec3& direction, const glm::vec3& diffuse, float intensity, float ambientIntensity) { auto light = _allocatedLights.front(); light->setDirection(direction); light->setColor(diffuse); light->setIntensity(intensity); light->setAmbientIntensity(ambientIntensity); } void DeferredLightingEffect::setGlobalSkybox(const model::SkyboxPointer& skybox) { _skybox = skybox; } model::MeshPointer DeferredLightingEffect::getSpotLightMesh() { if (!_spotLightMesh) { _spotLightMesh = std::make_shared<model::Mesh>(); int slices = 32; int rings = 3; int vertices = 2 + rings * slices; int originVertex = vertices - 2; int capVertex = vertices - 1; int verticesSize = vertices * 3 * sizeof(float); int indices = 3 * slices * (1 + 1 + 2 * (rings -1)); int ringFloatOffset = slices * 3; float* vertexData = new float[verticesSize]; float* vertexRing0 = vertexData; float* vertexRing1 = vertexRing0 + ringFloatOffset; float* vertexRing2 = vertexRing1 + ringFloatOffset; for (int i = 0; i < slices; i++) { float theta = TWO_PI * i / slices; auto cosin = glm::vec2(cosf(theta), sinf(theta)); *(vertexRing0++) = cosin.x; *(vertexRing0++) = cosin.y; *(vertexRing0++) = 0.0f; *(vertexRing1++) = cosin.x; *(vertexRing1++) = cosin.y; *(vertexRing1++) = 0.33f; *(vertexRing2++) = cosin.x; *(vertexRing2++) = cosin.y; *(vertexRing2++) = 0.66f; } *(vertexRing2++) = 0.0f; *(vertexRing2++) = 0.0f; *(vertexRing2++) = -1.0f; *(vertexRing2++) = 0.0f; *(vertexRing2++) = 0.0f; *(vertexRing2++) = 1.0f; _spotLightMesh->setVertexBuffer(gpu::BufferView(new gpu::Buffer(verticesSize, (gpu::Byte*) vertexData), gpu::Element::VEC3F_XYZ)); delete[] vertexData; gpu::uint16* indexData = new gpu::uint16[indices]; gpu::uint16* index = indexData; for (int i = 0; i < slices; i++) { *(index++) = originVertex; int s0 = i; int s1 = ((i + 1) % slices); *(index++) = s0; *(index++) = s1; int s2 = s0 + slices; int s3 = s1 + slices; *(index++) = s1; *(index++) = s0; *(index++) = s2; *(index++) = s1; *(index++) = s2; *(index++) = s3; int s4 = s2 + slices; int s5 = s3 + slices; *(index++) = s3; *(index++) = s2; *(index++) = s4; *(index++) = s3; *(index++) = s4; *(index++) = s5; *(index++) = s5; *(index++) = s4; *(index++) = capVertex; } _spotLightMesh->setIndexBuffer(gpu::BufferView(new gpu::Buffer(sizeof(unsigned short) * indices, (gpu::Byte*) indexData), gpu::Element::INDEX_UINT16)); delete[] indexData; model::Mesh::Part part(0, indices, 0, model::Mesh::TRIANGLES); //DEBUG: model::Mesh::Part part(0, indices, 0, model::Mesh::LINE_STRIP); _spotLightMesh->setPartBuffer(gpu::BufferView(new gpu::Buffer(sizeof(part), (gpu::Byte*) &part), gpu::Element::PART_DRAWCALL)); _spotLightMesh->makeBufferStream(); } return _spotLightMesh; }
46.684916
169
0.633679
[ "mesh", "geometry", "render", "shape", "model", "transform", "solid" ]
dbd34271f8a72e443f027f1bd5f297581a88c705
2,369
cpp
C++
source/bodies/BasicBody.cpp
cburggie/raytracer
ca941807bf8086c0a7b54f8fd04abe619c1d0703
[ "MIT" ]
1
2016-06-21T03:14:59.000Z
2016-06-21T03:14:59.000Z
source/bodies/BasicBody.cpp
dburggie/raytracer
d88a7c273c861e83608eb2a52b527cf76fbcc045
[ "MIT" ]
null
null
null
source/bodies/BasicBody.cpp
dburggie/raytracer
d88a7c273c861e83608eb2a52b527cf76fbcc045
[ "MIT" ]
null
null
null
#include <raytracer.h> #include <bodies.h> #include <cassert> #include <cmath> using namespace raytracer; BasicBody::BasicBody() { useDefaults(); } void BasicBody::useDefaults() { transparent = false; index = 1.0; reflectivity = 0.0; matte = false; normal_delta = 0.0; size = 1.0; position.copy(0.0,0.0,0.0); orientation.copy(0.0,1.0,0.0); x_axis.copy(1.0,0.0,0.0); y_axis.copy(0.0,1.0,0.0); z_axis.copy(0.0,0.0,1.0); interior_color.copy(0.50,0.50,0.50); color.copy(interior_color); } bool BasicBody::isTransparent(const Vector & p) const { return transparent; } double BasicBody::getIndex(const Vector & p) const { return index; } Vector BasicBody::getColor(const Vector & p) const { return color; } Vector BasicBody::getInteriorColor(const Vector & p) const { return interior_color; } void BasicBody::setReflectivity(double r) { assert(0 <= r); assert(r < 1.0); reflectivity = r; } double BasicBody::getReflectivity(const Vector & p) const { return reflectivity; } void BasicBody::setPosition(const Vector & p) { position.copy(p); } void BasicBody::setOrientation(const Vector & o) { orientation.copy(o); orientation.normalize(); } void BasicBody::setOrientation( const Vector & X, const Vector & Y, const Vector & Z ) { x_axis.copy(X); y_axis.copy(Y); z_axis.copy(Z); } void BasicBody::setSize(double S) { assert(S > DIV_LIMIT); size = S; } void BasicBody::setColor(const Vector & c) { assert(0.0 <= c.x); assert(0.0 <= c.y); assert(0.0 <= c.z); assert(c.x < 1.0); assert(c.y < 1.0); assert(c.z < 1.0); color.copy(c); interior_color.copy(c); } void BasicBody::setInteriorColor(const Vector & c) { assert(0.0 <= c.x); assert(0.0 <= c.y); assert(0.0 <= c.z); assert(c.x < 1.0); assert(c.y < 1.0); assert(c.z < 1.0); interior_color.copy(c); } void BasicBody::refractionOff() { transparent = false; } void BasicBody::refractionOn() { transparent = true; } void BasicBody::setIndex(double n) { assert(1.0 <= n); index = n; reflectivity = (index - 1.0) / (index); reflectivity = reflectivity * reflectivity; assert(0.0 <= reflectivity); assert(reflectivity < 1.0); } void BasicBody::matteOn(double delta) { assert(0.0 <= delta); assert(delta < 1.0); matte = true; normal_delta = delta; } void BasicBody::matteOff() { matte = false; }
13.614943
60
0.652596
[ "vector" ]
dbdb83235d53810608a826dcd6ebebda9e8adae7
4,478
cpp
C++
bingwa/src/EffectParameterNamePack.cpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
null
null
null
bingwa/src/EffectParameterNamePack.cpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
null
null
null
bingwa/src/EffectParameterNamePack.cpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
null
null
null
// Copyright Gavin Band 2008 - 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <string> #include <vector> #include <cassert> #include "genfile/string_utils/string_utils.hpp" #include "genfile/string_utils/slice.hpp" #include "bingwa/EffectParameterNamePack.hpp" namespace bingwa { EffectParameterNamePack::EffectParameterNamePack() {} EffectParameterNamePack::EffectParameterNamePack( std::vector< std::string > betas, std::vector< std::string > ses, std::vector< std::string > cov ): m_betas( betas ), m_ses( ses ), m_cov( cov ) { assert( m_ses.size() == m_betas.size() ) ; assert( m_cov.size() == ( m_betas.size() * ( m_betas.size() - 1 )) / 2 ) ; } EffectParameterNamePack::EffectParameterNamePack( EffectParameterNamePack const& other ): m_betas( other.m_betas ), m_ses( other.m_ses ), m_cov( other.m_cov ) { } EffectParameterNamePack& EffectParameterNamePack::operator=( EffectParameterNamePack const& other ) { m_betas = other.m_betas ; m_ses = other.m_ses ; m_cov = other.m_cov ; return *this ; } std::size_t EffectParameterNamePack::size() const { return m_betas.size() ; } std::size_t EffectParameterNamePack::find( std::string const& name ) const { std::vector< std::string >::const_iterator where = std::find( m_betas.begin(), m_betas.end(), name ) ; if( where == m_betas.end() ) { return npos ; } else { return std::size_t( where - m_betas.begin() ) ; } } std::string EffectParameterNamePack::parameter_name( std::size_t i ) const { return m_betas[i] ; } std::string EffectParameterNamePack::se_name( std::size_t i ) const { return m_ses[i] ; } std::string EffectParameterNamePack::wald_pvalue_name( std::size_t i ) const { std::string result = m_ses[i] ; std::size_t pos = result.find( "se_" ) ; assert( pos != std::string::npos ) ; result.replace( pos, 3, "wald_pvalue_" ) ; return result ; } std::string EffectParameterNamePack::covariance_name( std::size_t i, std::size_t j ) const { return m_cov[ get_index_of_covariance(i,j) ] ; } std::size_t EffectParameterNamePack::get_index_of_covariance( std::size_t i, std::size_t j ) const { assert( j > i ) ; // index in cov skips the lower diagonal. // Lower diagonal has ((i+1)*(i+2)/2) entries since i is a 0-based index. // index in full array would be i*N+j std::size_t const N = m_betas.size() ; return i*N + j - ( (i+1)*(i+2)/2 ) ; } void EffectParameterNamePack::rename( std::size_t parameter_i, std::string const& newName, std::string const& newSubscript, std::string const& identifier ) { using genfile::string_utils::to_string ; using genfile::string_utils::slice ; std::size_t const N = m_betas.size() ; assert( parameter_i < N ) ; m_betas[parameter_i] = newName + "_" + newSubscript + ":" + identifier ; m_ses[parameter_i] = "se_" + newSubscript ; // Rename covariance parameters // They are expected to be of the form <name>_i,j { std::size_t j = parameter_i ; for( std::size_t i = 0; i < parameter_i; ++i ) { std::size_t index = get_index_of_covariance(i,j) ; std::vector< slice > elts = slice( m_cov[index] ).split( "_" ) ; assert( elts.size() == 2 ) ; std::vector< slice > elts2 = elts[1].split( "," ) ; assert( elts2.size() == 2 ) ; m_cov[index] = elts[0] + "_" + elts2[0] + "," + newSubscript ; } } { std::size_t i = parameter_i ; for( std::size_t j = parameter_i+1; j < N; ++j ) { std::size_t index = get_index_of_covariance(i,j) ; std::vector< slice > elts = slice( m_cov[index] ).split( "_" ) ; assert( elts.size() == 2 ) ; std::vector< slice > elts2 = elts[1].split( "," ) ; assert( elts2.size() == 2 ) ; m_cov[index] = elts[0] + "_" + newSubscript + "," + elts2[1] ; } } } bool EffectParameterNamePack::operator==( EffectParameterNamePack const& other ) const { return m_betas == other.m_betas && m_ses == other.m_ses && m_cov == other.m_cov ; } bool EffectParameterNamePack::operator!=( EffectParameterNamePack const& other ) const { return !operator==( other ) ; } std::string EffectParameterNamePack::get_summary() const { using genfile::string_utils::join ; std::ostringstream ostr ; ostr << "(" << join( m_betas, "," ) << "; " << join( m_ses, "," ) << "; " << join( m_cov, ", " ) << ")" ; return ostr.str() ; } }
32.449275
107
0.650737
[ "vector" ]
dbdbbc4892e2324677c9c1c5c47241d68d8779e0
2,662
cpp
C++
lab2/Q3.cpp
jasonsie88/Algorithm
4d373df037aa68f4810e271d7f8488f3ded81864
[ "MIT" ]
1
2021-09-14T12:10:50.000Z
2021-09-14T12:10:50.000Z
lab2/Q3.cpp
jasonsie88/Algorithm
4d373df037aa68f4810e271d7f8488f3ded81864
[ "MIT" ]
null
null
null
lab2/Q3.cpp
jasonsie88/Algorithm
4d373df037aa68f4810e271d7f8488f3ded81864
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define zero 0 using namespace std; int a[25+5][25+5]={0}; int row_exist[25][25]={0}; int col_exist[25][25]={0}; int block_exist[25][25]={0}; int block_num(int row,int col,int box_size){ int i=row/box_size; int j=col/box_size; return i*box_size+j; } bool findzero(int size,int &row,int &col){ for(row=0;row<size;++row){ for(col=0;col<size;++col){ if(a[row][col]==zero){ return true; } } } return false; } bool row_used(int row,int size,int ans){ for(int col=0;col<size;++col){ if(a[row][col]==ans){ return true; } } return false; } bool col_used(int col,int size,int ans){ for(int row=0;row<size;++row){ if(a[row][col]==ans){ return true; } } return false; } bool box_used(int box_row,int box_col,int box_size,int ans){ for(int row=0;row<box_size;++row){ for(int col=0;col<box_size;++col){ if(a[row+box_row][col+box_col]==ans){ return true; } } } return false; } bool check(int size,int box_size,int row,int col,int ans){ return !row_used(row,size,ans) && !col_used(col,size,ans) && !box_used(row-row%box_size,col-col%box_size,box_size,ans) && a[row][col]==zero; } bool solve(int size,int box_size){ int col,row; if(!findzero(size,row,col)){ return true; } for(int ans=1;ans<=size;++ans){ if(row_exist[row][ans] || col_exist[col][ans] || block_exist[block_num(row,col,box_size)][ans]){ continue; } if( check(size,box_size,row,col,ans) ){ a[row][col]=ans; row_exist[row][ans]=true; col_exist[col][ans]=true; block_exist[block_num(row,col,box_size)][ans]=true; if(solve(size,box_size)){ return true; } a[row][col]=zero; row_exist[row][ans]=false; col_exist[col][ans]=false; block_exist[block_num(row,col,box_size)][ans]=false; } } return false; } void print(int size){ for(int i=0;i<size;++i){ for(int j=0;j<size;++j){ cout<<a[i][j]<<" "; } cout<<endl; } } int main(){ vector<int> v; int tmp,size,box_size; while(scanf(" %d",&tmp)!=EOF){ v.push_back(tmp); } switch(v.size()){ case 16: size=4; box_size=2; break; case 81: size=9; box_size=3; break; case 256: size=16; box_size=4; break; case 625: size=25; box_size=5; break; } for(int i=0;i<size;++i){ for(int j=0;j<size;++j){ row_exist[i][v[size*i+j]]=true; col_exist[j][v[size*i+j]]=true; block_exist[block_num(i,j,box_size)][v[size*i+j]]=true; a[i][j]=v[size*i+j]; } } if(solve(size,box_size)){ print(size); }else{ cout<<"NO\n"; } return 0; }
20.166667
142
0.587528
[ "vector" ]
dbdc353244703be73ea620238e54283c8e0541f0
11,336
cpp
C++
Source/Falcor/Core/API/D3D12/D3D12RootSignature.cpp
NVIDIAGameWorks/Falcor
b6b54c13f64ca81a45fc43fd127b93d85cd9c073
[ "BSD-3-Clause" ]
1,615
2017-07-28T05:41:39.000Z
2022-03-31T16:31:57.000Z
Source/Falcor/Core/API/D3D12/D3D12RootSignature.cpp
NVIDIAGameWorks/Falcor
b6b54c13f64ca81a45fc43fd127b93d85cd9c073
[ "BSD-3-Clause" ]
232
2017-08-03T10:58:41.000Z
2022-03-31T16:17:46.000Z
Source/Falcor/Core/API/D3D12/D3D12RootSignature.cpp
NVIDIAGameWorks/Falcor
b6b54c13f64ca81a45fc43fd127b93d85cd9c073
[ "BSD-3-Clause" ]
383
2017-07-30T04:28:34.000Z
2022-03-30T05:12:13.000Z
/*************************************************************************** # Copyright (c) 2015-21, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************/ #include "stdafx.h" #include "D3D12RootSignature.h" #include "D3D12State.h" #include "Core/API/Device.h" #include "Core/Program/ProgramReflection.h" namespace Falcor { D3D12RootSignature::SharedPtr D3D12RootSignature::spEmptySig; uint64_t D3D12RootSignature::sObjCount = 0; D3D12RootSignature::Desc& D3D12RootSignature::Desc::addDescriptorSet(const DescriptorSetLayout& setLayout) { assert(mRootConstants.empty()); // For now we disallow both root-constants and descriptor-sets assert(setLayout.getRangeCount()); mSets.push_back(setLayout); return *this; } D3D12RootSignature::Desc& D3D12RootSignature::Desc::addRootDescriptor(DescType type, uint32_t regIndex, uint32_t spaceIndex, ShaderVisibility visibility) { RootDescriptorDesc desc; desc.type = type; desc.regIndex = regIndex; desc.spaceIndex = spaceIndex; desc.visibility = visibility; mRootDescriptors.push_back(desc); return *this; } D3D12RootSignature::Desc& D3D12RootSignature::Desc::addRootConstants(uint32_t regIndex, uint32_t spaceIndex, uint32_t count) { assert(mSets.empty()); // For now we disallow both root-constants and descriptor-sets RootConstantsDesc desc; desc.count = count; desc.regIndex = regIndex; desc.spaceIndex = spaceIndex; mRootConstants.push_back(desc); return *this; } D3D12RootSignature::D3D12RootSignature(const Desc& desc) : mDesc(desc) { sObjCount++; // Get vector of root parameters RootSignatureParams params; initD3D12RootParams(mDesc, params); // Create the root signature D3D12_VERSIONED_ROOT_SIGNATURE_DESC versionedDesc = {}; versionedDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; D3D12_ROOT_SIGNATURE_DESC1& d3dDesc = versionedDesc.Desc_1_1; d3dDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; mSizeInBytes = params.signatureSizeInBytes; mElementByteOffset = params.elementByteOffset; d3dDesc.pParameters = params.rootParams.data(); d3dDesc.NumParameters = (uint32_t)params.rootParams.size(); d3dDesc.pStaticSamplers = nullptr; d3dDesc.NumStaticSamplers = 0; // Create versioned root signature ID3DBlobPtr pSigBlob; ID3DBlobPtr pErrorBlob; HRESULT hr = D3D12SerializeVersionedRootSignature(&versionedDesc, &pSigBlob, &pErrorBlob); if (FAILED(hr)) { std::string msg = convertBlobToString(pErrorBlob.GetInterfacePtr()); throw RuntimeError("Failed to create root signature: " + msg); } if (mSizeInBytes > sizeof(uint32_t) * D3D12_MAX_ROOT_COST) { throw RuntimeError("Root signature cost is too high. D3D12 root signatures are limited to 64 DWORDs, trying to create a signature with {} DWORDs.", mSizeInBytes / sizeof(uint32_t)); } createApiHandle(pSigBlob); } D3D12RootSignature::~D3D12RootSignature() { sObjCount--; if (spEmptySig && sObjCount == 1) // That's right, 1. It means spEmptySig is the only object { spEmptySig = nullptr; } } D3D12RootSignature::SharedPtr D3D12RootSignature::getEmpty() { if (spEmptySig) return spEmptySig; return create(Desc()); } D3D12RootSignature::SharedPtr D3D12RootSignature::create(const Desc& desc) { bool empty = desc.mSets.empty() && desc.mRootDescriptors.empty() && desc.mRootConstants.empty(); if (empty && spEmptySig) return spEmptySig; SharedPtr pSig = SharedPtr(new D3D12RootSignature(desc)); if (empty) spEmptySig = pSig; return pSig; } ReflectionResourceType::ShaderAccess getRequiredShaderAccess(D3D12RootSignature::DescType type) { switch (type) { case D3D12RootSignature::DescType::TextureSrv: case D3D12RootSignature::DescType::RawBufferSrv: case D3D12RootSignature::DescType::TypedBufferSrv: case D3D12RootSignature::DescType::StructuredBufferSrv: case D3D12RootSignature::DescType::AccelerationStructureSrv: case D3D12RootSignature::DescType::Cbv: case D3D12RootSignature::DescType::Sampler: return ReflectionResourceType::ShaderAccess::Read; case D3D12RootSignature::DescType::TextureUav: case D3D12RootSignature::DescType::RawBufferUav: case D3D12RootSignature::DescType::TypedBufferUav: case D3D12RootSignature::DescType::StructuredBufferUav: return ReflectionResourceType::ShaderAccess::ReadWrite; default: should_not_get_here(); return ReflectionResourceType::ShaderAccess(-1); } } // Add the descriptor set layouts from `pBlock` to the list // of descriptor set layouts being built for a root signature. // static void addParamBlockSets( const ParameterBlockReflection* pBlock, D3D12RootSignature::Desc& ioDesc) { auto defaultConstantBufferInfo = pBlock->getDefaultConstantBufferBindingInfo(); if (defaultConstantBufferInfo.useRootConstants) { uint32_t count = uint32_t(pBlock->getElementType()->getByteSize() / sizeof(uint32_t)); ioDesc.addRootConstants(defaultConstantBufferInfo.regIndex, defaultConstantBufferInfo.regSpace, count); } uint32_t setCount = pBlock->getD3D12DescriptorSetCount(); for (uint32_t s = 0; s < setCount; ++s) { auto& setLayout = pBlock->getD3D12DescriptorSetLayout(s); ioDesc.addDescriptorSet(setLayout); } uint32_t parameterBlockRangeCount = pBlock->getParameterBlockSubObjectRangeCount(); for (uint32_t i = 0; i < parameterBlockRangeCount; ++i) { uint32_t rangeIndex = pBlock->getParameterBlockSubObjectRangeIndex(i); auto& resourceRange = pBlock->getResourceRange(rangeIndex); auto& bindingInfo = pBlock->getResourceRangeBindingInfo(rangeIndex); assert(bindingInfo.flavor == ParameterBlockReflection::ResourceRangeBindingInfo::Flavor::ParameterBlock); assert(resourceRange.count == 1); // TODO: The code here does not handle arrays of sub-objects addParamBlockSets(bindingInfo.pSubObjectReflector.get(), ioDesc); } } // Add the root descriptors from `pBlock` to the root signature being built. static void addRootDescriptors( const ParameterBlockReflection* pBlock, D3D12RootSignature::Desc& ioDesc) { uint32_t rootDescriptorRangeCount = pBlock->getRootDescriptorRangeCount(); for (uint32_t i = 0; i < rootDescriptorRangeCount; ++i) { uint32_t rangeIndex = pBlock->getRootDescriptorRangeIndex(i); auto& resourceRange = pBlock->getResourceRange(rangeIndex); auto& bindingInfo = pBlock->getResourceRangeBindingInfo(rangeIndex); assert(bindingInfo.isRootDescriptor()); assert(resourceRange.count == 1); // Root descriptors cannot be arrays ioDesc.addRootDescriptor(resourceRange.descriptorType, bindingInfo.regIndex, bindingInfo.regSpace); // TODO: Using shader visibility *all* for now, get this info from reflection if we have it. } // Iterate over constant buffers and parameter blocks to recursively add their root descriptors. uint32_t resourceRangeCount = pBlock->getResourceRangeCount(); for (uint32_t rangeIndex = 0; rangeIndex < resourceRangeCount; ++rangeIndex) { auto& bindingInfo = pBlock->getResourceRangeBindingInfo(rangeIndex); if (bindingInfo.flavor != ParameterBlockReflection::ResourceRangeBindingInfo::Flavor::ConstantBuffer && bindingInfo.flavor != ParameterBlockReflection::ResourceRangeBindingInfo::Flavor::ParameterBlock) continue; auto& resourceRange = pBlock->getResourceRange(rangeIndex); assert(resourceRange.count == 1); // TODO: The code here does not handle arrays of sub-objects addRootDescriptors(bindingInfo.pSubObjectReflector.get(), ioDesc); } } D3D12RootSignature::SharedPtr D3D12RootSignature::create(const ProgramReflection* pReflector) { assert(pReflector); D3D12RootSignature::Desc d; addParamBlockSets(pReflector->getDefaultParameterBlock().get(), d); addRootDescriptors(pReflector->getDefaultParameterBlock().get(), d); return D3D12RootSignature::create(d); } void D3D12RootSignature::createApiHandle(ID3DBlobPtr pSigBlob) { Device::ApiHandle pDevice = gpDevice->getApiHandle(); FALCOR_D3D_CALL(pDevice->CreateRootSignature(0, pSigBlob->GetBufferPointer(), pSigBlob->GetBufferSize(), IID_PPV_ARGS(&mApiHandle))); } template<bool forGraphics> static void bindRootSigCommon(CopyContext* pCtx, const D3D12RootSignature::ApiHandle& rootSig) { if (forGraphics) { pCtx->getLowLevelData()->getCommandList()->SetGraphicsRootSignature(rootSig); } else { pCtx->getLowLevelData()->getCommandList()->SetComputeRootSignature(rootSig); } } void D3D12RootSignature::bindForCompute(CopyContext* pCtx) { bindRootSigCommon<false>(pCtx, mApiHandle); } void D3D12RootSignature::bindForGraphics(CopyContext* pCtx) { bindRootSigCommon<true>(pCtx, mApiHandle); } }
42.456929
204
0.68428
[ "object", "vector" ]
dbe5082232c32bb50afe93b199a8416551dea5f7
19,942
cpp
C++
MonoNative.Tests/mscorlib/System/mscorlib_System_Array_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/mscorlib_System_Array_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/mscorlib_System_Array_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System // Name: Array // C++ Typed Name: mscorlib::System::Array #include <gtest/gtest.h> #include <mscorlib/System/mscorlib_System_Array.h> #include <mscorlib/System/mscorlib_System_Type.h> #include <mscorlib/System/mscorlib_System_String.h> namespace mscorlib { namespace System { //Public Methods Tests // Method GetLength // Signature: mscorlib::System::Int32 dimension TEST(mscorlib_System_Array_Fixture,GetLength_Test) { } // Method GetLongLength // Signature: mscorlib::System::Int32 dimension TEST(mscorlib_System_Array_Fixture,GetLongLength_Test) { } // Method GetLowerBound // Signature: mscorlib::System::Int32 dimension TEST(mscorlib_System_Array_Fixture,GetLowerBound_Test) { } // Method GetValue // Signature: std::vector<mscorlib::System::Int32*> indices TEST(mscorlib_System_Array_Fixture,GetValue_1_Test) { } // Method SetValue // Signature: mscorlib::System::Object value, std::vector<mscorlib::System::Int32*> indices TEST(mscorlib_System_Array_Fixture,SetValue_1_Test) { } // Method GetEnumerator // Signature: TEST(mscorlib_System_Array_Fixture,GetEnumerator_Test) { } // Method GetUpperBound // Signature: mscorlib::System::Int32 dimension TEST(mscorlib_System_Array_Fixture,GetUpperBound_Test) { } // Method GetValue // Signature: mscorlib::System::Int32 index TEST(mscorlib_System_Array_Fixture,GetValue_2_Test) { } // Method GetValue // Signature: mscorlib::System::Int32 index1, mscorlib::System::Int32 index2 TEST(mscorlib_System_Array_Fixture,GetValue_3_Test) { } // Method GetValue // Signature: mscorlib::System::Int32 index1, mscorlib::System::Int32 index2, mscorlib::System::Int32 index3 TEST(mscorlib_System_Array_Fixture,GetValue_4_Test) { } // Method GetValue // Signature: mscorlib::System::Int64 index TEST(mscorlib_System_Array_Fixture,GetValue_5_Test) { } // Method GetValue // Signature: mscorlib::System::Int64 index1, mscorlib::System::Int64 index2 TEST(mscorlib_System_Array_Fixture,GetValue_6_Test) { } // Method GetValue // Signature: mscorlib::System::Int64 index1, mscorlib::System::Int64 index2, mscorlib::System::Int64 index3 TEST(mscorlib_System_Array_Fixture,GetValue_7_Test) { } // Method SetValue // Signature: mscorlib::System::Object value, mscorlib::System::Int64 index TEST(mscorlib_System_Array_Fixture,SetValue_2_Test) { } // Method SetValue // Signature: mscorlib::System::Object value, mscorlib::System::Int64 index1, mscorlib::System::Int64 index2 TEST(mscorlib_System_Array_Fixture,SetValue_3_Test) { } // Method SetValue // Signature: mscorlib::System::Object value, mscorlib::System::Int64 index1, mscorlib::System::Int64 index2, mscorlib::System::Int64 index3 TEST(mscorlib_System_Array_Fixture,SetValue_4_Test) { } // Method SetValue // Signature: mscorlib::System::Object value, mscorlib::System::Int32 index TEST(mscorlib_System_Array_Fixture,SetValue_5_Test) { } // Method SetValue // Signature: mscorlib::System::Object value, mscorlib::System::Int32 index1, mscorlib::System::Int32 index2 TEST(mscorlib_System_Array_Fixture,SetValue_6_Test) { } // Method SetValue // Signature: mscorlib::System::Object value, mscorlib::System::Int32 index1, mscorlib::System::Int32 index2, mscorlib::System::Int32 index3 TEST(mscorlib_System_Array_Fixture,SetValue_7_Test) { } // Method GetValue // Signature: std::vector<mscorlib::System::Int64*> indices TEST(mscorlib_System_Array_Fixture,GetValue_8_Test) { } // Method SetValue // Signature: mscorlib::System::Object value, std::vector<mscorlib::System::Int64*> indices TEST(mscorlib_System_Array_Fixture,SetValue_8_Test) { } // Method Clone // Signature: TEST(mscorlib_System_Array_Fixture,Clone_Test) { } // Method Initialize // Signature: TEST(mscorlib_System_Array_Fixture,Initialize_Test) { } // Method CopyTo // Signature: mscorlib::System::Array array, mscorlib::System::Int32 index TEST(mscorlib_System_Array_Fixture,CopyTo_1_Test) { } // Method CopyTo // Signature: mscorlib::System::Array array, mscorlib::System::Int64 index TEST(mscorlib_System_Array_Fixture,CopyTo_2_Test) { } //Public Static Methods Tests // Method CreateInstance // Signature: mscorlib::System::Type elementType, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,CreateInstance_1_StaticTest) { } // Method CreateInstance // Signature: mscorlib::System::Type elementType, mscorlib::System::Int32 length1, mscorlib::System::Int32 length2 TEST(mscorlib_System_Array_Fixture,CreateInstance_2_StaticTest) { } // Method CreateInstance // Signature: mscorlib::System::Type elementType, mscorlib::System::Int32 length1, mscorlib::System::Int32 length2, mscorlib::System::Int32 length3 TEST(mscorlib_System_Array_Fixture,CreateInstance_3_StaticTest) { } // Method CreateInstance // Signature: mscorlib::System::Type elementType, std::vector<mscorlib::System::Int32*> lengths TEST(mscorlib_System_Array_Fixture,CreateInstance_4_StaticTest) { } // Method CreateInstance // Signature: mscorlib::System::Type elementType, std::vector<mscorlib::System::Int32*> lengths, std::vector<mscorlib::System::Int32*> lowerBounds TEST(mscorlib_System_Array_Fixture,CreateInstance_5_StaticTest) { } // Method CreateInstance // Signature: mscorlib::System::Type elementType, std::vector<mscorlib::System::Int64*> lengths TEST(mscorlib_System_Array_Fixture,CreateInstance_6_StaticTest) { } // Method BinarySearch // Signature: mscorlib::System::Array array, mscorlib::System::Object value TEST(mscorlib_System_Array_Fixture,BinarySearch_1_StaticTest) { } // Method BinarySearch // Signature: mscorlib::System::Array array, mscorlib::System::Object value, mscorlib::System::Collections::IComparer comparer TEST(mscorlib_System_Array_Fixture,BinarySearch_2_StaticTest) { } // Method BinarySearch // Signature: mscorlib::System::Array array, mscorlib::System::Int32 index, mscorlib::System::Int32 length, mscorlib::System::Object value TEST(mscorlib_System_Array_Fixture,BinarySearch_3_StaticTest) { } // Method BinarySearch // Signature: mscorlib::System::Array array, mscorlib::System::Int32 index, mscorlib::System::Int32 length, mscorlib::System::Object value, mscorlib::System::Collections::IComparer comparer TEST(mscorlib_System_Array_Fixture,BinarySearch_4_StaticTest) { } // Method Clear // Signature: mscorlib::System::Array array, mscorlib::System::Int32 index, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,Clear_StaticTest) { } // Method Copy // Signature: mscorlib::System::Array sourceArray, mscorlib::System::Array destinationArray, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,Copy_1_StaticTest) { } // Method Copy // Signature: mscorlib::System::Array sourceArray, mscorlib::System::Int32 sourceIndex, mscorlib::System::Array destinationArray, mscorlib::System::Int32 destinationIndex, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,Copy_2_StaticTest) { } // Method Copy // Signature: mscorlib::System::Array sourceArray, mscorlib::System::Int64 sourceIndex, mscorlib::System::Array destinationArray, mscorlib::System::Int64 destinationIndex, mscorlib::System::Int64 length TEST(mscorlib_System_Array_Fixture,Copy_3_StaticTest) { } // Method Copy // Signature: mscorlib::System::Array sourceArray, mscorlib::System::Array destinationArray, mscorlib::System::Int64 length TEST(mscorlib_System_Array_Fixture,Copy_4_StaticTest) { } // Method IndexOf // Signature: mscorlib::System::Array array, mscorlib::System::Object value TEST(mscorlib_System_Array_Fixture,IndexOf_1_StaticTest) { } // Method IndexOf // Signature: mscorlib::System::Array array, mscorlib::System::Object value, mscorlib::System::Int32 startIndex TEST(mscorlib_System_Array_Fixture,IndexOf_2_StaticTest) { } // Method IndexOf // Signature: mscorlib::System::Array array, mscorlib::System::Object value, mscorlib::System::Int32 startIndex, mscorlib::System::Int32 count TEST(mscorlib_System_Array_Fixture,IndexOf_3_StaticTest) { } // Method LastIndexOf // Signature: mscorlib::System::Array array, mscorlib::System::Object value TEST(mscorlib_System_Array_Fixture,LastIndexOf_1_StaticTest) { } // Method LastIndexOf // Signature: mscorlib::System::Array array, mscorlib::System::Object value, mscorlib::System::Int32 startIndex TEST(mscorlib_System_Array_Fixture,LastIndexOf_2_StaticTest) { } // Method LastIndexOf // Signature: mscorlib::System::Array array, mscorlib::System::Object value, mscorlib::System::Int32 startIndex, mscorlib::System::Int32 count TEST(mscorlib_System_Array_Fixture,LastIndexOf_3_StaticTest) { } // Method Reverse // Signature: mscorlib::System::Array array TEST(mscorlib_System_Array_Fixture,Reverse_1_StaticTest) { } // Method Reverse // Signature: mscorlib::System::Array array, mscorlib::System::Int32 index, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,Reverse_2_StaticTest) { } // Method Sort // Signature: mscorlib::System::Array array TEST(mscorlib_System_Array_Fixture,Sort_1_StaticTest) { } // Method Sort // Signature: mscorlib::System::Array keys, mscorlib::System::Array items TEST(mscorlib_System_Array_Fixture,Sort_2_StaticTest) { } // Method Sort // Signature: mscorlib::System::Array array, mscorlib::System::Collections::IComparer comparer TEST(mscorlib_System_Array_Fixture,Sort_3_StaticTest) { } // Method Sort // Signature: mscorlib::System::Array array, mscorlib::System::Int32 index, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,Sort_4_StaticTest) { } // Method Sort // Signature: mscorlib::System::Array keys, mscorlib::System::Array items, mscorlib::System::Collections::IComparer comparer TEST(mscorlib_System_Array_Fixture,Sort_5_StaticTest) { } // Method Sort // Signature: mscorlib::System::Array keys, mscorlib::System::Array items, mscorlib::System::Int32 index, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,Sort_6_StaticTest) { } // Method Sort // Signature: mscorlib::System::Array array, mscorlib::System::Int32 index, mscorlib::System::Int32 length, mscorlib::System::Collections::IComparer comparer TEST(mscorlib_System_Array_Fixture,Sort_7_StaticTest) { } // Method Sort // Signature: mscorlib::System::Array keys, mscorlib::System::Array items, mscorlib::System::Int32 index, mscorlib::System::Int32 length, mscorlib::System::Collections::IComparer comparer TEST(mscorlib_System_Array_Fixture,Sort_8_StaticTest) { } // Method Sort // Signature: std::vector<T*> array TEST(mscorlib_System_Array_Fixture,Sort_9_StaticTest) { } // Method Sort // Signature: std::vector<TKey*> keys, std::vector<TValue*> items TEST(mscorlib_System_Array_Fixture,Sort_10_StaticTest) { } // Method Sort // Signature: std::vector<T*> array, mscorlib::System::Collections::Generic::IComparer<T> comparer TEST(mscorlib_System_Array_Fixture,Sort_11_StaticTest) { } // Method Sort // Signature: std::vector<TKey*> keys, std::vector<TValue*> items, mscorlib::System::Collections::Generic::IComparer<TKey> comparer TEST(mscorlib_System_Array_Fixture,Sort_12_StaticTest) { } // Method Sort // Signature: std::vector<T*> array, mscorlib::System::Int32 index, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,Sort_13_StaticTest) { } // Method Sort // Signature: std::vector<TKey*> keys, std::vector<TValue*> items, mscorlib::System::Int32 index, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,Sort_14_StaticTest) { } // Method Sort // Signature: std::vector<T*> array, mscorlib::System::Int32 index, mscorlib::System::Int32 length, mscorlib::System::Collections::Generic::IComparer<T> comparer TEST(mscorlib_System_Array_Fixture,Sort_15_StaticTest) { } // Method Sort // Signature: std::vector<TKey*> keys, std::vector<TValue*> items, mscorlib::System::Int32 index, mscorlib::System::Int32 length, mscorlib::System::Collections::Generic::IComparer<TKey> comparer TEST(mscorlib_System_Array_Fixture,Sort_16_StaticTest) { } // Method Sort // Signature: std::vector<T*> array, mscorlib::Callback<mscorlib::System::Int32 (T , T )> comparison TEST(mscorlib_System_Array_Fixture,Sort_17_StaticTest) { } // Method Resize // Signature: std::vector<T*> array, mscorlib::System::Int32 newSize TEST(mscorlib_System_Array_Fixture,Resize_StaticTest) { } // Method TrueForAll // Signature: std::vector<T*> array, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,TrueForAll_StaticTest) { } // Method ForEach // Signature: std::vector<T*> array, mscorlib::Callback<void (T )> action TEST(mscorlib_System_Array_Fixture,ForEach_StaticTest) { } // Method ConvertAll // Signature: std::vector<TInput*> array, mscorlib::Callback<TOutput (TInput )> converter TEST(mscorlib_System_Array_Fixture,ConvertAll_StaticTest) { } // Method FindLastIndex // Signature: std::vector<T*> array, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,FindLastIndex_1_StaticTest) { } // Method FindLastIndex // Signature: std::vector<T*> array, mscorlib::System::Int32 startIndex, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,FindLastIndex_2_StaticTest) { } // Method FindLastIndex // Signature: std::vector<T*> array, mscorlib::System::Int32 startIndex, mscorlib::System::Int32 count, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,FindLastIndex_3_StaticTest) { } // Method FindIndex // Signature: std::vector<T*> array, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,FindIndex_1_StaticTest) { } // Method FindIndex // Signature: std::vector<T*> array, mscorlib::System::Int32 startIndex, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,FindIndex_2_StaticTest) { } // Method FindIndex // Signature: std::vector<T*> array, mscorlib::System::Int32 startIndex, mscorlib::System::Int32 count, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,FindIndex_3_StaticTest) { } // Method BinarySearch // Signature: std::vector<T*> array, T value TEST(mscorlib_System_Array_Fixture,BinarySearch_5_StaticTest) { } // Method BinarySearch // Signature: std::vector<T*> array, T value, mscorlib::System::Collections::Generic::IComparer<T> comparer TEST(mscorlib_System_Array_Fixture,BinarySearch_6_StaticTest) { } // Method BinarySearch // Signature: std::vector<T*> array, mscorlib::System::Int32 index, mscorlib::System::Int32 length, T value TEST(mscorlib_System_Array_Fixture,BinarySearch_7_StaticTest) { } // Method BinarySearch // Signature: std::vector<T*> array, mscorlib::System::Int32 index, mscorlib::System::Int32 length, T value, mscorlib::System::Collections::Generic::IComparer<T> comparer TEST(mscorlib_System_Array_Fixture,BinarySearch_8_StaticTest) { } // Method IndexOf // Signature: std::vector<T*> array, T value TEST(mscorlib_System_Array_Fixture,IndexOf_7_StaticTest) { } // Method IndexOf // Signature: std::vector<T*> array, T value, mscorlib::System::Int32 startIndex TEST(mscorlib_System_Array_Fixture,IndexOf_8_StaticTest) { } // Method IndexOf // Signature: std::vector<T*> array, T value, mscorlib::System::Int32 startIndex, mscorlib::System::Int32 count TEST(mscorlib_System_Array_Fixture,IndexOf_9_StaticTest) { } // Method LastIndexOf // Signature: std::vector<T*> array, T value TEST(mscorlib_System_Array_Fixture,LastIndexOf_4_StaticTest) { } // Method LastIndexOf // Signature: std::vector<T*> array, T value, mscorlib::System::Int32 startIndex TEST(mscorlib_System_Array_Fixture,LastIndexOf_5_StaticTest) { } // Method LastIndexOf // Signature: std::vector<T*> array, T value, mscorlib::System::Int32 startIndex, mscorlib::System::Int32 count TEST(mscorlib_System_Array_Fixture,LastIndexOf_6_StaticTest) { } // Method FindAll // Signature: std::vector<T*> array, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,FindAll_StaticTest) { } // Method Exists // Signature: std::vector<T*> array, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,Exists_StaticTest) { } // Method AsReadOnly // Signature: std::vector<T*> array TEST(mscorlib_System_Array_Fixture,AsReadOnly_StaticTest) { } // Method Find // Signature: std::vector<T*> array, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,Find_StaticTest) { } // Method FindLast // Signature: std::vector<T*> array, mscorlib::Callback<mscorlib::System::Boolean (T )> match TEST(mscorlib_System_Array_Fixture,FindLast_StaticTest) { } // Method ConstrainedCopy // Signature: mscorlib::System::Array sourceArray, mscorlib::System::Int32 sourceIndex, mscorlib::System::Array destinationArray, mscorlib::System::Int32 destinationIndex, mscorlib::System::Int32 length TEST(mscorlib_System_Array_Fixture,ConstrainedCopy_StaticTest) { } //Public Properties Tests // Property Length // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_Array_Fixture,get_Length_Test) { } // Property LongLength // Return Type: mscorlib::System::Int64 // Property Get Method TEST(mscorlib_System_Array_Fixture,get_LongLength_Test) { } // Property Rank // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_Array_Fixture,get_Rank_Test) { } // Property IsSynchronized // Return Type: mscorlib::System::Boolean // Property Get Method TEST(mscorlib_System_Array_Fixture,get_IsSynchronized_Test) { } // Property SyncRoot // Return Type: mscorlib::System::Object // Property Get Method TEST(mscorlib_System_Array_Fixture,get_SyncRoot_Test) { } // Property IsFixedSize // Return Type: mscorlib::System::Boolean // Property Get Method TEST(mscorlib_System_Array_Fixture,get_IsFixedSize_Test) { } // Property IsReadOnly // Return Type: mscorlib::System::Boolean // Property Get Method TEST(mscorlib_System_Array_Fixture,get_IsReadOnly_Test) { } } }
24.319512
205
0.711614
[ "object", "vector" ]
dbe5647e91793ee5fdeaf9097ca7b727a203acc8
1,906
cpp
C++
QuantExt/test/logquote.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
QuantExt/test/logquote.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
QuantExt/test/logquote.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
1
2022-02-07T02:04:10.000Z
2022-02-07T02:04:10.000Z
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include "toplevelfixture.hpp" #include <boost/test/unit_test.hpp> #include <ql/quotes/simplequote.hpp> #include <qle/quotes/logquote.hpp> using namespace QuantLib; using namespace boost::unit_test_framework; using QuantExt::LogQuote; BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture) BOOST_AUTO_TEST_SUITE(LogQuoteTest) BOOST_AUTO_TEST_CASE(testLogQuote) { BOOST_TEST_MESSAGE("Testing QuantExt::LogQuote..."); boost::shared_ptr<SimpleQuote> quote(new QuantLib::SimpleQuote(1.0)); Handle<Quote> qh(quote); Handle<Quote> logQuote(boost::shared_ptr<Quote>(new LogQuote(qh))); BOOST_CHECK_EQUAL(logQuote->value(), std::log(quote->value())); quote->setValue(2.0); BOOST_CHECK_EQUAL(logQuote->value(), std::log(quote->value())); quote->setValue(3.0); BOOST_CHECK_EQUAL(logQuote->value(), std::log(quote->value())); quote->setValue(123.0); BOOST_CHECK_EQUAL(logQuote->value(), std::log(quote->value())); // LogQuote should throw when a negative value is set BOOST_CHECK_THROW(quote->setValue(-1.0), std::exception); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
32.305085
73
0.756558
[ "model" ]
dbebbc1b6c3d163a32a469f91c886486f3ceb975
5,949
cpp
C++
02_gtkmm/src/main_updating_plot.cpp
fdcl-gwu/cpp-plots
cdb7d7f571b1ff336e239949f6915195b8c4f4aa
[ "MIT" ]
3
2020-07-27T01:54:12.000Z
2022-02-08T20:00:12.000Z
02_gtkmm/src/main_updating_plot.cpp
fdcl-gwu/cpp-plots
cdb7d7f571b1ff336e239949f6915195b8c4f4aa
[ "MIT" ]
1
2019-08-23T12:06:21.000Z
2019-08-24T05:49:50.000Z
02_gtkmm/src/main_updating_plot.cpp
fdcl-gwu/cpp-plots
cdb7d7f571b1ff336e239949f6915195b8c4f4aa
[ "MIT" ]
1
2022-03-31T07:34:19.000Z
2022-03-31T07:34:19.000Z
/* * Copyright (c) 2019 Flight Dynamics and Control Lab * * 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 "gtkmm-plplot.h" #include <gtkmm/application.h> #include <glibmm/miscutils.h> #include <glib.h> #include <gtkmm.h> #include <gtkmm/window.h> #include <gtkmm/grid.h> #include <iostream> #include <pthread.h> #include <unistd.h> #define NUM_THREADS 2 struct Params { int argc; char **argv; }; pthread_mutex_t mutex; bool system_on = true; std::valarray<double> x(20), y(20); Params params; namespace fdcl { class gui : public Gtk::Window { private: Gtk::PLplot::PlotData2D plot_ax, *plot_keep_ax; Gtk::PLplot::PlotData2D *plot_update; Gtk::PLplot::Plot2D *plot_keep; Gtk::PLplot::Plot2D *plot; Gtk::PLplot::Canvas canvas; Gtk::Grid grid; Gtk::Grid button_grid; Gtk::Button close; public: gui(std::valarray<double> &x, std::valarray<double> &y): plot_ax(x, y), close("Exit") { canvas.set_can_focus(false); std::valarray<double> xx(10), yy(10); for (int i = 0; i < 10; i++) { xx[i] = i; yy[i] = 5.0; } plot_keep_ax = Gtk::manage(new Gtk::PLplot::PlotData2D(xx, yy)); plot_keep = Gtk::manage(new Gtk::PLplot::Plot2D(*plot_keep_ax)); canvas.add_plot(*plot_keep); plot = Gtk::manage(new Gtk::PLplot::Plot2D(plot_ax)); canvas.add_plot(*plot); // // Set window size int w = 720, h = 580; set_default_size(w, h); Gdk::Geometry geometry; geometry.min_aspect = geometry.max_aspect = double(w) / double(h); set_geometry_hints(*this, geometry, Gdk::HINT_ASPECT); canvas.set_hexpand(true); canvas.set_vexpand(true); button_grid.set_row_spacing(5); button_grid.set_column_spacing(5); button_grid.set_column_homogeneous(false); close.signal_clicked().connect(sigc::mem_fun(*this, \ &gui::on_close_button_clicked)); button_grid.attach(close, 1, 0, 1, 1); grid.attach(button_grid, 0, 0, 1, 1); grid.attach(canvas, 0, 1, 1, 1); add(grid); grid.show_all(); //create slot for timeout signal int timeout_value = 50; //in ms 20 Hz sigc::slot<bool> my_slot = sigc::mem_fun(*this, &gui::on_timeout); Glib::signal_timeout().connect(my_slot, timeout_value); } void on_close_button_clicked(void) { hide(); } bool on_timeout(void) { pthread_mutex_lock(&mutex); canvas.remove_plot(*plot); // Gtk::PLplot::Plot *curr_plot; // auto curr_plot = canvas.get_plot(0); // canvas.remove_plot(*curr_plot); plot_update = Gtk::manage(new Gtk::PLplot::PlotData2D(x, y)); plot = Gtk::manage(new Gtk::PLplot::Plot2D(*plot_update)); // std::cout << plot << std::endl; canvas.add_plot(*plot); // canvas.remove_plot(1); // canvas. pthread_mutex_unlock(&mutex); return true; } bool on_plplot_drawing_area_double_click(GdkEventButton *event) { if (event->type == GDK_2BUTTON_PRESS) { // plplot_drawing_area.set_region(xmin, xmax, ymin, ymax); } return false; } }; // end of class gui } // end of namespace fdcl bool Gtk::PLplot::Canvas::on_motion_notify_event(GdkEventMotion *event) { return true; } void thread_gui(void) { for (int i = 0; i < 20; i++) { x[i] = i; y[i] = 2.0 * i; } Glib::set_application_name("gtkmm-plplot-update"); auto app = Gtk::Application::create(params.argc, params.argv, \ "com.gwu.fdcl"); fdcl::gui gui(x, y); app->run(gui); system_on = false; usleep(1000000); // 1 second std::cout << "GUI: thread closed!" << std::endl; } void *thread_change_data(void *thread_id) { while (system_on) { pthread_mutex_lock(&mutex); y[0] = y[0] + 0.01; pthread_mutex_unlock(&mutex); usleep(50000); // 50 millis } std::cout << "Closing change data thread .." << std::endl; pthread_exit(NULL); } int main(int argc, char *argv[]) { params.argc = argc; params.argv = argv; pthread_t threads[NUM_THREADS]; pthread_attr_t attr; struct sched_param param; int fifo_max_prio, fifo_min_prio; // Set thread attributes. pthread_attr_init(&attr); pthread_attr_setschedpolicy(&attr, SCHED_FIFO); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); fifo_max_prio = sched_get_priority_max(SCHED_FIFO); fifo_min_prio = sched_get_priority_min(SCHED_FIFO); param.sched_priority = fifo_max_prio / NUM_THREADS; pthread_attr_setschedparam(&attr, &param); pthread_create(&threads[0], &attr, thread_change_data, (void *) 1); thread_gui(); return 0; }
27.040909
80
0.635569
[ "geometry" ]
dbee0e0175a01880b387ce0f2071827f513bd59f
9,376
cpp
C++
lib_cvgutils/src/source/code_tests.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
lib_cvgutils/src/source/code_tests.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
lib_cvgutils/src/source/code_tests.cpp
MorS25/cvg_quadrotor_swarm
da75d02049163cf65fd7305bc46a16359a851c7c
[ "BSD-3-Clause" ]
null
null
null
#include "xmlfilereader.h" #include <cstdlib> #include <exception> #include <vector> #include <string> #include "matrixLib.h" #include "pruebastaticbool.h" #include <unistd.h> #include "cvg_utils_library.h" template <typename T> T my_function(int a, T t) { std::cout << "a: " << a << std::endl; return T(); } enum class myPrivateEnum { RED = 0, YELLOW = 1, GREEN = -1}; int main(int argc,char **argv) { std::cout << "Compile test" << std::to_string(10) << std::endl; // general tests { // std::cout << BOOST_CURRENT_FUNCTION << std::endl; // std::cout << __func__ << std::endl; // int b = 0; // std::cout << "b++" << b++ << std::endl; // b = 0; // std::cout << "++b" << ++b << std::endl; // for ( int i = 0; i<1; i++) { // std::cout << "i:" << i << std::endl; // } // char c = '\''; // if ( c == '\'' ) // std::cout << "c == '\''" << std::endl; // int i = 0, j = 0; // int* pi = &i; // const int* pi = &i; // pointer to (const inst) // int const* pi = &i; // pointer to (const inst) // int* const pi = &i; // (const pointer) to int // const int* const pi = &i; // (const pointer) to (const inst) // (*pi) = 3; // pi = &j; } // Pruebas con XMLFileReader { // std::cout << "Your DRONE_STACK is located in: " << std::getenv("DRONE_STACK") << std::endl; // try { // XMLFileReader my_xml_reader(std::string(std::getenv("DRONE_STACK"))+"/configs/drone0/ekf_state_estimator_config.xml"); // int result_int; // std::string result_string; // double result_double; // { // result_string = my_xml_reader.readStringValue( {"ekf_state_estimator_config","description"} ); // std::cout << "result: " << result_string << std::endl; // } // { // static const std::vector<std::string> vr = {"ekf_state_estimator_config","module_frequency"}; // result_double = my_xml_reader.readDoubleValue(vr); // std::cout << "result: " << result_double << std::endl; // } // { // static const std::vector<std::string> vr = {"ekf_state_estimator_config","state_model","number_of_states"}; // result_int = my_xml_reader.readIntValue(vr); // std::cout << "result: " << result_int << std::endl; // } // { // static const std::vector<std::string> vr = {"ekf_state_estimator_config","state_model","delete_this_parameter"}; // try { //// result_string = my_xml_reader.readStringValue(vr); // result_int = my_xml_reader.readIntValue(vr); // std::cout << "result_string: " << result_string << " result_string.size(): " << result_string.size() << std::endl; // } catch ( cvg_XMLFileReader_exception &e) { // throw cvg_XMLFileReader_exception(std::string("[cvg_XMLFileReader_exception! caller_function: ") + BOOST_CURRENT_FUNCTION + e.what() + "]\n"); // } // std::cout << "xml::value_location: {"; // for (auto it : vr) { // std::cout << "\'" << it << "\';"; // } std::cout << "}" << std::endl; // std::cout << BOOST_CURRENT_FUNCTION << std::endl; // } // } catch (std::exception &e) { // std::cout << "lib_cvgutils:code_tests, exception: " << e.what() << std::endl; // return 0; // } // Prueba, como se leerian varios doubles de una lista de xmls // std::string prueba_varios_doubles = "6.30 3.55"; // std::size_t pos; // double my_d = std::stod(prueba_varios_doubles, &pos); // std::cout << "my_d:" << my_d << " pos:" << pos << std::endl; // prueba_varios_doubles = prueba_varios_doubles.substr( pos); // my_d = std::stod(prueba_varios_doubles, &pos); // std::cout << "my_d:" << my_d << " pos:" << pos << std::endl; // prueba_varios_doubles = prueba_varios_doubles.substr( pos); // my_d = std::stod(prueba_varios_doubles, &pos); // std::cout << "my_d:" << my_d << " pos:" << pos << std::endl; } // prueba a definir un static const vector { // static const std::vector<std::string> vr = {"2", "3", "4"}; // for (int i=0; i < vr.size(); i++) { // std::cout << vr[i] << " "; // } std::cout << std::endl; } // test OpenCV matrix multiplication { // cv::Mat A, B, C, D, t; //// A = cv::Mat::eye(3,3,CV_32F); // B = cv::Mat::eye(4,4,CV_32F); // C = cv::Mat::zeros(3,1,CV_32F); // D = cv::Mat::zeros(3,1,CV_32F); // B.at<float>(0,0) = 2; // B.at<float>(0,2) = 3; // std::cout << "C: " << C << std::endl; // C.at<float>(0,0) = 1; // C.at<float>(1,0) = 0; // C.at<float>(2,0) = 3; // std::cout << "B: " << B << std::endl; // A = B(cv::Rect(0,0,3,3)); // std::cout << "A: " << A << std::endl; // std::cout << "C: " << C << std::endl; // std::cout << "D: " << D << std::endl; // D = A*C; // std::cout << "D: " << D << std::endl; // A = B(cv::Rect(0,0,3,3)); // t = B(cv::Rect(3,0,1,3)); // A.at<float>(0,0) = 5; // B.at<float>(0,3) = 5; // std::cout << "B: " << B << std::endl; // std::cout << "A: " << A << std::endl; // std::cout << "t: " << t << std::endl; // A = A.t(); // t = -A*t; // std::cout << "B, At: " << B << std::endl; // std::cout << "At: " << A << std::endl; // std::cout << "t, At*t: " << t << std::endl; } // prueba bool to integer conversion and viceversa { // int a; // bool a_b; // a = 1; // a_b = a; // std::cout << "(bool) = (int,1): " << a_b << std::endl; // a = 0; // a_b = a; // std::cout << "(bool) = (int,0): " << a_b << std::endl; // a_b = true; // a = a_b; // std::cout << "(int) = (bool,true): " << a_b << std::endl; // a_b = false; // a = a_b; // std::cout << "(int) = (bool,false): " << a_b << std::endl; } // prueba string comparison { // int idDrone = 0; // XMLFileReader my_xml_reader(std::string(std::getenv("DRONE_STACK"))+"/configs/drone"+std::to_string(idDrone)+"/trajectory_controller_config.xml"); // std::string init_control_mode_str, control_mode; // init_control_mode_str = my_xml_reader.readStringValue( {"trajectory_controller_config","init_control_mode"} ); // std::cout << "init_control_mode_str.compare(\"speed\"):"<< init_control_mode_str.compare("speed") << std::endl; // std::cout << "init_control_mode_str.compare(\"position\"):"<< init_control_mode_str.compare("position") << std::endl; // std::cout << "init_control_mode_str.compare(\"trajectory\"):"<< init_control_mode_str.compare("trajectory") << std::endl; // if ( init_control_mode_str.compare("speed") == 0 ) // { control_mode = "speed"; } // else { // if ( init_control_mode_str.compare("position") == 0 ) // { control_mode = "position"; } // else // "trajectory" // { control_mode = "trajectory"; } // } // std::cout << "init_control_mode_str: " << init_control_mode_str << " control_mode: " << control_mode << std::endl; } // Prueba initialization from xml_file { // for (int i=0; i<10; i++) { // std::cout << "i:" << i <<std::endl; // PruebaStaticBool my_trajectory_config(0); // PruebaStaticBool my_trajectory_config2(0); // usleep(1000000); // } // PruebaStaticBool my_trajectory_config(0); // PruebaStaticBool my_trajectory_config2(0); // PruebaStaticBool my_trajectory_config3(1); } // Prueba yaws, yawci { double yawci = ( 185.0)*M_PI/180.0; double yaws = ( 6.0)*M_PI/180.0; std::cout << "Yaw_Error: " << cvg_utils_library::getAngleError( yawci, yaws)*(180.0/M_PI) << std::endl; // std::cout << cvg_utils_library::getAngleError( NAN, NAN) << std::endl; // double yaw_test; // yaw_test = NAN; // std::cout << "yaw_test:"<< yaw_test << std::endl; // bool my_float_is_nan = false; // if ( isnan(yaw_test) ) { // my_float_is_nan = true; // std::cout << "yaw_test:"<< yaw_test << std::endl; // std::cout << "yaw_test:"<< yaw_test << std::endl; // std::cout << "yaw_test:"<< yaw_test << std::endl; // } // std::cout << "yaw_test:"<< yaw_test << std::endl; } // Prueba reference variables { // double x = 3.0; // double &rx = x; // std::cout << "x:" << x << " rx:" << rx << std::endl; // rx = 6.0; // std::cout << "x:" << x << " rx:" << rx << std::endl; // for (int i = 0; i<0; i++) { // std::cout << "i:" << i << std::endl; // } } // enum class { // myPrivateEnum my_enum = myPrivateEnum::RED; // enum class //// std::cout << "my_enum = myPrivateEnum::RED:" << my_enum << std::endl; // no compila //// my_enum = 1; // no compila //// int a = my_enum; // no compila // std::cout << "(my_enum < myPrivateEnum::GREEN):" << (my_enum < myPrivateEnum::GREEN) << std::endl; } return 1; }
36.768627
160
0.503946
[ "vector" ]
dbfd14b346c29fef50a57fd5577ff7046f922954
4,462
cc
C++
samples/framework/profile.cc
nstokes2/ozz-animation
0b9a1c90398dbc8dc11394fbc93720159db19cc9
[ "Zlib" ]
null
null
null
samples/framework/profile.cc
nstokes2/ozz-animation
0b9a1c90398dbc8dc11394fbc93720159db19cc9
[ "Zlib" ]
null
null
null
samples/framework/profile.cc
nstokes2/ozz-animation
0b9a1c90398dbc8dc11394fbc93720159db19cc9
[ "Zlib" ]
null
null
null
//============================================================================// // // // ozz-animation, 3d skeletal animation libraries and tools. // // https://code.google.com/p/ozz-animation/ // // // //----------------------------------------------------------------------------// // // // Copyright (c) 2012-2015 Guillaume Blanc // // // // This software is provided 'as-is', without any express or implied // // warranty. In no event will the authors be held liable for any damages // // arising from the use of this software. // // // // Permission is granted to anyone to use this software for any purpose, // // including commercial applications, and to alter it and redistribute it // // freely, subject to the following restrictions: // // // // 1. The origin of this software must not be misrepresented; you must not // // claim that you wrote the original software. If you use this software // // in a product, an acknowledgment in the product documentation would be // // appreciated but is not required. // // // // 2. Altered source versions must be plainly marked as such, and must not be // // misrepresented as being the original software. // // // // 3. This notice may not be removed or altered from any source // // distribution. // // // //============================================================================// #define OZZ_INCLUDE_PRIVATE_HEADER // Allows to include private headers. #include "framework/profile.h" #include "framework/internal/renderer_impl.h" #include <cfloat> #include <cmath> #include "ozz/base/memory/allocator.h" namespace ozz { namespace sample { Profiler::Profiler(Record* _record) : begin_(static_cast<float>(glfwGetTime())), record_(_record) { } Profiler::~Profiler() { if (record_) { float end = static_cast<float>(glfwGetTime()); record_->Push((end - begin_) * 1000.f); } } Record::Record(int _max_records) : max_records_(_max_records < 1 ? 1 : _max_records), records_end_(memory::default_allocator()->Allocate<float>(_max_records) + max_records_), records_begin_(records_end_), cursor_(records_end_) { } Record::~Record() { memory::default_allocator()->Deallocate(records_end_ - max_records_); } void Record::Push(float _value) { if (records_begin_ + max_records_ == records_end_) { if (cursor_ == records_begin_) { // Looping... cursor_ = records_begin_ + max_records_; } } else { // The buffer is not full yet. records_begin_--; } --cursor_; *cursor_ = _value; } Record::Statistics Record::GetStatistics() { Statistics statistics = {FLT_MAX, -FLT_MAX, 0.f, 0.f}; if (records_begin_ == records_end_) { // No record. return statistics; } // Computes statistics. float sum = 0.f; const float* current = cursor_; const float* end = records_end_; while (current < end) { if (*current < statistics.min) { statistics.min = *current; } if (*current > statistics.max) { statistics.max = *current; } sum += *current; ++current; if (current == records_end_) { // Looping... end = cursor_; current = records_begin_; } } // Stores outputs. /* int exponent; std::frexp(_f, &exponent); float upper = pow(2.f, exponent); statistics.max = func(statistics.max);*/ statistics.latest = *cursor_; statistics.mean = sum / (records_end_ - records_begin_); return statistics; } } // sample } // ozz
36.57377
80
0.477364
[ "3d" ]
e003617c3ae0b99cc0efbbe34e72861e3683410a
10,997
cxx
C++
Charts/vtkContextInteractorStyle.cxx
Armand0s/VTK
9c0c4d351d256d1dce5c8fa8f8e836ccc09e6248
[ "BSD-3-Clause" ]
1
2020-09-10T04:53:31.000Z
2020-09-10T04:53:31.000Z
Charts/vtkContextInteractorStyle.cxx
Armand0s/homemade_vtk
6bc7b595a4a7f86e8fa969d067360450fa4e0a6a
[ "BSD-3-Clause" ]
null
null
null
Charts/vtkContextInteractorStyle.cxx
Armand0s/homemade_vtk
6bc7b595a4a7f86e8fa969d067360450fa4e0a6a
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkContextInteractorStyle.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkContextInteractorStyle.h" #include "vtkContextMouseEvent.h" #include "vtkContextKeyEvent.h" #include "vtkContextScene.h" #include "vtkCallbackCommand.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include <cassert> vtkStandardNewMacro(vtkContextInteractorStyle); //-------------------------------------------------------------------------- vtkContextInteractorStyle::vtkContextInteractorStyle() { this->Scene = NULL; this->ProcessingEvents = 0; this->SceneCallbackCommand = vtkCallbackCommand::New(); this->SceneCallbackCommand->SetClientData(this); this->SceneCallbackCommand->SetCallback( vtkContextInteractorStyle::ProcessSceneEvents); this->LastSceneRepaintMTime = 0; } //-------------------------------------------------------------------------- vtkContextInteractorStyle::~vtkContextInteractorStyle() { if (this->SceneCallbackCommand) { this->SceneCallbackCommand->Delete(); this->SceneCallbackCommand = 0; } } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Scene: " << this->Scene << endl; if (this->Scene) { this->Scene->PrintSelf(os, indent.GetNextIndent()); } } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::SetScene(vtkContextScene* scene) { if (this->Scene == scene) { return; } if (this->Scene) { this->Scene->RemoveObserver(this->SceneCallbackCommand); } this->Scene = scene; if (this->Scene) { this->Scene->AddObserver(vtkCommand::ModifiedEvent, this->SceneCallbackCommand, this->Priority); } this->Modified(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::ProcessSceneEvents(vtkObject* vtkNotUsed(object), unsigned long event, void* clientdata, void* vtkNotUsed(calldata)) { vtkContextInteractorStyle* self = reinterpret_cast<vtkContextInteractorStyle *>( clientdata ); switch (event) { case vtkCommand::ModifiedEvent: self->OnSceneModified(); break; default: break; } } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnSceneModified() { if (!this->Scene || !this->Scene->GetDirty() || this->ProcessingEvents || this->Scene->GetMTime() == this->LastSceneRepaintMTime || !this->Interactor->GetInitialized()) { return; } this->BeginProcessingEvent(); this->LastSceneRepaintMTime = this->Scene->GetMTime(); this->Interactor->GetRenderWindow()->Render(); this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::BeginProcessingEvent() { ++this->ProcessingEvents; } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::EndProcessingEvent() { --this->ProcessingEvents; assert(this->ProcessingEvents >= 0); if (this->ProcessingEvents == 0) { this->OnSceneModified(); } } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseMove() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; eatEvent = this->Scene->MouseMoveEvent(x, y); } if (!eatEvent) { this->Superclass::OnMouseMove(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnLeftButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; if (this->Interactor->GetRepeatCount()) { eatEvent = this->Scene->DoubleClickEvent(vtkContextMouseEvent::LEFT_BUTTON, x, y); } else { eatEvent = this->Scene->ButtonPressEvent(vtkContextMouseEvent::LEFT_BUTTON, x, y); } } if (!eatEvent) { this->Superclass::OnLeftButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnLeftButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; eatEvent = this->Scene->ButtonReleaseEvent(vtkContextMouseEvent::LEFT_BUTTON, x, y); } if (!eatEvent) { this->Superclass::OnLeftButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMiddleButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; if (this->Interactor->GetRepeatCount()) { eatEvent = this->Scene->DoubleClickEvent(vtkContextMouseEvent::MIDDLE_BUTTON, x, y); } else { eatEvent = this->Scene->ButtonPressEvent(vtkContextMouseEvent::MIDDLE_BUTTON, x, y); } } if (!eatEvent) { this->Superclass::OnMiddleButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMiddleButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; eatEvent = this->Scene->ButtonReleaseEvent(vtkContextMouseEvent::MIDDLE_BUTTON, x, y); } if (!eatEvent) { this->Superclass::OnMiddleButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnRightButtonDown() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; if (this->Interactor->GetRepeatCount()) { eatEvent = this->Scene->DoubleClickEvent(vtkContextMouseEvent::RIGHT_BUTTON, x, y); } else { eatEvent = this->Scene->ButtonPressEvent(vtkContextMouseEvent::RIGHT_BUTTON, x, y); } } if (!eatEvent) { this->Superclass::OnRightButtonDown(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnRightButtonUp() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; eatEvent = this->Scene->ButtonReleaseEvent(vtkContextMouseEvent::RIGHT_BUTTON, x, y); } if (!eatEvent) { this->Superclass::OnRightButtonUp(); } this->EndProcessingEvent(); } //---------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseWheelForward() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; eatEvent = this->Scene->MouseWheelEvent(static_cast<int>(this->MouseWheelMotionFactor), x, y); } if (!eatEvent) { this->Superclass::OnMouseWheelForward(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnMouseWheelBackward() { this->BeginProcessingEvent(); bool eatEvent = false; if (this->Scene) { int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; eatEvent = this->Scene->MouseWheelEvent(-static_cast<int>(this->MouseWheelMotionFactor), x, y); } if (!eatEvent) { this->Superclass::OnMouseWheelBackward(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnSelection(unsigned int rect[5]) { this->BeginProcessingEvent(); if (this->Scene) { this->Scene->ProcessSelectionEvent(rect); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnChar() { this->Superclass::OnChar(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnKeyPress() { this->BeginProcessingEvent(); vtkContextKeyEvent event; vtkVector2i position(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[0]); event.SetInteractor(this->Interactor); event.SetPosition(position); bool keepEvent = false; if (this->Scene) { keepEvent = this->Scene->KeyPressEvent(event); } if (!keepEvent) { this->Superclass::OnKeyPress(); } this->EndProcessingEvent(); } //-------------------------------------------------------------------------- void vtkContextInteractorStyle::OnKeyRelease() { this->BeginProcessingEvent(); vtkContextKeyEvent event; vtkVector2i position(this->Interactor->GetEventPosition()[0], this->Interactor->GetEventPosition()[0]); event.SetInteractor(this->Interactor); event.SetPosition(position); bool keepEvent = false; if (this->Scene) { keepEvent = this->Scene->KeyReleaseEvent(event); } if (!keepEvent) { this->Superclass::OnKeyRelease(); } this->EndProcessingEvent(); }
27.4925
90
0.553787
[ "render", "object" ]
e003ec823fda0ea06d5b115c9e1caccd62488e4e
5,698
hpp
C++
tiny_htm/encoder.hpp
marty1885/tiny-htm
5173fcf1a22b9b4f5e3186ce8c941b4eb6bbcbae
[ "BSD-3-Clause" ]
7
2019-02-18T16:28:55.000Z
2021-08-28T03:20:16.000Z
tiny_htm/encoder.hpp
marty1885/tiny-htm
5173fcf1a22b9b4f5e3186ce8c941b4eb6bbcbae
[ "BSD-3-Clause" ]
null
null
null
tiny_htm/encoder.hpp
marty1885/tiny-htm
5173fcf1a22b9b4f5e3186ce8c941b4eb6bbcbae
[ "BSD-3-Clause" ]
4
2019-02-18T20:04:12.000Z
2021-08-28T03:20:17.000Z
#pragma once #include <xtensor/xarray.hpp> #include <xtensor/xtensor.hpp> #include <xtensor/xview.hpp> namespace th { //Your standard ScalarEncoder. struct ScalarEncoder { ScalarEncoder() = default; ScalarEncoder(float minval, float maxval, size_t result_sdr_length, size_t num_active_bits) : min_val(minval), max_val(maxval), active_bits(num_active_bits), sdr_length(result_sdr_length) { if(min_val > max_val) throw std::runtime_error("ScalarEncoder error: min_val > max_val"); if(result_sdr_length < num_active_bits) throw std::runtime_error("ScalarEncoder error: result_sdr_length < num_active_bits"); } xt::xarray<bool> operator() (float value) const { return encode(value); } xt::xarray<bool> encode(float value) const { float encode_space = (sdr_length - active_bits)/(max_val - min_val); int start = encode_space*(value-min_val); int end = start + active_bits; xt::xarray<bool> res = xt::zeros<bool>({sdr_length}); xt::view(res, xt::range(start, end)) = true; return res; } void setMiniumValue(float val) {min_val = val;} void setMaximumValue(float val) {max_val = val;} void setEncodeLengt(size_t val) {active_bits = val;} void setSDRLength(size_t val) {sdr_length = val;} float miniumValue() const {return min_val;} float maximumValue() const {return max_val;} size_t encodeLength() const {return active_bits;} size_t sdrLength() const {return sdr_length;} protected: float min_val = 0; float max_val = 1; size_t active_bits = 8; size_t sdr_length = 32; }; //Unlike in NuPIC. The CategoryEncoder in tinyhtm does NOT include space for //an Unknown category. And the encoding is done by passing a size_t representing //the category instread of a string. struct CategoryEncoder { CategoryEncoder(size_t num_cat, size_t encode_len) : num_category(num_cat), encode_length(encode_len) {} xt::xarray<bool> operator() (size_t category) const { return encode(category); } xt::xarray<bool> encode(size_t category) const { if(category > num_category) throw std::runtime_error("CategoryEncoder: category > num_category"); xt::xarray<bool> res = xt::zeros<bool>({num_category, encode_length}); xt::view(res, category) = true; return xt::flatten(res); } std::vector<size_t> decode(const xt::xarray<bool>& t) { std::vector<size_t> possible_category; for(size_t i=0;i<num_category;i++) { if(xt::sum(xt::view(t, xt::range(i*encode_length, (i+1)*encode_length)))[0] > 0) possible_category.push_back(i); } //if(possible_category.size() == 0) // possible_category.push_back(0); return possible_category; } void setNumCategorise(size_t num_cat) {num_category = num_cat;} void setEncodeLengt(size_t val) {encode_length = val;} size_t numCategories() const {return num_category;} size_t encodeLength() const {return encode_length;} size_t sdrLength() const {return num_category*encode_length;} protected: size_t num_category; size_t encode_length; }; int roundCoord(float x) { int v = (int)x + ((x-(int)x) > 0.5 ? 1 : -1); if(v < 0) v += 4; return v; } template <typename T> inline decltype(auto) matmul2D(const T& a, const T& b) { return xt::sum(a*b, -1); } class GridCellUnit2D { public: GridCellUnit2D(xt::xtensor<size_t, 1> module_shape={4,4}, float scale_min=6, float scale_max=25, size_t seed=42) : border_len_(module_shape) { std::mt19937 rng(seed); auto random = [&](float min, float max){std::uniform_real_distribution<float> dist(min, max); return dist(rng);}; float theta = random(0,2*xt::numeric_constants<float>::PI); scale_ = random(scale_min, scale_max); bias_ = {random(0, border_len_[0]), random(0, border_len_[1])}; transform_matrix_ = {{cosf(theta), -sinf(theta)}, {sinf(theta), cosf(theta)}}; } xt::xarray<bool> encode(const xt::xtensor<float, 2>& pos) const { xt::xarray<bool> res = xt::zeros<bool>({border_len_[0], border_len_[1]}); //Wrap the position auto grid_cord = xt::fmod(matmul2D(transform_matrix_, pos)/scale_+bias_, border_len_); assert(grid_cord.size() == 2); //Set the nearest cell to active xt::view(res, (int)grid_cord[1], (int)grid_cord[0]) = 1; //Set the 2nd nearest cell to active int cx = roundCoord(grid_cord[1])%4; int cy = roundCoord(grid_cord[0])%4; xt::view(res, cx, cy) = 1; res.reshape({res.size()}); return res; } size_t encodeSize() const { return border_len_[0] * border_len_[1]; } xt::xtensor<float, 2> transform_matrix_; xt::xtensor<size_t, 1> border_len_; xt::xtensor<float, 1> bias_; float scale_; }; class GridCellEncoder2D { public: GridCellEncoder2D(int num_modules_ = 32, xt::xtensor<size_t, 1> module_shape={4,4}, float scale_min=6, float scale_max=25, size_t seed=42) { std::mt19937 rng(seed); for(int i=0;i<num_modules_;i++) units.push_back(GridCellUnit2D(module_shape, scale_min, scale_max, rng())); } xt::xarray<bool> encode(const xt::xtensor<float, 2>& pos) const { size_t num_cells = 0; for(const auto& u : units) num_cells += u.encodeSize(); xt::xarray<bool> res = xt::zeros<bool>({num_cells}); size_t start = 0; for(const auto& u : units) { size_t l = u.encodeSize(); xt::view(res, xt::range((int)start, l)) = u.encode(pos); start += l; } return res; } std::vector<GridCellUnit2D> units; }; //Handy encode functions inline xt::xarray<bool> encodeScalar(float value, float minval, float maxval, size_t result_sdr_length, size_t num_active_bits) { ScalarEncoder e(minval, maxval, result_sdr_length, num_active_bits); return e.encode(value); } inline xt::xarray<bool> encodeCategory(size_t category, size_t num_cat, size_t encode_len) { CategoryEncoder e(num_cat, encode_len); return e.encode(category); } }
27.931373
139
0.709372
[ "vector" ]
e0064c27fa47b3748db5d5fb511ba1de06cf2dfd
24,086
cpp
C++
tests/tests.cpp
asd19951995/kvdk
167206a0bb2702d96b78889e6f7a9e01ce6f835c
[ "BSD-3-Clause" ]
null
null
null
tests/tests.cpp
asd19951995/kvdk
167206a0bb2702d96b78889e6f7a9e01ce6f835c
[ "BSD-3-Clause" ]
null
null
null
tests/tests.cpp
asd19951995/kvdk
167206a0bb2702d96b78889e6f7a9e01ce6f835c
[ "BSD-3-Clause" ]
null
null
null
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2021 Intel Corporation */ #include <future> #include <string> #include <thread> #include <vector> #include "../engine/pmem_allocator/pmem_allocator.hpp" #include "kvdk/engine.hpp" #include "kvdk/namespace.hpp" #include "test_util.h" #include "gtest/gtest.h" using namespace KVDK_NAMESPACE; static const uint64_t str_pool_length = 1024000; static void LaunchNThreads(int n_thread, std::function<void(int tid)> func, uint32_t id_start = 0) { std::vector<std::thread> ts; for (int i = id_start; i < id_start + n_thread; i++) { ts.emplace_back(std::thread(func, i)); } for (auto &t : ts) t.join(); } class EngineBasicTest : public testing::Test { protected: Engine *engine = nullptr; Configs configs; std::string db_path; std::string str_pool; virtual void SetUp() override { str_pool.resize(str_pool_length); random_str(&str_pool[0], str_pool_length); configs.pmem_file_size = (16ULL << 30); configs.populate_pmem_space = false; configs.hash_bucket_num = (1 << 10); configs.hash_bucket_size = 64; configs.pmem_segment_blocks = 8 * 1024; // For faster test, no interval so it would not block engine closing configs.background_work_interval = 0; db_path = "/mnt/pmem0/data"; char cmd[1024]; sprintf(cmd, "rm -rf %s\n", db_path.c_str()); int res __attribute__((unused)) = system(cmd); } virtual void TearDown() { char cmd[1024]; sprintf(cmd, "rm -rf %s\n", db_path.c_str()); int res __attribute__((unused)) = system(cmd); // delete db_path } void AssignData(std::string &data, int len) { data.assign(str_pool.data() + (rand() % (str_pool_length - len)), len); } }; TEST_F(EngineBasicTest, TestThreadManager) { int max_write_threads = 1; configs.max_write_threads = max_write_threads; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); std::string key("k"); std::string val("value"); ASSERT_EQ(engine->Set(key, val), Status::Ok); // Reach max write threads auto s = std::async(&Engine::Set, engine, key, val); ASSERT_EQ(s.get(), Status::TooManyWriteThreads); // Manually release write thread engine->ReleaseWriteThread(); s = std::async(&Engine::Set, engine, key, val); ASSERT_EQ(s.get(), Status::Ok); // Release write thread on thread exits s = std::async(&Engine::Set, engine, key, val); ASSERT_EQ(s.get(), Status::Ok); delete engine; } TEST_F(EngineBasicTest, TestBasicStringOperations) { int num_threads = 16; configs.max_write_threads = num_threads; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); // Test empty key std::string key{""}, val{"val"}, got_val; ASSERT_EQ(engine->Set(key, val), Status::Ok); ASSERT_EQ(engine->Get(key, &got_val), Status::Ok); ASSERT_EQ(val, got_val); ASSERT_EQ(engine->Delete(key), Status::Ok); ASSERT_EQ(engine->Get(key, &got_val), Status::NotFound); engine->ReleaseWriteThread(); auto SetGetDelete = [&](uint32_t id) { std::string val1, val2, got_val1, got_val2; int cnt = 100; while (cnt--) { std::string key1(std::string(id + 1, 'a') + std::to_string(cnt)); std::string key2(std::string(id + 1, 'b') + std::to_string(cnt)); AssignData(val1, fast_random_64() % 1024); AssignData(val2, fast_random_64() % 1024); ASSERT_EQ(engine->Set(key1, val1), Status::Ok); ASSERT_EQ(engine->Set(key2, val2), Status::Ok); // Get ASSERT_EQ(engine->Get(key1, &got_val1), Status::Ok); ASSERT_EQ(val1, got_val1); ASSERT_EQ(engine->Get(key2, &got_val2), Status::Ok); ASSERT_EQ(val2, got_val2); // Delete ASSERT_EQ(engine->Delete(key1), Status::Ok); ASSERT_EQ(engine->Get(key1, &got_val1), Status::NotFound); // Update AssignData(val1, fast_random_64() % 1024); ASSERT_EQ(engine->Set(key1, val1), Status::Ok); ASSERT_EQ(engine->Get(key1, &got_val1), Status::Ok); ASSERT_EQ(got_val1, val1); } }; LaunchNThreads(num_threads, SetGetDelete); delete engine; } TEST_F(EngineBasicTest, TestBatchWrite) { int num_threads = 16; configs.max_write_threads = num_threads; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); int batch_num = 10; int count = 500; auto BatchSetDelete = [&](uint32_t id) { std::string key_prefix(std::string(id, 'a')); std::string got_val; WriteBatch batch; int cnt = count; while (cnt--) { for (size_t i = 0; i < batch_num; i++) { auto key = key_prefix + std::to_string(i) + std::to_string(cnt); auto val = std::to_string(i * id); batch.Put(key, val); } ASSERT_EQ(engine->BatchWrite(batch), Status::Ok); batch.Clear(); for (size_t i = 0; i < batch_num; i++) { if ((i * cnt) % 2 == 1) { auto key = key_prefix + std::to_string(i) + std::to_string(cnt); auto val = std::to_string(i * id); ASSERT_EQ(engine->Get(key, &got_val), Status::Ok); ASSERT_EQ(got_val, val); batch.Delete(key); } } engine->BatchWrite(batch); batch.Clear(); } }; LaunchNThreads(num_threads, BatchSetDelete); delete engine; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); for (uint32_t id = 0; id < num_threads; id++) { std::string key_prefix(id, 'a'); std::string got_val; int cnt = count; while (cnt--) { for (size_t i = 0; i < batch_num; i++) { auto key = key_prefix + std::to_string(i) + std::to_string(cnt); if ((i * cnt) % 2 == 1) { ASSERT_EQ(engine->Get(key, &got_val), Status::NotFound); } else { auto val = std::to_string(i * id); ASSERT_EQ(engine->Get(key, &got_val), Status::Ok); ASSERT_EQ(got_val, val); } } } } delete engine; } TEST_F(EngineBasicTest, TestFreeList) { // TODO: Add more cases configs.pmem_segment_blocks = 4 * kMinPaddingBlockSize; configs.max_write_threads = 1; configs.pmem_block_size = 64; configs.pmem_file_size = configs.pmem_segment_blocks * configs.pmem_block_size; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); std::string key1("a1"); std::string key2("a2"); std::string key3("a3"); std::string key4("a4"); std::string small_value(64 * (kMinPaddingBlockSize - 1) + 1, 'a'); std::string large_value(64 * (kMinPaddingBlockSize * 2 - 1) + 1, 'a'); // We have 4 kMinimalPaddingBlockSize size chunk of blocks, this will take // up 2 of them ASSERT_EQ(engine->Set(key1, large_value), Status::Ok); // update large value, new value will be stored in 3th chunk ASSERT_EQ(engine->Set(key1, small_value), Status::Ok); // key2 will be stored in 4th chunk ASSERT_EQ(engine->Set(key2, small_value), Status::Ok); // new key 1 and new key 2 will be stored in updated 1st and 2nd chunks ASSERT_EQ(engine->Set(key1, small_value), Status::Ok); ASSERT_EQ(engine->Set(key2, small_value), Status::Ok); delete engine; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); // large key3 will be stored in merged 3th and 4th chunks ASSERT_EQ(engine->Set(key3, large_value), Status::Ok); // No more space ASSERT_EQ(engine->Set(key4, small_value), Status::PmemOverflow); } TEST_F(EngineBasicTest, TestLocalSortedCollection) { int num_threads = 16; configs.max_write_threads = num_threads; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); std::vector<int> n_local_entries(num_threads, 0); auto SSetSGetSDelete = [&](uint32_t id) { std::string thread_local_skiplist("t_skiplist" + std::to_string(id)); std::string key1, key2, val1, val2; std::string got_val1, got_val2; AssignData(val1, 10); // Test Empty Key { std::string k0{""}; ASSERT_EQ(engine->SSet(thread_local_skiplist, k0, val1), Status::Ok); ++n_local_entries[id]; ASSERT_EQ(engine->SGet(thread_local_skiplist, k0, &got_val1), Status::Ok); ASSERT_EQ(val1, got_val1); ASSERT_EQ(engine->SDelete(thread_local_skiplist, k0), Status::Ok); --n_local_entries[id]; ASSERT_EQ(engine->SGet(thread_local_skiplist, k0, &got_val1), Status::NotFound); } key1 = std::to_string(id); key2 = std::to_string(id); int cnt = 100; while (cnt--) { key1.append("k1"); key2.append("k2"); // insert AssignData(val1, fast_random_64() % 1024); AssignData(val2, fast_random_64() % 1024); ASSERT_EQ(engine->SSet(thread_local_skiplist, key1, val1), Status::Ok); ++n_local_entries[id]; ASSERT_EQ(engine->SSet(thread_local_skiplist, key2, val2), Status::Ok); ++n_local_entries[id]; ASSERT_EQ(engine->SGet(thread_local_skiplist, key1, &got_val1), Status::Ok); ASSERT_EQ(engine->SGet(thread_local_skiplist, key2, &got_val2), Status::Ok); ASSERT_EQ(val1, got_val1); ASSERT_EQ(val2, got_val2); // update AssignData(val1, fast_random_64() % 1024); ASSERT_EQ(engine->SSet(thread_local_skiplist, key1, val1), Status::Ok); ASSERT_EQ(engine->SGet(thread_local_skiplist, key1, &got_val1), Status::Ok); ASSERT_EQ(got_val1, val1); AssignData(val2, fast_random_64() % 1024); ASSERT_EQ(engine->SSet(thread_local_skiplist, key2, val2), Status::Ok); ASSERT_EQ(engine->SGet(thread_local_skiplist, key2, &got_val2), Status::Ok); ASSERT_EQ(got_val2, val2); // delete ASSERT_EQ(engine->SDelete(thread_local_skiplist, key1), Status::Ok); --n_local_entries[id]; ASSERT_EQ(engine->SGet(thread_local_skiplist, key1, &got_val1), Status::NotFound); } }; auto IteratingThrough = [&](uint32_t id) { std::string thread_local_skiplist("t_skiplist" + std::to_string(id)); std::vector<int> n_entries(num_threads, 0); auto t_iter = engine->NewSortedIterator(thread_local_skiplist); ASSERT_TRUE(t_iter != nullptr); t_iter->SeekToFirst(); if (t_iter->Valid()) { ++n_entries[id]; std::string prev = t_iter->Key(); t_iter->Next(); while (t_iter->Valid()) { ++n_entries[id]; std::string k = t_iter->Key(); t_iter->Next(); ASSERT_EQ(true, k.compare(prev) > 0); prev = k; } } ASSERT_EQ(n_local_entries[id], n_entries[id]); n_entries[id] = 0; }; LaunchNThreads(num_threads, SSetSGetSDelete); LaunchNThreads(num_threads, IteratingThrough); delete engine; } TEST_F(EngineBasicTest, TestGlobalSortedCollection) { const std::string global_skiplist = "skiplist"; int num_threads = 16; configs.max_write_threads = num_threads; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); std::atomic<int> n_global_entries{0}; // Test empty key std::string key{""}, val{"val"}, got_val; ASSERT_EQ(engine->SSet(global_skiplist, key, val), Status::Ok); ++n_global_entries; ASSERT_EQ(engine->SGet(global_skiplist, key, &got_val), Status::Ok); ASSERT_EQ(val, got_val); ASSERT_EQ(engine->SDelete(global_skiplist, key), Status::Ok); --n_global_entries; ASSERT_EQ(engine->SGet(global_skiplist, key, &got_val), Status::NotFound); engine->ReleaseWriteThread(); auto SSetSGetSDelete = [&](uint32_t id) { std::string k1, k2, v1, v2; std::string got_v1, got_v2; AssignData(v1, 10); k1 = std::to_string(id); k2 = std::to_string(id); int cnt = 100; while (cnt--) { int v1_len = rand() % 1024; int v2_len = rand() % 1024; k1.append("k1"); k2.append("k2"); // insert AssignData(v1, v1_len); AssignData(v2, v2_len); ASSERT_EQ(engine->SSet(global_skiplist, k1, v1), Status::Ok); ++n_global_entries; ASSERT_EQ(engine->SSet(global_skiplist, k2, v2), Status::Ok); ++n_global_entries; ASSERT_EQ(engine->SGet(global_skiplist, k1, &got_v1), Status::Ok); ASSERT_EQ(engine->SGet(global_skiplist, k2, &got_v2), Status::Ok); ASSERT_EQ(v1, got_v1); ASSERT_EQ(v2, got_v2); // update AssignData(v1, v1_len); ASSERT_EQ(engine->SSet(global_skiplist, k1, v1), Status::Ok); ASSERT_EQ(engine->SGet(global_skiplist, k1, &got_v1), Status::Ok); ASSERT_EQ(got_v1, v1); AssignData(v2, v2_len); ASSERT_EQ(engine->SSet(global_skiplist, k2, v2), Status::Ok); ASSERT_EQ(engine->SGet(global_skiplist, k2, &got_v2), Status::Ok); ASSERT_EQ(got_v2, v2); // delete ASSERT_EQ(engine->SDelete(global_skiplist, k1), Status::Ok); --n_global_entries; ASSERT_EQ(engine->SGet(global_skiplist, k1, &got_v1), Status::NotFound); } }; auto IteratingThrough = [&](uint32_t id) { std::vector<int> n_entries(num_threads, 0); auto iter = engine->NewSortedIterator(global_skiplist); ASSERT_TRUE(iter != nullptr); iter->SeekToFirst(); if (iter->Valid()) { ++n_entries[id]; std::string prev = iter->Key(); iter->Next(); while (iter->Valid()) { ++n_entries[id]; std::string k = iter->Key(); iter->Next(); ASSERT_EQ(true, k.compare(prev) > 0); prev = k; } } ASSERT_EQ(n_global_entries, n_entries[id]); n_entries[id] = 0; }; auto SeekToDeleted = [&](uint32_t id) { auto t_iter2 = engine->NewSortedIterator(global_skiplist); ASSERT_TRUE(t_iter2 != nullptr); // First deleted key t_iter2->Seek(std::to_string(id) + "k1"); ASSERT_TRUE(t_iter2->Valid()); // First valid key t_iter2->Seek(std::to_string(id) + "k2"); ASSERT_TRUE(t_iter2->Valid()); ASSERT_EQ(t_iter2->Key(), std::to_string(id) + "k2"); }; LaunchNThreads(num_threads, SSetSGetSDelete); LaunchNThreads(num_threads, IteratingThrough); LaunchNThreads(num_threads, SeekToDeleted); delete engine; } TEST_F(EngineBasicTest, TestSeek) { std::string val; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); // Test Seek std::string collection = "col1"; uint64_t z = 0; auto zero_filled_str = uint64_to_string(z); ASSERT_EQ(engine->SSet(collection, zero_filled_str, zero_filled_str), Status::Ok); ASSERT_EQ(engine->SGet(collection, zero_filled_str, &val), Status::Ok); auto iter = engine->NewSortedIterator(collection); ASSERT_NE(iter, nullptr); iter->Seek(zero_filled_str); ASSERT_TRUE(iter->Valid()); // Test SeekToFirst collection.assign("col2"); ASSERT_EQ(engine->SSet(collection, "foo", "bar"), Status::Ok); ASSERT_EQ(engine->SGet(collection, "foo", &val), Status::Ok); ASSERT_EQ(engine->SDelete(collection, "foo"), Status::Ok); ASSERT_EQ(engine->SGet(collection, "foo", &val), Status::NotFound); ASSERT_EQ(engine->SSet(collection, "foo2", "bar2"), Status::Ok); iter = engine->NewSortedIterator(collection); ASSERT_NE(iter, nullptr); iter->SeekToFirst(); ASSERT_TRUE(iter->Valid()); ASSERT_EQ(iter->Value(), "bar2"); } TEST_F(EngineBasicTest, TestStringRestore) { int num_threads = 16; configs.max_write_threads = num_threads; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); // insert and delete some keys, then re-insert some deleted keys int count = 1000; auto SetupEngine = [&](uint32_t id) { std::string key_prefix(id, 'a'); std::string got_val; for (int i = 1; i <= count; i++) { std::string key(key_prefix + std::to_string(i)); std::string val(std::to_string(i)); std::string update_val(std::to_string(i * 2)); ASSERT_EQ(engine->Set(key, val), Status::Ok); if ((i * id) % 2 == 1) { ASSERT_EQ(engine->Delete(key), Status::Ok); if ((i * id) % 3 == 0) { // Update after delete ASSERT_EQ(engine->Set(key, update_val), Status::Ok); ASSERT_EQ(engine->Get(key, &got_val), Status::Ok); ASSERT_EQ(got_val, update_val); } else { ASSERT_EQ(engine->Get(key, &got_val), Status::NotFound); } } else { ASSERT_EQ(engine->Get(key, &got_val), Status::Ok); ASSERT_EQ(got_val, val); } } }; LaunchNThreads(num_threads, SetupEngine); delete engine; // reopen and restore engine and try gets ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); for (uint32_t id = 0; id < num_threads; id++) { std::string key_prefix(id, 'a'); std::string got_val; for (int i = 1; i <= count; i++) { std::string key(key_prefix + std::to_string(i)); std::string val(std::to_string(i)); std::string updated_val(std::to_string(i * 2)); Status s = engine->Get(key, &got_val); if ((i * id) % 3 == 0 && (id * i) % 2 == 1) { // deleted then updated ones ASSERT_EQ(s, Status::Ok); ASSERT_EQ(got_val, updated_val); } else if ((i * id) % 2 == 0) { // not deleted ones ASSERT_EQ(s, Status::Ok); ASSERT_EQ(got_val, val); } else { // deleted ones ASSERT_EQ(s, Status::NotFound); } } } delete engine; } TEST_F(EngineBasicTest, TestSortedRestore) { int num_threads = 16; configs.max_write_threads = num_threads; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); // insert and delete some keys, then re-insert some deleted keys int count = 100; std::string overall_skiplist = "skiplist"; std::string thread_skiplist = "t_skiplist"; auto SetupEngine = [&](uint32_t id) { std::string key_prefix(id, 'a'); std::string got_val; std::string t_skiplist(thread_skiplist + std::to_string(id)); for (int i = 1; i <= count; i++) { auto key = key_prefix + std::to_string(i); auto overall_val = std::to_string(i); auto t_val = std::to_string(i * 2); ASSERT_EQ(engine->SSet(overall_skiplist, key, overall_val), Status::Ok); ASSERT_EQ(engine->SSet(t_skiplist, key, t_val), Status::Ok); ASSERT_EQ(engine->SGet(overall_skiplist, key, &got_val), Status::Ok); ASSERT_EQ(got_val, overall_val); ASSERT_EQ(engine->SGet(t_skiplist, key, &got_val), Status::Ok); ASSERT_EQ(got_val, t_val); if (i % 2 == 1) { ASSERT_EQ(engine->SDelete(overall_skiplist, key), Status::Ok); ASSERT_EQ(engine->SDelete(t_skiplist, key), Status::Ok); ASSERT_EQ(engine->SGet(overall_skiplist, key, &got_val), Status::NotFound); ASSERT_EQ(engine->SGet(t_skiplist, key, &got_val), Status::NotFound); } } }; LaunchNThreads(num_threads, SetupEngine); delete engine; // reopen and restore engine and try gets ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); for (uint32_t id = 0; id < num_threads; id++) { std::string t_skiplist(thread_skiplist + std::to_string(id)); std::string key_prefix(id, 'a'); std::string got_val; for (int i = 1; i <= count; i++) { std::string key(key_prefix + std::to_string(i)); std::string overall_val(std::to_string(i)); std::string t_val(std::to_string(i * 2)); Status s = engine->SGet(overall_skiplist, key, &got_val); if (i % 2 == 1) { ASSERT_EQ(s, Status::NotFound); } else { ASSERT_EQ(s, Status::Ok); ASSERT_EQ(got_val, overall_val); } s = engine->SGet(t_skiplist, key, &got_val); if (i % 2 == 1) { ASSERT_EQ(s, Status::NotFound); } else { ASSERT_EQ(s, Status::Ok); ASSERT_EQ(got_val, t_val); } } auto iter = engine->NewSortedIterator(t_skiplist); ASSERT_TRUE(iter != nullptr); iter->SeekToFirst(); std::string prev = ""; int cnt = 0; while (iter->Valid()) { cnt++; std::string k = iter->Key(); iter->Next(); ASSERT_TRUE(k.compare(prev) > 0); prev = k; } ASSERT_EQ(cnt, count / 2); } auto iter = engine->NewSortedIterator(overall_skiplist); ASSERT_TRUE(iter != nullptr); iter->SeekToFirst(); std::string prev = ""; int cnt = 0; while (iter->Valid()) { cnt++; std::string k = iter->Key(); iter->Next(); ASSERT_TRUE(k.compare(prev) > 0); prev = k; } ASSERT_EQ(cnt, (count / 2) * num_threads); delete engine; } TEST_F(EngineBasicTest, TestStringHotspot) { int n_thread_reading = 16; int n_thread_writing = 16; configs.max_write_threads = n_thread_writing; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); int count = 100000; std::string key{"SuperHotspot"}; std::string val1(1024, 'a'); std::string val2(1023, 'b'); ASSERT_EQ(engine->Set(key, val1), Status::Ok); engine->ReleaseWriteThread(); auto EvenWriteOddRead = [&](uint32_t id) { for (size_t i = 0; i < count; i++) { if (id % 2 == 0) { // Even Write if (id % 4 == 0) { ASSERT_EQ(engine->Set(key, val1), Status::Ok); } else { ASSERT_EQ(engine->Set(key, val2), Status::Ok); } } else { // Odd Read std::string got_val; ASSERT_EQ(engine->Get(key, &got_val), Status::Ok); bool match = false; match = match || (got_val == val1); match = match || (got_val == val2); if (!match) { std::string msg; msg.append("Wrong value!\n"); msg.append("The value should be 1024 of a's or 1023 of b's.\n"); msg.append("Actual result is:\n"); msg.append(got_val); msg.append("\n"); msg.append("Length: "); msg.append(std::to_string(got_val.size())); msg.append("\n"); GlobalLogger.Error(msg.data()); } ASSERT_TRUE(match); } } }; LaunchNThreads(n_thread_reading + n_thread_writing, EvenWriteOddRead); delete engine; } TEST_F(EngineBasicTest, TestSortedHotspot) { int n_thread_reading = 16; int n_thread_writing = 16; configs.max_write_threads = n_thread_writing; ASSERT_EQ(Engine::Open(db_path.c_str(), &engine, configs, stdout), Status::Ok); int count = 100000; std::string collection{"collection"}; std::vector<std::string> keys{"SuperHotSpot0", "SuperHotSpot2", "SuperHotSpot1"}; std::string val1(1024, 'a'); std::string val2(1024, 'b'); for (const std::string &key : keys) { ASSERT_EQ(engine->SSet(collection, key, val1), Status::Ok); engine->ReleaseWriteThread(); auto EvenWriteOddRead = [&](uint32_t id) { for (size_t i = 0; i < count; i++) { if (id % 2 == 0) { // Even Write if (id % 4 == 0) { ASSERT_EQ(engine->SSet(collection, key, val1), Status::Ok); } else { ASSERT_EQ(engine->SSet(collection, key, val2), Status::Ok); } } else { // Odd Read std::string got_val; ASSERT_EQ(engine->SGet(collection, key, &got_val), Status::Ok); bool match = false; match = match || (got_val == val1); match = match || (got_val == val2); if (!match) { std::string msg; msg.append("Wrong value!\n"); msg.append("The value should be 1024 of a's or 1023 of b's.\n"); msg.append("Actual result is:\n"); msg.append(got_val); msg.append("\n"); msg.append("Length: "); msg.append(std::to_string(got_val.size())); msg.append("\n"); GlobalLogger.Error(msg.data()); } ASSERT_TRUE(match); } } }; LaunchNThreads(n_thread_reading + n_thread_writing, EvenWriteOddRead); } delete engine; } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
32.504723
80
0.618534
[ "vector" ]
e0071534ed439734eddd1dc64bc1fb9a04fa7ee0
827
cc
C++
elang/vm/class.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2018-01-27T22:40:53.000Z
2018-01-27T22:40:53.000Z
elang/vm/class.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2016-01-29T00:54:49.000Z
2016-01-29T00:54:49.000Z
elang/vm/class.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
null
null
null
// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/vm/class.h" namespace elang { namespace vm { ////////////////////////////////////////////////////////////////////// // // Class // Class::Class(Zone* zone, Namespace* outer, AtomicString* simple_name, const std::vector<Class*>& base_classes) : Namespace(zone, outer, simple_name), base_classes_(zone, base_classes) { // TODO(eval1749) NYI default base class |Object|. // TODO(eval1749) NYI validate |base_classes|, |base_classes[0]| must be // a class rather than an interface. } // NamespaceMember Namespace* Class::ToNamespace() { return nullptr; } } // namespace vm } // namespace elang
26.677419
78
0.620314
[ "object", "vector" ]
e00a5f16270d46e4b08df6d449738ebed4eee1f1
3,497
cpp
C++
List/main.cpp
brown9804/Abstract_List_Templates
38121c48e282fb5ebc6acb4d9cf28b7d67ee5fe5
[ "Apache-2.0" ]
null
null
null
List/main.cpp
brown9804/Abstract_List_Templates
38121c48e282fb5ebc6acb4d9cf28b7d67ee5fe5
[ "Apache-2.0" ]
null
null
null
List/main.cpp
brown9804/Abstract_List_Templates
38121c48e282fb5ebc6acb4d9cf28b7d67ee5fe5
[ "Apache-2.0" ]
null
null
null
#include "Node.cpp" #include "LinkedList.cpp" #include <vector> #define DataType int #include<iostream> #include <stdint.h> using namespace std; int Menu() { cout<<"\n************** Menu **************\n\n"; int Decision; cout<<"\n\n1) Introduzca nodo al principio"; cout<<"\n\n2) Introduzca nodo al final"; cout<<"\n\n3) Introduzca nodo en una posicion definida a su escogencia"; cout<<"\n\n4) Elimine nodo al principio"; cout<<"\n\n5) Elimine nodo al final"; cout<<"\n\n6) Elimine nodo que se encuentra en una posicion definida"; cout<<"\n\n7) Darle vuelta a los nodos em lista"; cout<<"\n\n8) Darle vuelta al Data"; cout<<"\n\n9) Darle vuelta a la lista recursivamente"; cout<<"\n\n10) Ordena la lista"; cout<<"\n\n11) Ver lista"; cout<<"\n\n12) Tamaño de la lista"; cout<<"\n\n0) Salir"; cout<<"\n\n\nDigite una opcion : "; cin>>Decision; return Decision; } int main(){ LinkedList<int> SLLOne; cout<<"\n--- Lista simple enlazada ---\n\n"; cout<<endl<<endl; while(1) { switch(Menu()) { case 1: { DataType Data; cout<<"\n\nDigite una opcion: "; cin>>Data; SLLOne.Ingre_inicio(Data); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 2: { DataType Data; cout<<"\n\nDigite un valor: "; cin>>Data; SLLOne.Ingre_final(Data); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 3: { int Pos=0; DataType Data; cout<<"\n\nDigite un valor : "; cin>>Data; cout<<"\n\nDigite un posicion: "; cin>>Pos; SLLOne.Ingreso_en_posicion(Data,Pos); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 4: { SLLOne.Eliminar_primero(); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 5: { SLLOne.Eliminar_ultimo(); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 6: { int Pos=0; cout<<"\n\nDigite una posicion: "; cin>>Pos; SLLOne.Eliminar_posicion(Pos); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 7: { SLLOne.Vuelta_lista(); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 8: { SLLOne.Vuelta_datos(); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 9: { SLLOne.Vuelta_lista(SLLOne.GetHead()); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 10: { SLLOne.Ordenar(); cout<<"\n\nProceso realizado exitosamente...\n\n"; break; } case 11: { SLLOne.Ver_lista(); break; } case 12: { cout<<"\n\nTamaño de la lista : "<<SLLOne.Obt_tamano()<<endl<<endl; break; } case 0: { cout<<endl<<endl<<"Cerrando el programa\n\n"; exit(0); break; } default: { cout<<"\nOpcion invalida\n"; } } cout<<endl; } }
24.117241
84
0.484415
[ "vector" ]
e00c4168c8c5d6f0d1abc0637bf4fe91f1a6efb7
8,756
cpp
C++
workload_readwrite.cpp
spcl/CoRM
2bcae859eafad28ba51a92ec73e57239febef147
[ "BSD-3-Clause" ]
7
2021-06-19T08:32:49.000Z
2022-03-31T15:46:48.000Z
workload_readwrite.cpp
spcl/CoRM
2bcae859eafad28ba51a92ec73e57239febef147
[ "BSD-3-Clause" ]
null
null
null
workload_readwrite.cpp
spcl/CoRM
2bcae859eafad28ba51a92ec73e57239febef147
[ "BSD-3-Clause" ]
2
2021-06-19T08:32:50.000Z
2022-01-04T12:11:32.000Z
/** * CoRM: Compactable Remote Memory over RDMA * * Various read/write workload for CoRM * * Copyright (c) 2020-2021 ETH-Zurich. All rights reserved. * * Author(s): Konstantin Taranov <konstantin.taranov@inf.ethz.ch> * */ #include <iostream> // std::cout #include <thread> #include <chrono> #include <vector> #include <cstdlib> #include <string> #include <sstream> #include <cassert> #include <stdlib.h> #include <csignal> #include <fstream> #include <algorithm> #include <atomic> FILE *log_fp; #include "worker/client_api.hpp" #include "rdma/connectRDMA.hpp" #include "utilities/zipf.hpp" #include "utilities/ycsb.hpp" #include "utilities/cxxopts.hpp" using ReadFuncPtr = int (RemoteMemoryClient::*)( LocalObjectHandler* obj, char* buffer, uint32_t length ); std::atomic<int> order(0); uint64_t num; cxxopts::ParseResult parse(int argc, char* argv[]) { cxxopts::Options options(argv[0], "Read write workload for CoRM"); options .positional_help("[optional args]") .show_positional_help(); try { options.add_options() ("server", "Another address", cxxopts::value<std::string>(), "IP") ("i,input", "input file", cxxopts::value<std::string>()->default_value("test.bin"), "FILE") ("t,threads", "the number of threads", cxxopts::value<uint32_t>()->default_value(std::to_string(1)), "N") ("target", "expected rate ops/sec", cxxopts::value<uint64_t>()->default_value(std::to_string(1000)), "N") ("p,prob", "Probability of read", cxxopts::value<float>()->default_value(std::to_string(0.5f)), "N") ("seed", "seed", cxxopts::value<int>()->default_value(std::to_string(3)), "N") ("zipf", "use zipf distribution as in YSCB") ("rdmaread", "Use one-sided reads") ("n,num", "Number of requests to run", cxxopts::value<uint64_t>()->default_value("123"), "N") ("help", "Print help") ; auto result = options.parse(argc, argv); if (result.count("help")) { std::cout << options.help({""}) << std::endl; exit(0); } if (!result.count("server")) { throw cxxopts::OptionException("input must be specified"); } return result; } catch (const cxxopts::OptionException& e) { std::cout << "error parsing options: " << e.what() << std::endl; std::cout << options.help({""}) << std::endl; exit(1); } } void workload_worker(int threadid, VerbsEP *ep, ReadFuncPtr readfunc, LocalObjectHandler *objects_orig, uint32_t NN, bool is_zipf, int seed, float read_prob, uint64_t target){ RemoteMemoryClient* api = new RemoteMemoryClient(0,ep); Trace *trace = nullptr; if (is_zipf) { trace = new YCSB(seed,read_prob,NN,0.99); } else { trace = new Uniform(seed,read_prob,NN); } LocalObjectHandler *objects = (LocalObjectHandler*)malloc(NN*sizeof(LocalObjectHandler)); memcpy((char*)objects,(char*)objects_orig,NN*sizeof(LocalObjectHandler)); uint32_t size = objects[0].requested_size; char* buffer = (char*)malloc(size); std::chrono::seconds sec(1); uint64_t nanodelay = std::chrono::nanoseconds(sec).count() / target ; // per request auto starttime = std::chrono::high_resolution_clock::now(); uint32_t interval = 2560; std::vector<uint64_t> request_bw; request_bw.reserve(1024); #ifdef LATENCY std::vector<uint64_t> request_latency; request_latency.reserve(num); #endif uint32_t conflicts = 0; auto bwt1 = std::chrono::high_resolution_clock::now(); uint32_t count = 0; for(uint64_t i=0; i<num; i++) { auto req = trace->get_next(); LocalObjectHandler* obj = &objects[req.first]; assert(obj!=nullptr && "object cannot be null"); #ifdef LATENCY auto t1 = std::chrono::high_resolution_clock::now(); #endif // the following piece of code were used to incur Indirect pointers // uint64_t direct_addr = obj->addr.comp.addr; // uint64_t base_addr = GetVirtBaseAddr(obj->addr.comp.addr); // if(direct_addr == base_addr){ // base_addr += 32; // } // obj->addr.comp.addr = base_addr; if(req.second == 'r'){ int ret = (api->*readfunc)(obj, buffer, size); if(ret<0){ conflicts++; } // api->Read(obj, buffer, size); } else { api->Write(obj, buffer, size, false); } #ifdef LATENCY auto t2 = std::chrono::high_resolution_clock::now(); request_latency.push_back( std::chrono::duration_cast< std::chrono::nanoseconds >( t2 - t1 ).count() ); #endif count++; if(count > interval){ auto bwt2 = std::chrono::high_resolution_clock::now(); request_bw.push_back(std::chrono::duration_cast<std::chrono::microseconds>(bwt2 - bwt1).count()); bwt1 = bwt2; count=0; } auto const sleep_end_time = starttime + std::chrono::nanoseconds(nanodelay*i); while (std::chrono::high_resolution_clock::now() < sleep_end_time){ // nothing } } auto endtime = std::chrono::high_resolution_clock::now(); while(order.load() != threadid ){ } printf("Data thread #%u: \n",threadid); printf("throughput(Kreq/sec): "); for(auto &x : request_bw){ printf("%.2f ",(interval*1000.0)/x); } #ifdef LATENCY printf("latency(us): "); for(auto &x : request_latency){ printf("%.2f ",x/1000.0); } #endif printf("\nFinished workload in %lu ms with %u conflicts\n", std::chrono::duration_cast< std::chrono::milliseconds >( endtime - starttime ).count(), conflicts ); order++; return; } int main(int argc, char* argv[]){ auto allparams = parse(argc,argv); log_fp=stdout; std::string server = allparams["server"].as<std::string>(); std::string input = allparams["input"].as<std::string>(); uint64_t target = allparams["target"].as<uint64_t>(); uint32_t threads = allparams["threads"].as<uint32_t>(); num = allparams["num"].as<uint64_t>(); float read_prob = allparams["prob"].as<float>(); int seed = allparams["seed"].as<int>(); ClientRDMA rdma((char*)server.c_str(),9999); struct rdma_cm_id * id = rdma.sendConnectRequest(); struct ibv_pd * pd = ClientRDMA::create_pd(id); struct ibv_qp_init_attr attr; struct rdma_conn_param conn_param; memset(&attr, 0, sizeof(attr)); attr.cap.max_send_wr = 32; attr.cap.max_recv_wr = 32; attr.cap.max_send_sge = 1; attr.cap.max_recv_sge = 1; attr.cap.max_inline_data = 0; attr.qp_type = IBV_QPT_RC; attr.send_cq = ibv_create_cq(pd->context, 32, NULL, NULL, 0); attr.recv_cq = ibv_create_cq(pd->context, 32, NULL, NULL, 0); memset(&conn_param, 0 , sizeof(conn_param)); conn_param.responder_resources = 0; conn_param.initiator_depth = 5; conn_param.retry_count = 3; conn_param.rnr_retry_count = 3; std::vector<VerbsEP*> conns; conns.push_back(ClientRDMA::connectEP(id, &attr, &conn_param, pd)); for(uint32_t i = 1 ; i < threads; i++){ struct rdma_cm_id * tid = rdma.sendConnectRequest(); attr.send_cq = ibv_create_cq(pd->context, 32, NULL, NULL, 0); attr.recv_cq = ibv_create_cq(pd->context, 32, NULL, NULL, 0); conns.push_back(ClientRDMA::connectEP(tid, &attr, &conn_param, pd)); } if(threads>1){ assert(conns[0]->qp->send_cq != conns[1]->qp->send_cq && "Different connections must use Different CQ") ; } printf("Connected\n"); sleep(1); std::fstream fout; // printf("File name %s \n",input.c_str()); fout.open(input.c_str(), std::ios::in|std::ios::binary); uint32_t NN = 0; fout.read((char*)&NN,sizeof(NN)); LocalObjectHandler *objects; objects = (LocalObjectHandler*)malloc(NN*sizeof(LocalObjectHandler)); for(uint32_t i = 0; i < NN; i++){ LocalObjectHandler* obj = &objects[i]; fout.read((char*)obj,sizeof(LocalObjectHandler)); // obj->print(); } fout.close(); printf("Finished reading %u objects from file\n", NN); ReadFuncPtr readfunc = nullptr; if(allparams.count("rdmaread")){ readfunc = &RemoteMemoryClient::ReadOneSided; }else { readfunc = &RemoteMemoryClient::Read; } std::vector<std::thread> workers; for(int i = 0; i < (int)threads; i++){ workers.push_back(std::thread(workload_worker,i,conns[i],readfunc, objects, NN, allparams.count("zipf"), seed + i, read_prob,target)); } for (auto& th : workers) th.join(); return 0; }
29.883959
177
0.615692
[ "object", "vector" ]
e00c994b07cd96260710f79d7c2338d1049f1f98
78,521
cpp
C++
src/referenceFrameCalib/src/vxl_util/vpgl_plus.cpp
lood339/CalibMe
03c4f51e63b2ec0824d47fae6daeae8ef52040c7
[ "BSD-2-Clause" ]
1
2022-01-07T10:52:45.000Z
2022-01-07T10:52:45.000Z
src/referenceFrameCalib/src/vxl_util/vpgl_plus.cpp
lood339/CalibMe
03c4f51e63b2ec0824d47fae6daeae8ef52040c7
[ "BSD-2-Clause" ]
null
null
null
src/referenceFrameCalib/src/vxl_util/vpgl_plus.cpp
lood339/CalibMe
03c4f51e63b2ec0824d47fae6daeae8ef52040c7
[ "BSD-2-Clause" ]
null
null
null
// // vpgl_plus.cpp // FinalCalib // // Created by jimmy on 12/31/14. // Copyright (c) 2014 Nowhere Planet. All rights reserved. // #include "vpgl_plus.h" #include <vgl/vgl_intersection.h> #include <vgl/vgl_distance.h> #include <vpgl/algo/vpgl_camera_compute.h> #include <vnl/vnl_least_squares_function.h> #include <vnl/algo/vnl_levenberg_marquardt.h> #include <vgl/algo/vgl_homg_operators_2d.h> #include <vcl_algorithm.h> #include <vgl/algo/vgl_h_matrix_2d_compute_linear.h> #include <vgl/algo/vgl_h_matrix_3d.h> #include <vnl/vnl_double_3.h> #include <vnl/vnl_det.h> #include <vnl/vnl_inverse.h> #include <vpgl/algo/vpgl_optimize_camera.h> #include <vnl/algo/vnl_cholesky.h> #include <vnl/algo/vnl_matrix_inverse.h> #include <vnl/algo/vnl_qr.h> #include <vnl/algo/vnl_determinant.h> #include <vnl/vnl_rank.h> // minimize area between line in image and the projection of "ideal line" in the image // from paper "Using line and ellipse features for rectification of broadcase hockey video" class vpgl_line_area_residual: public vnl_least_squares_function { protected: const vcl_vector< vgl_infinite_line_3d< double > > world_lines_; const vcl_vector< vgl_line_segment_2d< double > > image_lines_; const vgl_point_2d<double> principle_point_; public: vpgl_line_area_residual(const vcl_vector< vgl_infinite_line_3d< double > > &world_lines, const vcl_vector< vgl_line_segment_2d< double > > &image_lines, const vgl_point_2d<double> &pp): vnl_least_squares_function(7, (unsigned int)world_lines.size(), no_gradient), world_lines_(world_lines), image_lines_(image_lines), principle_point_(pp) { assert(world_lines.size() == image_lines.size()); assert(world_lines.size() >= 7); } double area(const vgl_line_2d<double> &line, const vgl_point_2d<double> &p1, const vgl_point_2d<double> &p2) const { return VpglPlus::vpgl_line_linesegment_area(line, p1, p2); } void f(const vnl_vector<double> &x, vnl_vector<double> &fx) { //construct camera vpgl_perspective_camera<double> camera; camera.set_calibration(vpgl_calibration_matrix<double>(x[0], principle_point_)); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); camera.set_rotation(vgl_rotation_3d<double>(rod)); camera.set_camera_center(vgl_point_3d<double>(x[4], x[5], x[6])); //project world_lines to the image for (int i = 0; i<world_lines_.size(); i++) { vgl_line_2d<double> projLine = camera.project(world_lines_[i]); //calculate areas between lines fx[i] = this->area(projLine, image_lines_[i].point1(), image_lines_[i].point2()); } } }; vpgl_perspective_camera< double > VpglPlus::opt_natural( const vpgl_perspective_camera< double >& initCamera, const vcl_vector< vgl_infinite_line_3d< double > >& world_lines, const vcl_vector< vgl_line_segment_2d< double > >& image_lines) { vpgl_perspective_camera< double > opt_camera = initCamera; vgl_point_2d<double> principlePoint = initCamera.get_calibration().principal_point(); vpgl_line_area_residual residual(world_lines, image_lines, principlePoint); //init parameters vnl_vector<double> x(7, 0.0); x[0] = initCamera.get_calibration().get_matrix()[0][0]; x[1] = initCamera.get_rotation().as_rodrigues()[0]; x[2] = initCamera.get_rotation().as_rodrigues()[1]; x[3] = initCamera.get_rotation().as_rodrigues()[2]; x[4] = initCamera.get_camera_center().x(); x[5] = initCamera.get_camera_center().y(); x[6] = initCamera.get_camera_center().z(); vnl_levenberg_marquardt lmq(residual); vcl_cout<<"before opt...\n"<<x<<vcl_endl; bool isMinimizeOk = lmq.minimize(x); vcl_cout<<"after opt...\n"<<x<<vcl_endl; lmq.diagnose_outcome(); vpgl_calibration_matrix<double> K(x[0], principlePoint); opt_camera.set_calibration(K); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); opt_camera.set_rotation(vgl_rotation_3d<double>(rod)); opt_camera.set_camera_center(vgl_point_3d<double>(x[4], x[5], x[6])); if (!isMinimizeOk) { vcl_cout<<"Warning: camera optimization failed.\n"; } return opt_camera; } double VpglPlus::vpgl_line_linesegment_area(const vgl_line_2d<double> &line, const vgl_point_2d<double> &p1, const vgl_point_2d<double> &p2) { double ret = 0.0; //check if two points are on the same side double a = line.a(); double b = line.b(); double c = line.c(); //construct two lines perpendicular with line and cross p1, p2 double a1 = b; double b1 = -a; double c1 = - (a1 * p1.x() + b1 * p1.y()); double c2 = - (a1 * p2.x() + b1 * p2.y()); vgl_line_2d<double> line1(a1, b1, c1); vgl_line_2d<double> line2(a1, b1, c2); vgl_point_2d<double> perpendicular1; vgl_point_2d<double> perpendicular2; //intersect with line bool isIntersect1 = vgl_intersection(line, line1, perpendicular1); bool isIntersect2 = vgl_intersection(line, line2, perpendicular2); if (isIntersect1 && isIntersect2) { double s1 = a * p1.x() + b * p1.y() + c; double s2 = a * p2.x() + b * p2.y() + c; if (s1 * s2 >= 0) { //same side double d1 = vgl_distance(perpendicular1, p1); double d2 = vgl_distance(perpendicular2, p2); double d3 = vgl_distance(perpendicular1, perpendicular2); ret = 0.5 * d3 * (d1 + d2); } else { //p1, p2 are in different side of line //intersection point:line and line(p1, p2); vgl_line_2d<double> line_p1p1(p1, p2); vgl_point_2d<double> p_o; bool isIntersect = vgl_intersection(line, line_p1p1, p_o); if (isIntersect) { double d1 = vgl_distance(perpendicular1, p1); double d2 = vgl_distance(perpendicular2, p2); double d3 = vgl_distance(perpendicular1, p_o); double d4 = vgl_distance(perpendicular2, p_o); ret = 0.5 * (d1 * d3 + d2 * d4); } else { vcl_cout<<"Error: vpgl_line_lineseg_area not find line intersection 1 \n"; } } } else { vcl_cout<<"Error: vpgl_line_lineseg_area not find line intersection 2 \n"; } return ret; } bool VpglPlus::focal_length(const vgl_point_2d<double> vp1, const vgl_point_2d<double> & vp2, double & fl) { double x1 = vp1.x(); double y1 = vp1.y(); double x2 = vp2.x(); double y2 = vp2.y(); double ff = - (x1 * x2 + y1 * y2); if (ff < 0) { return false; } fl = sqrt(ff); return true; } bool VpglPlus::init_calib(const vcl_vector<vgl_point_2d<double> > &wldPts, const vcl_vector<vgl_point_2d<double> > &imgPts, const vgl_point_2d<double> &principlePoint, double focalLength, vpgl_perspective_camera<double> &camera) { if (wldPts.size() < 4 && imgPts.size() < 4) { return false; } if (wldPts.size() != imgPts.size()) { return false; } assert(wldPts.size() >= 4 && imgPts.size() >= 4); assert(wldPts.size() == imgPts.size()); vpgl_calibration_matrix<double> K(focalLength, principlePoint); camera.set_calibration(K); // vpgl_perspective_camera_compute_positiveZ if (vpgl_perspective_camera_compute::compute(imgPts, wldPts, camera) == false) { vcl_cerr<<"Failed to computer R, C"<<vcl_endl; return false; } return true; } static bool vpgl_perspective_camera_compute_positiveZ( const vcl_vector< vgl_point_2d<double> >& image_pts, const vcl_vector< vgl_point_2d<double> >& ground_pts, vpgl_perspective_camera<double>& camera ) { unsigned num_pts = ground_pts.size(); if (image_pts.size()!=num_pts) { vcl_cout << "Unequal points sets in" << " vpgl_perspective_camera_compute::compute()\n"; return false; } if (num_pts<4) { vcl_cout << "Need at least 4 points for" << " vpgl_perspective_camera_compute::compute()\n"; return false; } vcl_vector<vgl_homg_point_2d<double> > pi, pg; for (unsigned i=0; i<num_pts; ++i) { #ifdef CAMERA_DEBUG vcl_cout << '('<<image_pts[i].x()<<", "<<image_pts[i].y()<<") -> " << '('<<ground_pts[i].x()<<", "<<ground_pts[i].y()<<')'<<vcl_endl; #endif pi.push_back(vgl_homg_point_2d<double>(image_pts[i].x(),image_pts[i].y())); pg.push_back(vgl_homg_point_2d<double>(ground_pts[i].x(),ground_pts[i].y())); } // compute a homography from the ground plane to image plane vgl_h_matrix_2d_compute_linear est_H; vnl_double_3x3 H = est_H.compute(pg,pi).get_matrix(); if (vnl_det(H) > 0) H *= -1.0; // invert the effects of intrinsic parameters vnl_double_3x3 Kinv = vnl_inverse(camera.get_calibration().get_matrix()); vnl_double_3x3 A(Kinv*H); // get the translation vector (up to a scale) vnl_vector_fixed<double,3> t = A.get_column(2); t.normalize(); // compute the closest rotation matrix A.set_column(2, vnl_cross_3d(A.get_column(0), A.get_column(1))); vnl_svd<double> svdA(A.as_ref()); vnl_double_3x3 R = svdA.U()*svdA.V().conjugate_transpose(); // find the point farthest from the origin int max_idx = 0; double max_dist = 0.0; for (unsigned int i=0; i < ground_pts.size(); ++i) { double d = (ground_pts[i]-vgl_point_2d<double>(0,0)).length(); if (d >= max_dist) { max_dist = d; max_idx = i; } } // compute the unknown scale vnl_vector_fixed<double,3> i1 = Kinv*vnl_double_3(image_pts[max_idx].x(),image_pts[max_idx].y(),1.0); vnl_vector_fixed<double,3> t1 = vnl_cross_3d(i1, t); vnl_vector_fixed<double,3> p1 = vnl_cross_3d(i1, R*vnl_double_3(ground_pts[max_idx].x(),ground_pts[max_idx].y(),1.0)); double s = p1.magnitude()/t1.magnitude(); // compute the camera center t *= s; t = -R.transpose()*t; camera.set_rotation(vgl_rotation_3d<double>(R)); camera.set_camera_center(vgl_point_3d<double>(t[0],t[1],t[2])); //perform a final non-linear optimization vcl_vector<vgl_homg_point_3d<double> > h_world_pts; for (unsigned i = 0; i<num_pts; ++i) { h_world_pts.push_back(vgl_homg_point_3d<double>(ground_pts[i].x(),ground_pts[i].y(),0,1)); if (camera.is_behind_camera(h_world_pts.back())) { // vcl_cout << "vpgl_perspective_camera_compute_compute behind camera" << vcl_endl; // return false; } } camera = vpgl_optimize_camera::opt_orient_pos(camera, h_world_pts, image_pts); return camera.get_camera_center().z() > 0; } bool VpglPlus::optimize_camera_by_inliers(const vcl_vector<vgl_point_2d<double> > & wldPts, const vcl_vector<vgl_point_2d<double> > & imgPts, const vpgl_perspective_camera<double> & initCamera, const double distance_threshod, vpgl_perspective_camera<double> & finalCamera) { assert(wldPts.size() == imgPts.size()); vcl_vector<vgl_point_2d<double> > wld_inliers; vcl_vector<vgl_point_2d<double> > img_inliers; for (int i = 0; i<wldPts.size(); i++) { vgl_homg_point_3d<double> p(wldPts[i].x(), wldPts[i].y(), 0.0, 1.0); if (initCamera.is_behind_camera(p)) { continue; } vgl_point_2d<double> q = initCamera.project(p); double dis = vgl_distance(imgPts[i], q); if (dis < distance_threshod) { wld_inliers.push_back(wldPts[i]); img_inliers.push_back(imgPts[i]); } } if (wld_inliers.size() < 4) { return false; } return VpglPlus::optimize_perspective_camera(wld_inliers, img_inliers, initCamera, finalCamera); } class optimize_perspective_camera_residual:public vnl_least_squares_function { protected: const vcl_vector<vgl_point_2d<double> > wldPts_; const vcl_vector<vgl_point_2d<double> > imgPts_; const vgl_point_2d<double> principlePoint_; public: optimize_perspective_camera_residual(const vcl_vector<vgl_point_2d<double> > & wldPts, const vcl_vector<vgl_point_2d<double> > & imgPts, const vgl_point_2d<double> & pp): vnl_least_squares_function(7, (unsigned int)(wldPts.size()) * 2, no_gradient), wldPts_(wldPts), imgPts_(imgPts), principlePoint_(pp) { assert(wldPts.size() == imgPts.size()); assert(wldPts.size() >= 4); } void f(vnl_vector<double> const &x, vnl_vector<double> &fx) { //focal length, Rxyz, Camera_center_xyz vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> cc(x[4], x[5], x[6]); //camera center vpgl_perspective_camera<double> camera; camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(cc); //loop all points int idx = 0; for (int i = 0; i<wldPts_.size(); i++) { vgl_point_3d<double> p(wldPts_[i].x(), wldPts_[i].y(), 0); vgl_point_2d<double> proj_p = (vgl_point_2d<double>)camera.project(p); fx[idx] = imgPts_[i].x() - proj_p.x(); idx++; fx[idx] = imgPts_[i].y() - proj_p.y(); idx++; } } void getCamera(vnl_vector<double> const &x, vpgl_perspective_camera<double> &camera) { vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> camera_center(x[4], x[5], x[6]); camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(camera_center); } }; bool VpglPlus::optimize_perspective_camera(const vcl_vector<vgl_point_2d<double> > & wldPts, const vcl_vector<vgl_point_2d<double> > & imgPts, const vpgl_perspective_camera<double> &initCamera, vpgl_perspective_camera<double> & finalCamera) { assert(wldPts.size() == imgPts.size()); assert(wldPts.size() >= 4); optimize_perspective_camera_residual residual(wldPts, imgPts, initCamera.get_calibration().principal_point()); vnl_vector<double> x(7, 0); x[0] = initCamera.get_calibration().get_matrix()[0][0]; x[1] = initCamera.get_rotation().as_rodrigues()[0]; x[2] = initCamera.get_rotation().as_rodrigues()[1]; x[3] = initCamera.get_rotation().as_rodrigues()[2]; x[4] = initCamera.camera_center().x(); x[5] = initCamera.camera_center().y(); x[6] = initCamera.camera_center().z(); vnl_levenberg_marquardt lmq(residual); bool isMinimied = lmq.minimize(x); if (!isMinimied) { vcl_cerr<<"Error: perspective camera optimize not converge.\n"; lmq.diagnose_outcome(); return false; } lmq.diagnose_outcome(); // lmq.diagnose_outcome(); residual.getCamera(x, finalCamera); return true; } class optimize_perspective_camera_ICP_residual: public vnl_least_squares_function { protected: const vcl_vector<vgl_point_2d<double> > wldPts_; const vcl_vector<vgl_point_2d<double> > imgPts_; const vcl_vector<vgl_line_3d_2_points<double> > wldLines_; const vcl_vector<vcl_vector<vgl_point_2d<double> > > imgLinePts_; const vgl_point_2d<double> principlePoint_; public: optimize_perspective_camera_ICP_residual(const vcl_vector<vgl_point_2d<double> > & wldPts, const vcl_vector<vgl_point_2d<double> > & imgPts, const vcl_vector<vgl_line_3d_2_points<double> > & wldLines, const vcl_vector<vcl_vector<vgl_point_2d<double> > > & imgLinePts, const vgl_point_2d<double> & pp, const int num_line_pts): vnl_least_squares_function(7, (unsigned int)(wldPts.size()) * 2 + num_line_pts, no_gradient), wldPts_(wldPts), imgPts_(imgPts), wldLines_(wldLines), imgLinePts_(imgLinePts), principlePoint_(pp) { assert(wldPts.size() == imgPts.size()); assert(wldPts.size() >= 4); assert(wldLines.size() == imgLinePts.size()); } void f(vnl_vector<double> const &x, vnl_vector<double> &fx) { //focal length, Rxyz, Camera_center_xyz vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> cc(x[4], x[5], x[6]); //camera center vpgl_perspective_camera<double> camera; camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(cc); //loop all points int idx = 0; for (int i = 0; i<wldPts_.size(); i++) { vgl_point_3d<double> p(wldPts_[i].x(), wldPts_[i].y(), 0); vgl_point_2d<double> proj_p = (vgl_point_2d<double>)camera.project(p); fx[idx] = imgPts_[i].x() - proj_p.x(); idx++; fx[idx] = imgPts_[i].y() - proj_p.y(); idx++; } // for points locate on the line for (int i = 0; i<wldLines_.size(); i++) { vgl_point_2d<double> p1 = camera.project(wldLines_[i].point1()); vgl_point_2d<double> p2 = camera.project(wldLines_[i].point2()); vgl_line_2d<double> line(p1, p2); for (int j = 0; j<imgLinePts_[i].size(); j++) { vgl_point_2d<double> p3 = imgLinePts_[i][j]; fx[idx] = vgl_distance(line, p3); idx++; } } } void getCamera(vnl_vector<double> const &x, vpgl_perspective_camera<double> &camera) { vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> camera_center(x[4], x[5], x[6]); camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(camera_center); } }; bool VpglPlus::optimize_perspective_camera_ICP(const vcl_vector<vgl_point_2d<double> > &wldPts, const vcl_vector<vgl_point_2d<double> > &imgPts, const vcl_vector<vgl_line_3d_2_points<double> > & wldLines, const vcl_vector<vcl_vector<vgl_point_2d<double> > > & imgLinePts, const vpgl_perspective_camera<double> & initCamera, vpgl_perspective_camera<double> &camera) { assert(wldPts.size() == imgPts.size()); assert(wldPts.size() >= 4); assert(wldLines.size() == imgLinePts.size()); int num_line_pts = 0; for (int i = 0; i<imgLinePts.size(); i++) { num_line_pts += (int)imgLinePts[i].size(); } optimize_perspective_camera_ICP_residual residual(wldPts, imgPts, wldLines, imgLinePts, initCamera.get_calibration().principal_point(), num_line_pts); vnl_vector<double> x(7, 0); x[0] = initCamera.get_calibration().get_matrix()[0][0]; x[1] = initCamera.get_rotation().as_rodrigues()[0]; x[2] = initCamera.get_rotation().as_rodrigues()[1]; x[3] = initCamera.get_rotation().as_rodrigues()[2]; x[4] = initCamera.camera_center().x(); x[5] = initCamera.camera_center().y(); x[6] = initCamera.camera_center().z(); vnl_levenberg_marquardt lmq(residual); bool isMinimied = lmq.minimize(x); if (!isMinimied) { vcl_cerr<<"Error: perspective camera optimize not converge.\n"; lmq.diagnose_outcome(); return false; } lmq.diagnose_outcome(); residual.getCamera(x, camera); return true; } class optimize_perspective_camera_conic_ICP_residual: public vnl_least_squares_function { protected: const vcl_vector<vgl_point_2d<double> > wldPts_; const vcl_vector<vgl_point_2d<double> > imgPts_; const vcl_vector<vgl_conic<double> > wldConics_; const vcl_vector<vcl_vector<vgl_point_2d<double> > > imgConicPts_; const vgl_point_2d<double> principlePoint_; public: optimize_perspective_camera_conic_ICP_residual(const vcl_vector<vgl_point_2d<double> > & wldPts, const vcl_vector<vgl_point_2d<double> > & imgPts, const vcl_vector<vgl_conic<double> > & wldConics, const vcl_vector<vcl_vector<vgl_point_2d<double> > > & imgConicPts, const vgl_point_2d<double> & pp, const int num_conic_pts): vnl_least_squares_function(7, (unsigned int)(wldPts.size()) * 2 + num_conic_pts, no_gradient), wldPts_(wldPts), imgPts_(imgPts), wldConics_(wldConics), imgConicPts_(imgConicPts), principlePoint_(pp) { assert(wldPts.size() == imgPts.size()); assert(wldPts.size() >= 4); assert(wldConics.size() == imgConicPts.size()); } void f(vnl_vector<double> const &x, vnl_vector<double> &fx) { //focal length, Rxyz, Camera_center_xyz vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> cc(x[4], x[5], x[6]); //camera center vpgl_perspective_camera<double> camera; camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(cc); //loop all points int idx = 0; for (int i = 0; i<wldPts_.size(); i++) { vgl_point_3d<double> p(wldPts_[i].x(), wldPts_[i].y(), 0); vgl_point_2d<double> proj_p = (vgl_point_2d<double>)camera.project(p); fx[idx] = imgPts_[i].x() - proj_p.x(); idx++; fx[idx] = imgPts_[i].y() - proj_p.y(); idx++; } vnl_matrix_fixed<double, 3, 3> H = VpglPlus::homographyFromProjectiveCamera(camera); // for points locate on the conics for (int i = 0; i<wldConics_.size(); i++) { vgl_conic<double> conic_proj = VpglPlus::projectConic(H, wldConics_[i]); for (int j = 0; j<imgConicPts_[i].size(); j++) { vgl_point_2d<double> p = imgConicPts_[i][j]; double dis = vgl_homg_operators_2d<double>::distance_squared(conic_proj, vgl_homg_point_2d<double>(p.x(), p.y(), 1.0)); // printf("distance is %f\n", dis); dis = sqrt(dis + 0.0000001); fx[idx] = dis; idx++; } } } void getCamera(vnl_vector<double> const &x, vpgl_perspective_camera<double> &camera) { vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> camera_center(x[4], x[5], x[6]); camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(camera_center); } }; bool VpglPlus::optimize_perspective_camera_ICP(const vcl_vector<vgl_point_2d<double> > &wldPts, const vcl_vector<vgl_point_2d<double> > &imgPts, const vcl_vector<vgl_conic<double> > & wldConics, const vcl_vector<vcl_vector<vgl_point_2d<double> > > & imgConicPts, const vpgl_perspective_camera<double> & initCamera, vpgl_perspective_camera<double> &camera) { assert(wldPts.size() == imgPts.size()); assert(wldConics.size() == imgConicPts.size()); assert(wldPts.size() >= 4); // only for circle for (int i = 0; i<wldConics.size(); i++) { vcl_string name = wldConics[i].real_type(); if(name != "real circle") { printf("Error: conic ICP only must be a circle!\n"); return false; } } int num_conic_pts = 0; for (int i = 0; i<imgConicPts.size(); i++) { num_conic_pts += (int)imgConicPts[i].size(); } optimize_perspective_camera_conic_ICP_residual residual(wldPts, imgPts, wldConics, imgConicPts, initCamera.get_calibration().principal_point(), num_conic_pts); vnl_vector<double> x(7, 0); x[0] = initCamera.get_calibration().get_matrix()[0][0]; x[1] = initCamera.get_rotation().as_rodrigues()[0]; x[2] = initCamera.get_rotation().as_rodrigues()[1]; x[3] = initCamera.get_rotation().as_rodrigues()[2]; x[4] = initCamera.camera_center().x(); x[5] = initCamera.camera_center().y(); x[6] = initCamera.camera_center().z(); vnl_levenberg_marquardt lmq(residual); bool isMinimied = lmq.minimize(x); if (!isMinimied) { vcl_cerr<<"Error: perspective camera optimize not converge.\n"; lmq.diagnose_outcome(); return false; } lmq.diagnose_outcome(); residual.getCamera(x, camera); return true; } class optimize_perspective_camera_line_conic_ICP_residual: public vnl_least_squares_function { protected: const vcl_vector<vgl_point_2d<double> > wldPts_; const vcl_vector<vgl_point_2d<double> > imgPts_; const vcl_vector<vgl_line_3d_2_points<double> > wldLines_; const vcl_vector<vcl_vector<vgl_point_2d<double> > > imgLinePts_; const vcl_vector<vgl_conic<double> > wldConics_; const vcl_vector<vcl_vector<vgl_point_2d<double> > > imgConicPts_; const vgl_point_2d<double> principlePoint_; public: optimize_perspective_camera_line_conic_ICP_residual(const vcl_vector<vgl_point_2d<double> > & wldPts, const vcl_vector<vgl_point_2d<double> > & imgPts, const vcl_vector<vgl_line_3d_2_points<double> > & wldLines, const vcl_vector<vcl_vector<vgl_point_2d<double> > > & imgLinePts, const vcl_vector<vgl_conic<double> > & wldConics, const vcl_vector<vcl_vector<vgl_point_2d<double> > > & imgConicPts, const vgl_point_2d<double> & pp, const int num_line_pts, const int num_conic_pts): vnl_least_squares_function(7, (unsigned int)(wldPts.size()) * 2 + num_line_pts + num_conic_pts, no_gradient), wldPts_(wldPts), imgPts_(imgPts), wldLines_(wldLines), imgLinePts_(imgLinePts), wldConics_(wldConics), imgConicPts_(imgConicPts), principlePoint_(pp) { assert(wldPts.size() == imgPts.size()); assert(wldPts.size() >= 2); assert(wldLines.size() == imgLinePts.size()); assert(wldConics.size() == imgConicPts.size()); } void f(vnl_vector<double> const &x, vnl_vector<double> &fx) { //focal length, Rxyz, Camera_center_xyz vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> cc(x[4], x[5], x[6]); //camera center vpgl_perspective_camera<double> camera; camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(cc); //loop all points int idx = 0; for (int i = 0; i<wldPts_.size(); i++) { vgl_point_3d<double> p(wldPts_[i].x(), wldPts_[i].y(), 0); vgl_point_2d<double> proj_p = (vgl_point_2d<double>)camera.project(p); fx[idx] = imgPts_[i].x() - proj_p.x(); idx++; fx[idx] = imgPts_[i].y() - proj_p.y(); idx++; } // for points locate on the line for (int i = 0; i<wldLines_.size(); i++) { vgl_point_2d<double> p1 = camera.project(wldLines_[i].point1()); vgl_point_2d<double> p2 = camera.project(wldLines_[i].point2()); vgl_line_2d<double> line(p1, p2); for (int j = 0; j<imgLinePts_[i].size(); j++) { vgl_point_2d<double> p3 = imgLinePts_[i][j]; fx[idx] = vgl_distance(line, p3); idx++; } } // for points locate on the conics vnl_matrix_fixed<double, 3, 3> H = VpglPlus::homographyFromProjectiveCamera(camera); for (int i = 0; i<wldConics_.size(); i++) { vgl_conic<double> conic_proj = VpglPlus::projectConic(H, wldConics_[i]); for (int j = 0; j<imgConicPts_[i].size(); j++) { vgl_point_2d<double> p = imgConicPts_[i][j]; double dis = vgl_homg_operators_2d<double>::distance_squared(conic_proj, vgl_homg_point_2d<double>(p.x(), p.y(), 1.0)); dis = sqrt(dis + 0.0000001); fx[idx] = dis; idx++; } } } void getCamera(vnl_vector<double> const &x, vpgl_perspective_camera<double> &camera) { vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> camera_center(x[4], x[5], x[6]); camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(camera_center); } }; bool VpglPlus::optimize_perspective_camera_ICP(const vcl_vector<vgl_point_2d<double> > &wldPts, const vcl_vector<vgl_point_2d<double> > &imgPts, const vcl_vector<vgl_line_3d_2_points<double> > & wldLines, const vcl_vector<vcl_vector<vgl_point_2d<double> > > & imgLinePts, const vcl_vector<vgl_conic<double> > & wldConics, const vcl_vector<vcl_vector<vgl_point_2d<double> > > & imgConicPts, const vpgl_perspective_camera<double> & initCamera, vpgl_perspective_camera<double> &camera) { assert(wldPts.size() == imgPts.size()); assert(wldLines.size() == imgLinePts.size()); assert(wldConics.size() == imgConicPts.size()); int num_line_pts = 0; int num_conic_pts = 0; for (int i = 0; i<imgLinePts.size(); i++) { num_line_pts += imgLinePts[i].size(); } for (int i = 0; i<imgConicPts.size(); i++) { num_conic_pts += imgConicPts[i].size(); } assert((unsigned int)(wldPts.size()) * 2 + num_line_pts + num_conic_pts > 7); optimize_perspective_camera_line_conic_ICP_residual residual(wldPts, imgPts, wldLines, imgLinePts, wldConics, imgConicPts, initCamera.get_calibration().principal_point(), num_line_pts, num_conic_pts); vnl_vector<double> x(7, 0); x[0] = initCamera.get_calibration().get_matrix()[0][0]; x[1] = initCamera.get_rotation().as_rodrigues()[0]; x[2] = initCamera.get_rotation().as_rodrigues()[1]; x[3] = initCamera.get_rotation().as_rodrigues()[2]; x[4] = initCamera.camera_center().x(); x[5] = initCamera.camera_center().y(); x[6] = initCamera.camera_center().z(); vnl_levenberg_marquardt lmq(residual); bool isMinimied = lmq.minimize(x); if (!isMinimied) { vcl_cerr<<"Error: perspective camera optimize not converge.\n"; lmq.diagnose_outcome(); return false; } lmq.diagnose_outcome(); residual.getCamera(x, camera); return true; } class optimize_perspective_camera_3d_residual :public vnl_least_squares_function { protected: const vcl_vector<vgl_point_3d<double> > wldPts_; const vcl_vector<vgl_point_2d<double> > imgPts_; const vgl_point_2d<double> principlePoint_; public: optimize_perspective_camera_3d_residual(const vcl_vector<vgl_point_3d<double> > & wldPts, const vcl_vector<vgl_point_2d<double> > & imgPts, const vgl_point_2d<double> & pp): vnl_least_squares_function(7, (unsigned int)(wldPts.size()) * 2, no_gradient), wldPts_(wldPts), imgPts_(imgPts), principlePoint_(pp) { assert(wldPts.size() == imgPts.size()); assert(wldPts.size() >= 5); } void f(vnl_vector<double> const &x, vnl_vector<double> &fx) { //focal length, Rxyz, Camera_center_xyz vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> cc(x[4], x[5], x[6]); //camera center vpgl_perspective_camera<double> camera; camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(cc); //loop all points int idx = 0; for (int i = 0; i<wldPts_.size(); i++) { vgl_point_2d<double> proj_p = (vgl_point_2d<double>)camera.project(wldPts_[i]); fx[idx] = imgPts_[i].x() - proj_p.x(); idx++; fx[idx] = imgPts_[i].y() - proj_p.y(); idx++; } } void getCamera(vnl_vector<double> const &x, vpgl_perspective_camera<double> &camera) { vpgl_calibration_matrix<double> K(x[0], principlePoint_); vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> camera_center(x[4], x[5], x[6]); camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(camera_center); } }; bool VpglPlus::optimize_perspective_camera(const vcl_vector<vgl_point_3d<double> > & wldPts, const vcl_vector<vgl_point_2d<double> > & imgPts, const vpgl_perspective_camera<double> & initCamera, vpgl_perspective_camera<double> & finalCamera) { assert(wldPts.size() == imgPts.size()); optimize_perspective_camera_3d_residual residual(wldPts, imgPts, initCamera.get_calibration().principal_point()); vnl_vector<double> x(7, 0); x[0] = initCamera.get_calibration().get_matrix()[0][0]; x[1] = initCamera.get_rotation().as_rodrigues()[0]; x[2] = initCamera.get_rotation().as_rodrigues()[1]; x[3] = initCamera.get_rotation().as_rodrigues()[2]; x[4] = initCamera.camera_center().x(); x[5] = initCamera.camera_center().y(); x[6] = initCamera.camera_center().z(); vnl_levenberg_marquardt lmq(residual); bool isMinimied = lmq.minimize(x); if (!isMinimied) { vcl_cerr<<"Error: perspective camera optimize not converge.\n"; lmq.diagnose_outcome(); return false; } lmq.diagnose_outcome(); lmq.diagnose_outcome(); residual.getCamera(x, finalCamera); return true; } vgl_conic<double> VpglPlus::projectConic(const vnl_matrix_fixed<double, 3, 3> & H, const vgl_conic<double> & conic) { double a = conic.a(); double b = conic.b(); double c = conic.c(); double d = conic.d(); double e = conic.e(); double f = conic.f(); vnl_matrix_fixed<double, 3, 3> C; C(0, 0) = a; C(0, 1) = b/2.0; C(0, 2) = d/2.0; C(1, 0) = b/2.0; C(1, 1) = c; C(1, 2) = e/2.0; C(2, 0) = d/2.0; C(2, 1) = e/2.0; C(2, 2) = f; // project conic by H vnl_matrix_fixed<double, 3, 3> H_inv = vnl_inverse(H); vnl_matrix_fixed<double, 3, 3> C_proj = H_inv.transpose() * C * H_inv; // approximate a conic from 3*3 matrix double aa = C_proj(0, 0); double bb = (C_proj(0, 1) + C_proj(1, 0)); double cc = C_proj(1, 1); double dd = (C_proj(0, 2) + C_proj(2, 0)); double ee = (C_proj(1, 2) + C_proj(2, 1)); double ff = C_proj(2, 2); // project conic vgl_conic<double> conic_proj(aa, bb, cc, dd, ee, ff); return conic_proj; } // static bool vpgl_vgl_inside_image(const vgl_point_2d<double> &p, int width, int height) { return p.x() >= 0 && p.x() < width && p.y() >= 0 && p.y() < height; } bool VpglPlus::sampleLineSegment(const vpgl_perspective_camera<double> & camera, int imageW, int imageH, const vgl_line_segment_2d<double> & init_segment, double sampleUnit, vgl_line_segment_2d<double> & sampled_segment) { vgl_point_3d<double> p1(init_segment.point1().x(), init_segment.point1().y(), 0); vgl_point_3d<double> p2(init_segment.point2().x(), init_segment.point2().y(), 0); if (camera.is_behind_camera(vgl_homg_point_3d<double>(p1)) || camera.is_behind_camera(vgl_homg_point_3d<double>(p2))) { return false; } vgl_point_2d<double> q1(-1, -1); // (-1, -1) is the mask for unfined end point vgl_point_2d<double> q2(-1, -1); vgl_vector_2d<double> dir = init_segment.direction(); const double length = vgl_distance(p1, p2); // length is measured in world coordinate vgl_point_2d<double> p3(-1, -1); // points in world coordinate vgl_point_2d<double> p4(-1, -1); // sample first point from p1 to p2 in the image bool isFound = false; for (double j = 0; j <= length; j += sampleUnit) { double x = p1.x() + dir.x() * j; double y = p1.y() + dir.y() * j; vgl_point_2d<double> q = camera.project(vgl_point_3d<double>(x, y, 0.0)); if (vpgl_vgl_inside_image(q, imageW, imageH)) { q1 = q; p3 = vgl_point_2d<double>(x, y); isFound = true; break; } } if (!isFound) { return false; } isFound = false; // sample second point from p2 to p1 in the image for (double j = length; j >= 0; j -= sampleUnit) { double x = p1.x() + dir.x() * j; double y = p1.y() + dir.y() * j; vgl_point_2d<double> q = camera.project(vgl_point_3d<double>(x, y, 0.0)); if (vpgl_vgl_inside_image(q, imageW, imageH)) { q2 = q; p4 = vgl_point_2d<double>(x, y); isFound = true; break; } } if (!isFound) { return false; } double dis = vgl_distance(p3, p4); // at if (dis > 2 * sampleUnit) { sampled_segment = vgl_line_segment_2d<double>(p3, p4); return true; } return false; } bool VpglPlus::sampleLineSegment(const vpgl_perspective_camera<double> & camera, int imageW, int imageH, const vgl_line_segment_3d<double> & init_segment, double sampleUnit, vgl_line_segment_3d<double> & sampled_segment) { vgl_point_3d<double> p1 = init_segment.point1(); vgl_point_3d<double> p2 = init_segment.point2(); if (camera.is_behind_camera(vgl_homg_point_3d<double>(p1)) || camera.is_behind_camera(vgl_homg_point_3d<double>(p2))) { return false; } vgl_vector_3d<double> dir = init_segment.direction(); dir = normalize(dir); const double length = vgl_distance(p1, p2); // length is measured in world coordinate vgl_point_3d<double> p3(-1, -1, -1); // points in world coordinate vgl_point_3d<double> p4(-1, -1, -1); // sample first point from p1 to p2 in the image bool isFound = false; for (double j = 0; j <= length; j += sampleUnit) { double x = p1.x() + dir.x() * j; double y = p1.y() + dir.y() * j; double z = p1.z() + dir.z() * j; vgl_point_2d<double> q = camera.project(vgl_point_3d<double>(x, y, z)); if (vpgl_vgl_inside_image(q, imageW, imageH)) { p3 = vgl_point_3d<double>(x, y, z); isFound = true; break; } } if (!isFound) { return false; } isFound = false; // sample second point from p2 to p1 in the image for (double j = length; j >= 0; j -= sampleUnit) { double x = p1.x() + dir.x() * j; double y = p1.y() + dir.y() * j; double z = p1.z() + dir.z() * j; vgl_point_2d<double> q = camera.project(vgl_point_3d<double>(x, y, z)); if (vpgl_vgl_inside_image(q, imageW, imageH)) { p4 = vgl_point_3d<double>(x, y, z); isFound = true; break; } } if (!isFound) { return false; } double dis = vgl_distance(p3, p4); // at if (dis > 2 * sampleUnit) { sampled_segment = vgl_line_segment_3d<double>(p3, p4); return true; } return false; } double VpglPlus::projectLineWidth(const vpgl_perspective_camera<double> & camera, const vgl_line_segment_2d<double> & segment, double lineWidth) { vgl_line_segment_2d<double> dump; return VpglPlus::projectLineWidth(camera, segment, lineWidth, dump); } double VpglPlus::projectLineWidth(const vpgl_perspective_camera<double> & camera, const vgl_line_segment_2d<double> & segment, double lineWidth, vgl_line_segment_2d<double> & projectedNorm) { vgl_point_2d<double> p1 = segment.point_t(0.5); // center vgl_vector_2d<double> norm = segment.normal(); vgl_point_2d<double> p2 = vgl_point_2d<double>(p1.x() + (lineWidth * norm).x(), p1.y() + (lineWidth * norm).y()); // center width displacment vgl_point_2d<double> q1 = camera.project(vgl_point_3d<double>(p1.x(), p1.y(), 0.0)); vgl_point_2d<double> q2 = camera.project(vgl_point_3d<double>(p2.x(), p2.y(), 0.0)); projectedNorm = vgl_line_segment_2d<double>(q1, q2); return vgl_distance(q1, q2); } vnl_matrix_fixed<double, 3, 3> VpglPlus::homographyFromProjectiveCamera(const vpgl_perspective_camera<double> & camera) { vnl_matrix_fixed<double, 3, 3> H; vnl_matrix_fixed<double, 3, 4> P = camera.get_matrix(); H(0, 0) = P(0, 0); H(0, 1) = P(0, 1); H(0, 2) = P(0, 3); H(1, 0) = P(1, 0); H(1, 1) = P(1, 1); H(1, 2) = P(1, 3); H(2, 0) = P(2, 0); H(2, 1) = P(2, 1); H(2, 2) = P(2, 3); return H; } void VpglPlus::matrixFromPanYTiltX(double pan, double tilt, vnl_matrix_fixed<double, 3, 3> &m) { pan *= vnl_math::pi / 180.0; tilt *= vnl_math::pi / 180.0; vnl_matrix_fixed<double, 3, 3> R_tilt; R_tilt[0][0] = 1; R_tilt[0][1] = 0; R_tilt[0][2] = 0; R_tilt[1][0] = 0; R_tilt[1][1] = cos(tilt); R_tilt[1][2] = sin(tilt); R_tilt[2][0] = 0; R_tilt[2][1] = -sin(tilt); R_tilt[2][2] = cos(tilt); vnl_matrix_fixed<double, 3, 3> R_pan; R_pan[0][0] = cos(pan); R_pan[0][1] = 0; R_pan[0][2] = -sin(pan); R_pan[1][0] = 0; R_pan[1][1] = 1; R_pan[1][2] = 0; R_pan[2][0] = sin(pan); R_pan[2][1] = 0; R_pan[2][2] = cos(pan); m = R_tilt * R_pan; } void VpglPlus::matrixFromPanYTiltX(double pan, double tilt, vnl_matrix_fixed<double, 4, 4> & m) { vnl_matrix_fixed<double, 3, 3> r; VpglPlus::matrixFromPanYTiltX(pan, tilt, r); m.set_identity(); for (int i = 0; i<3; i++) { for (int j = 0; j<3; j++) { m(i, j) = r(i, j); } } } vnl_matrix<double> VpglPlus::matrixPanY(double pan) { pan *= vnl_math::pi / 180.0; vnl_matrix_fixed<double, 3, 3> R_pan; R_pan[0][0] = cos(pan); R_pan[0][1] = 0; R_pan[0][2] = -sin(pan); R_pan[1][0] = 0; R_pan[1][1] = 1; R_pan[1][2] = 0; R_pan[2][0] = sin(pan); R_pan[2][1] = 0; R_pan[2][2] = cos(pan); return R_pan; } vnl_matrix<double> VpglPlus::matrixTiltX(double tilt) { tilt *= vnl_math::pi / 180.0; vnl_matrix_fixed<double, 3, 3> R_tilt; R_tilt[0][0] = 1; R_tilt[0][1] = 0; R_tilt[0][2] = 0; R_tilt[1][0] = 0; R_tilt[1][1] = cos(tilt); R_tilt[1][2] = sin(tilt); R_tilt[2][0] = 0; R_tilt[2][1] = -sin(tilt); R_tilt[2][2] = cos(tilt); return R_tilt; } void VpglPlus::panYtiltXFromPrinciplePoint(const vgl_point_2d<double> & pp, const vnl_vector_fixed<double, 3> & pp_ptz, const vgl_point_2d<double> & p2, vnl_vector_fixed<double, 3> & p2_ptz) { double dx = p2.x() - pp.x(); double dy = p2.y() - pp.y(); double pan_pp = pp_ptz[0]; double tilt_pp = pp_ptz[1]; double focal_length = pp_ptz[2]; double delta_pan = atan2(dx, focal_length) * 180/vnl_math::pi; double delta_tilt = atan2(dy, focal_length) * 180/vnl_math::pi; double pan2 = pan_pp + delta_pan; double tilt2 = tilt_pp - delta_tilt; // y is upside down p2_ptz[0] = pan2; p2_ptz[1] = tilt2; p2_ptz[2] = focal_length; } void VpglPlus::panYtiltXFromPrinciplePointEncodeFocalLength(const vgl_point_2d<double> & pp, const vnl_vector_fixed<double, 3> & pp_ptz, const vgl_point_2d<double> & p2, vnl_vector_fixed<double, 3> & p2_ptz) { double dx = p2.x() - pp.x(); double dy = p2.y() - pp.y(); double pan_pp = pp_ptz[0]; double tilt_pp = pp_ptz[1]; double focal_length = pp_ptz[2]; double delta_pan = atan2(dx, focal_length) * 180/vnl_math::pi; double delta_tilt = atan2(dy, focal_length) * 180/vnl_math::pi; double pan2 = pan_pp + delta_pan; double tilt2 = tilt_pp - delta_tilt; // y is upside down p2_ptz[0] = pan2; p2_ptz[1] = tilt2; p2_ptz[2] = sqrt(focal_length * focal_length + dx * dx + dy * dy); } void VpglPlus::panTiltFromReferencePoint(const vgl_point_2d<double> & reference_point, const vnl_vector_fixed<double, 3> & reference_ptz, const vgl_point_2d<double> & principle_point, vnl_vector_fixed<double, 3> & ptz) { double dx = reference_point.x() - principle_point.x(); double dy = reference_point.y() - principle_point.y(); double ref_pan = reference_ptz[0]; double ref_tilt = reference_ptz[1]; double fl = reference_ptz[2]; double delta_pan = atan2(dx, fl) * 180.0/vnl_math::pi; double delta_tilt = atan2(dy, fl) * 180.0/vnl_math::pi; ptz[0] = ref_pan - delta_pan; ptz[1] = ref_tilt + delta_tilt; ptz[2] = fl; } void VpglPlus::panTiltFromReferencePointDecodeFocalLength(const vgl_point_2d<double> & reference_point, const vnl_vector_fixed<double, 3> & reference_ptz, const vgl_point_2d<double> & principle_point, vnl_vector_fixed<double, 3> & ptz) { double dx = reference_point.x() - principle_point.x(); double dy = reference_point.y() - principle_point.y(); double ref_pan = reference_ptz[0]; double ref_tilt = reference_ptz[1]; double fl = reference_ptz[2]; double delta_pan = atan2(dx, fl) * 180.0/vnl_math::pi; double delta_tilt = atan2(dy, fl) * 180.0/vnl_math::pi; ptz[0] = ref_pan - delta_pan; ptz[1] = ref_tilt + delta_tilt; if (fl*fl - dx*dx - dy*dy > 0) { ptz[2] = sqrt(fl*fl - dx*dx - dy*dy); } else { ptz[2] = fl; } } void VpglPlus::matrixFromRotationCameraCenter(const vnl_matrix_fixed<double, 3, 3> &rot, const vgl_point_3d<double> &cameraCenter, vnl_matrix_fixed<double, 4, 4> &outMatrix) { vnl_matrix_fixed<double, 3, 4> translation; translation.set_identity(); translation[0][3] = -cameraCenter.x(); translation[1][3] = -cameraCenter.y(); translation[2][3] = -cameraCenter.z(); vnl_matrix_fixed<double, 3, 4> rot_tras_34 = rot * translation; outMatrix.set_identity(); for (int i = 0; i<3; i++) { for (int j = 0; j<4; j++) { outMatrix[i][j] = rot_tras_34[i][j]; } } } vnl_matrix<double> VpglPlus::eularToRotation(const double y_angle, const double z_angle, const double x_angle) { // http://www.cprogramming.com/tutorial/3d/rotationMatrices.html // right hand double pan = y_angle; double tilt = x_angle; double rotate = z_angle; vnl_matrix<double> R_pan(3, 3, 0); R_pan[0][0] = cos(pan); R_pan[0][1] = 0; R_pan[0][2] = sin(pan); R_pan[1][0] = 0; R_pan[1][1] = 1; R_pan[1][2] = 0; R_pan[2][0] = -sin(pan); R_pan[2][1] = 0; R_pan[2][2] = cos(pan); vnl_matrix<double> R_tilt(3, 3, 0); R_tilt[0][0] = 1; R_tilt[0][1] = 0; R_tilt[0][2] = 0; R_tilt[1][0] = 0; R_tilt[1][1] = cos(tilt); R_tilt[1][2] = -sin(tilt); R_tilt[2][0] = 0; R_tilt[2][1] = sin(tilt); R_tilt[2][2] = cos(tilt); vnl_matrix<double> R_rotate(3, 3, 0); R_rotate[0][0] = cos(rotate); R_rotate[0][1] = -sin(rotate); R_rotate[0][2] = 0; R_rotate[1][0] = sin(rotate); R_rotate[1][1] = cos(rotate); R_rotate[1][2] = 0; R_rotate[2][0] = 0; R_rotate[2][1] = 0; R_rotate[2][2] = 1; return R_tilt*R_rotate*R_pan; } bool VpglPlus::decomposeCameraPTZ(double fl, const vnl_vector_fixed<double, 6> & coeff, const vgl_point_2d<double> & principlePoint, double pan, double tilt, const vnl_vector_fixed<double, 3> & rod, const vgl_point_3d<double> & cameraCenter, vpgl_perspective_camera<double> & camera) { double c1 = coeff[0]; double c2 = coeff[1]; double c3 = coeff[2]; double c4 = coeff[3]; double c5 = coeff[4]; double c6 = coeff[5]; vgl_rotation_3d<double> Rs(rod); // model rotation vpgl_calibration_matrix<double> K(fl, principlePoint); vnl_matrix_fixed<double, 3, 4> C; C.set_identity(); C(0, 3) = - (c1 + c4 * fl); C(1, 3) = - (c2 + c5 * fl); C(2, 3) = - (c3 + c6 * fl); vnl_matrix_fixed<double, 4, 4> Q; //rotation from pan tilt angle VpglPlus::matrixFromPanYTiltX(pan, tilt, Q); vnl_matrix_fixed<double, 4, 4> RSD; VpglPlus::matrixFromRotationCameraCenter(Rs.as_matrix(), cameraCenter, RSD); vnl_matrix_fixed<double, 3, 4> P = K.get_matrix() * C * Q * RSD; return vpgl_perspective_decomposition(P, camera); } bool VpglPlus::decomposeCameraPTZ(double fl, double pan, double tilt, vpgl_perspective_camera<double> & camera) { assert(fl > 1000); //estimte fl, pan, tilt from camera vgl_point_3d<double> cc(12.9456, -14.8695, 6.21215); //camera center vnl_vector_fixed<double, 3> rod; // 1.58044 -0.118628 0.124857 rod[0] = 1.58044; rod[1] = -0.118628; rod[2] = 0.124857; vnl_vector_fixed<double, 6> coeff; // 0.570882 0.0310795 -0.533881 -0.000229727 -5.68634e-06 0.000266362 coeff[0] = 0.570882; coeff[1] = 0.0310795; coeff[2] = -0.533881; coeff[3] = -0.000229727; coeff[4] = -5.68634e-06; coeff[5] = 0.000266362; vgl_point_2d<double> pp(640, 360); //principle point return VpglPlus::decomposeCameraPTZ(fl, coeff, pp, pan, tilt, rod, cc, camera); } //example: //glMatrixMode (GL_MODELVIEW); //glClear (GL_COLOR_BUFFER_BIT); //glLoadIdentity (); /* clear the matrix */ //glLoadMatrixd(glCamera.model_view_.data_block()); //glMatrixMode (GL_PROJECTION); //glLoadIdentity(); //glOrtho(0, width, height, 0, -0.1, 25); //glMultMatrixd(glCamera.proj_.data_block()); void VpglPlus::cameraToOpenGLCamera(const vpgl_perspective_camera<double> & camera, OpenglCamera & glCamera, double scale) { vnl_matrix<double> R = camera.get_rotation().as_matrix(); vnl_matrix<double> Tmat(3, 4, 0); Tmat.set_identity(); Tmat(0, 3) = -camera.get_camera_center().x(); Tmat(1, 3) = -camera.get_camera_center().y(); Tmat(2, 3) = -camera.get_camera_center().z(); vnl_matrix<double> RT = R * Tmat; vnl_matrix<double> m44(4, 4, 0); m44.set_identity(); m44.update(RT, 0, 0); m44 = m44.transpose(); glCamera.model_view_ = m44; double alpha = scale * camera.get_calibration().focal_length(); double beta = scale * camera.get_calibration().focal_length(); double u0 = scale * camera.get_calibration().principal_point().x(); double v0 = scale * camera.get_calibration().principal_point().y(); glCamera.proj_ = VpglPlus::opengl_projection_from_intrinsics(alpha, beta, 0.0, u0, v0, -0.1, 25); } // from http://jamesgregson.blogspot.ca/2011/11/matching-calibrated-cameras-with-opengl.html // http://www.songho.ca/opengl/gl_projectionmatrix.html vnl_matrix<double> VpglPlus::opengl_projection_from_intrinsics( double alpha, double beta, double skew, double u0, double v0, double near_clip, double far_clip ) { assert(near_clip < 0.0); double N = near_clip; double F = far_clip; vnl_matrix<double> projection = vnl_matrix<double>(4, 4, 0); projection(0,0) = alpha; projection(0,1) = skew; projection(0,2) = u0; projection(1,0) = 0.0; projection(1,1) = beta; projection(1,2) = v0; projection(2,0) = 0.0; projection(2,1) = 0.0; projection(2,2) = -(N+F); projection(2,3) = -N*F; projection(3,0) = 0.0; projection(3,1) = 0.0; projection(3,2) = 1.0; projection(3,3) = 0.0; projection = projection.transpose(); return projection; } vgl_h_matrix_2d<double> VpglPlus::cameraViewToWorld(const vpgl_perspective_camera<double> & camera) { // homography from P matrix vnl_matrix_fixed<double, 3, 4> P = camera.get_matrix(); double data[3][3] = {0}; for (int i = 0; i<3; i++) { data[i][0] = P(i, 0); data[i][1] = P(i, 1); data[i][2] = P(i, 3); } vgl_h_matrix_2d<double> H(&(data[0][0])); vgl_h_matrix_2d<double> inV = H.get_inverse(); return inV; } vgl_h_matrix_2d<double> VpglPlus::homographyFromCameraToCamera(const vpgl_perspective_camera<double> & cameraA, const vpgl_perspective_camera<double> & cameraB) { vnl_matrix<double> K1 = cameraA.get_calibration().get_matrix().as_matrix(); vnl_matrix<double> R1 = cameraA.get_rotation().as_matrix().as_matrix(); vnl_matrix<double> K2 = cameraB.get_calibration().get_matrix().as_matrix(); vnl_matrix<double> R2 = cameraB.get_rotation().as_matrix().as_matrix(); // H2 * H1^{-1} vnl_matrix<double> H = K2 * R2 * vnl_matrix_inverse<double>(K1*R1); H /= H(2, 2); assert(H.rows() == 3 && H.cols() == 3); return vgl_h_matrix_2d<double>(vnl_matrix_fixed<double,3,3>(H)); } class calibrate_pure_rotate_camera_residual : public vnl_least_squares_function { protected: const vcl_vector<vgl_point_2d<double> > pts1_; const vcl_vector<vgl_point_2d<double> > pts2_; const vnl_matrix_fixed<double, 3, 3> invR1_; const vnl_matrix_fixed<double, 3, 3> invK1_; const vgl_point_2d<double> pp_; // principle point public: calibrate_pure_rotate_camera_residual(const vcl_vector<vgl_point_2d<double> > & pts1, const vcl_vector<vgl_point_2d<double> > & pts2, const vnl_matrix_fixed<double, 3, 3> & invR1, const vnl_matrix_fixed<double, 3, 3> & invK1, const vgl_point_2d<double> & pp): vnl_least_squares_function(4, 2*(int)pts1.size(), no_gradient), pts1_(pts1), pts2_(pts2), invR1_(invR1), invK1_(invK1), pp_(pp) { assert(pts1.size() >= 4); assert(pts1.size() == pts2.size()); } void f(vnl_vector<double> const &x, vnl_vector<double> &fx) { double fl = x[0]; vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R2(rod); vnl_matrix_fixed<double, 3, 3> R2mat = R2.as_matrix(); vnl_matrix_fixed<double, 3, 3> K2; K2.fill(0); K2(0, 0) = K2(1, 1) = fl; K2(0, 2) = pp_.x(); K2(1, 2) = pp_.y(); K2(2, 2) = 1.0; // x2 = K_2 * R_2 * R_1^{-1} * K_1^{-1} x1 int idx = 0; for (int i = 0; i<pts1_.size(); i++) { vnl_vector_fixed<double, 3> p(pts1_[i].x(), pts1_[i].y(), 1.0); vnl_vector_fixed<double, 3> q = K2 * R2mat * invR1_ * invK1_ * p; double x = q[0]/q[2]; double y = q[1]/q[2]; fx[idx] = pts2_[i].x() - x; idx++; fx[idx] = pts2_[i].y() - y; idx++; } } void setCameraMatrixRotation(vnl_vector<double> const &x, vpgl_perspective_camera<double> & camera) { double fl = x[0]; vnl_vector_fixed<double, 3> rod(x[1], x[2], x[3]); vgl_rotation_3d<double> R2(rod); camera.set_calibration(vpgl_calibration_matrix<double>(fl, pp_)); camera.set_rotation(R2); } }; bool VpglPlus::calibrate_pure_rotate_camera(const vcl_vector<vgl_point_2d<double> > & pts1, const vcl_vector<vgl_point_2d<double> > & pts2, const vpgl_perspective_camera<double> & camera1, vpgl_perspective_camera<double> & camera2) { assert(pts1.size() == pts2.size()); assert(pts1.size() >= 4); vnl_matrix_fixed<double, 3, 3> invR1 = vnl_inverse(camera1.get_rotation().as_matrix()); vnl_matrix_fixed<double, 3, 3> invK1 = vnl_inverse(camera1.get_calibration().get_matrix()); vgl_point_2d<double> pp = camera1.get_calibration().principal_point(); calibrate_pure_rotate_camera_residual residual(pts1, pts2, invR1, invK1, pp); vnl_vector<double> x(4); x[0] = camera1.get_calibration().get_matrix()[0][0]; x[1] = camera1.get_rotation().as_rodrigues()[0]; x[2] = camera1.get_rotation().as_rodrigues()[1]; x[3] = camera1.get_rotation().as_rodrigues()[2]; vnl_levenberg_marquardt lmq(residual); lmq.set_f_tolerance(0.0001); bool isMinized = lmq.minimize(x); if (!isMinized) { vcl_cerr<<"Error: minimization failed.\n"; lmq.diagnose_outcome(); return false; } lmq.diagnose_outcome(); residual.setCameraMatrixRotation(x, camera2); camera2.set_camera_center(camera1.get_camera_center()); return true; } class KfromP_residual : public vnl_least_squares_function { protected: vnl_matrix<double> PSPt_normalized_; // normalized by Frobenius norms const double u_; const double v_; public: KfromP_residual(const vnl_matrix<double> & PSPt, const vgl_point_2d<double> &pp): vnl_least_squares_function(1, 9, no_gradient), PSPt_normalized_(PSPt), u_(pp.x()), v_(pp.y()) { } void f(vnl_vector<double> const &x, vnl_vector<double> &fx) { double f = x[0]; vnl_matrix<double> K(3, 3, 0); K(0, 0) = K(1, 1) = f; K(2, 2) = 1.0; K(0, 2) = u_; K(1, 2) = v_; vnl_matrix<double> KKt = K * K.transpose(); double frob = 0.0; for (int r = 0; r<3; r++) { for (int c = 0; c<3; c++) { frob += KKt(r, c) * KKt(r, c); } } KKt = KKt/sqrt(frob); int idx = 0; for (int r = 0; r<3; r++) { for (int c = 0; c<3; c++) { fx[idx] = KKt(r, c) - PSPt_normalized_(r, c); idx++; } } } }; // The original node is in matlab //ART Factorize camera matrix into intrinsic and extrinsic matrices // //[A,R,t] = art(P,fsign) factorize the projection matrix P // as P=A*[R;t] and enforce the sign of the focal lenght to be fsign. // By default fsign=1. // Author: A. Fusiello, 1999 // // fsign tells the position of the image plane wrt the focal plane. If it is // negative the image plane is behind the focal plane. bool VpglPlus::KRTfromP(const vnl_matrix_fixed<double, 3, 4> &P, vnl_matrix_fixed<double, 3, 3> & outK, vnl_matrix_fixed<double, 3, 3> & outR, vnl_vector_fixed<double, 3> & outT, double fsign) { //s = P(1:3,4); //Q = inv(P(1:3, 1:3)); //[U,B] = qr(Q); vnl_matrix<double> s = P.extract(3, 1, 0, 3); vnl_matrix<double> Q = vnl_matrix_inverse<double>(P.extract(3, 3, 0, 0)); vnl_qr<double> iqr(Q); vnl_matrix<double> U = iqr.Q(); vnl_matrix<double> B = iqr.R(); //% fix the sign of B(3,3). This can possibly change the sign of the resulting matrix, //% which is defined up to a scale factor, however. //sig = sign(B(3,3)); //B=B*sig; //s=s*sig; if (fabs(B(2, 2)) <= 0.0000001) { return false; } double sig = 1.0; if (B(2, 2) < 0.0) { sig = -1.0; } B = sig * B; s = sig * s; //% if the sign of the focal lenght is not the required one, // % change it, and change the rotation accordingly. // if fsign*B(1,1) < 0 // E= [-1 0 0 // 0 1 0 // 0 0 1]; // B = E*B; // U = U*E; // end if (fsign * B(0, 0) < 0.0) { vnl_matrix<double> E(3, 3); E.fill(0.0); E(0, 0) = -1.0; E(1, 1) = 1.0; E(2, 2) = 1.0; B = E * B; U = U * E; } //if fsign*B(2,2) < 0 // E= [1 0 0 // 0 -1 0 // 0 0 1]; // B = E*B; // U = U*E; // end if (fsign * B(1, 1) < 0.0) { vnl_matrix<double> E(3, 3); E.fill(0.0); E(0, 0) = 1.0; E(1, 1) = -1.0; E(2, 2) = 1.0; B = E * B; U = U * E; } //% if U is not a rotation, fix the sign. This can possibly change the sign // % of the resulting matrix, which is defined up to a scale factor, however. // if det(U)< 0 // U = -U; // s= - s; //end if (vnl_determinant(U) < 0) { U = - U; s = - s; } //vcl_cout<<"B is \n"<<B<<vcl_endl; // % sanity check // if (norm(Q-U*B)>1e-10) & (norm(Q+U*B)>1e-10) // error('Something wrong with the QR factorization.'); end if ((Q - U*B).array_two_norm() > 1e-10 && (Q + U*B).array_two_norm() > 1e-10) { printf("Something wrong with the QR factorization.\n"); return false; } //R = U'; //t = B*s; //A = inv(B); //A = A ./A(3,3); vnl_matrix<double> R = U.transpose(); vnl_matrix<double> t = B * s; vnl_matrix<double> A = vnl_matrix_inverse<double>(B); A /= A(2, 2); //vcl_cout<<"A is \n"<<A<<vcl_endl; // if det(R) < 0 error('R is not a rotation matrix'); end // if A(3,3) < 0 error('Wrong sign of A(3,3)'); end if (vnl_determinant(R) < 0.0) { printf("error: R is not a rotation matrix\n"); return false; } if (A(2, 2) < 0.0) { printf("error: Wrong sign of K matirx (2, 2)\n"); return false; } //% this guarantee that the result *is* a factorization of the given P, up to a scale factor //W = A*[R,t]; //if (rank([P(:), W(:)]) ~= 1 ) // error('Something wrong with the ART factorization.'); end vnl_matrix<double> Rt(3, 4); Rt.update(R, 0, 0); assert(t.rows() == 3 && t.cols() == 1); Rt.update(t, 0, 3); vnl_matrix<double> W = A *Rt; vnl_vector<double> Pvec(12); vnl_vector<double> Wvec(12); for (int i = 0; i<12; i++) { int r = i/4; int c = i%4; Pvec[i] = P(r, c); Wvec[i] = W(r, c); } Pvec = Pvec.normalize(); Wvec = Wvec.normalize(); double dif_norm = (Pvec-Wvec).two_norm(); if (dif_norm > 0.000001) { printf("Warning: Something wrong with the ART factorization. L2 norm difference is %f\n", dif_norm); vcl_cout<<"P is : \n"<<P<<vcl_endl; vcl_cout<<"KRT is : \n"<<W<<vcl_endl; return false; } // output outK = A; outK(1, 0) = outK(2, 0) = 0.0; outK(0, 1) = 0.0; outR = R; outT[0] = t(0, 0); outT[1] = t(1, 0); outT[2] = t(2, 0); return true; } bool VpglPlus::KfromP(const vnl_matrix_fixed<double, 3, 4> & P, const vgl_point_2d<double> & pp, vnl_matrix_fixed<double, 3, 3> & K) { vnl_matrix<double> Pmat = P.as_matrix(); vnl_matrix<double> Simga(4, 4, 0); Simga(0, 0) = 1.0; Simga(1, 1) = 1.0; Simga(2, 2) = 1.0; vnl_matrix<double> PSPt = Pmat * Simga * Pmat.transpose(); // choleskey decompositon as the initial guess of focal lenth vnl_cholesky chol(PSPt); vnl_matrix<double> upTri = chol.upper_triangle(); assert(upTri.rows() == 3 && upTri.cols() == 3); double fx = upTri(0, 0)/upTri(2, 2); double fy = upTri(1, 1)/upTri(2, 2); if (fx < 0 || fy < 0) { return false; } // normalization double frob = 0.0; for (int r = 0; r<3; r++) { for (int c = 0; c<3; c++) { frob += PSPt(r, c) * PSPt(r, c); } } PSPt = PSPt/sqrt(frob); // KfromP_residual residual(PSPt, pp); vnl_vector<double> x(1, 0.0); x[0] = (fx + fy)/2.0; //constant order first vnl_levenberg_marquardt lmq(residual); bool isMinized = lmq.minimize(x); if (!isMinized) { vcl_cerr<<"Error: minimization failed.\n"; vcl_cerr<<"x = "<<x<<vcl_endl; lmq.diagnose_outcome(); return false; } lmq.diagnose_outcome(); K.set_identity(); K(0, 0) = K(1, 1) = x[0]; K(0, 2) = pp.x(); K(1, 2) = pp.y(); return true; } bool VpglPlus::rectifyStereoImage(const vpgl_perspective_camera<double> & leftP, const vpgl_perspective_camera<double> & rightP, const vgl_point_2d<double> & d1, const vgl_point_2d<double> & d2, vnl_matrix_fixed<double, 3, 4> & leftProj, vnl_matrix_fixed<double, 3, 4> & rightProj, vnl_matrix_fixed<double, 3, 3> & leftTransform, vnl_matrix_fixed<double, 3, 3> & rightTransform) { // % factorise old PPM // [A1,R1,t1] = art(Po1); // [A2,R2,t2] = art(Po2); vnl_matrix<double> A1 = leftP.get_calibration().get_matrix().as_matrix(); vnl_matrix<double> R1 = leftP.get_rotation().as_matrix().as_matrix(); vnl_matrix<double> A2 = rightP.get_calibration().get_matrix().as_matrix(); vnl_matrix<double> R2 = rightP.get_rotation().as_matrix().as_matrix(); vnl_matrix<double> Po1 = leftP.get_matrix().as_matrix(); // 3 x 4 matrix vnl_matrix<double> Po2 = rightP.get_matrix().as_matrix(); // % optical centers (unchanged) // c1 = - R1'*inv(A1)*Po1(:,4); // c2 = - R2'*inv(A2)*Po2(:,4); vnl_matrix<double> c1 = - R1.transpose()*vnl_matrix_inverse<double>(A1)*Po1.extract(3, 1, 0, 3); vnl_matrix<double> c2 = - R2.transpose()*vnl_matrix_inverse<double>(A2)*Po2.extract(3, 1, 0, 3); //vcl_cout<<"c1 is "<<c1<<vcl_endl; //vcl_cout<<"c2 is "<<c2<<vcl_endl; //% new x axis (baseline, from c1 to c2) //v1 = (c2-c1); //% new y axes (orthogonal to old z and new x) //v2 = cross(R1(3,:)',v1); // % new z axes (no choice, orthogonal to baseline and y) // v3 = cross(v1,v2); vnl_vector<double> v1 = (c2 - c1).get_column(0); vnl_vector<double> v2 = vnl_cross_3d(R1.get_row(2), v1); vnl_vector<double> v3 = vnl_cross_3d(v1, v2); //% new extrinsic (translation unchanged) //R = [v1'/norm(v1) // v2'/norm(v2) // v3'/norm(v3)]; //v1 = v1.normalize(); //v2 = v2.normalize(); //v3 = v3.normalize(); //vcl_cout<<"v1 is"<<v1<<vcl_endl; //vcl_cout<<"v2 is"<<v2<<vcl_endl; //vcl_cout<<"v3 is"<<v3<<vcl_endl; v1 = v1/v1.two_norm(); v2 = v2/v2.two_norm(); v3 = v3/v3.two_norm(); vnl_matrix<double> R(3, 3); R.set_row(0, v1); R.set_row(1, v2); R.set_row(2, v3); vcl_cout<<"R is \n"<<R<<vcl_endl; //% new intrinsic (arbitrary) //An1 = A2; //An1(1,2)=0; //An2 = A2; //An2(1,2)=0; vnl_matrix<double> An1 = A2; An1(0, 1) = 0.0; vnl_matrix<double> An2 = A2; An2(0, 1) = 0.0; //% translate image centers //An1(1,3)=An1(1,3)+d1(1); //An1(2,3)=An1(2,3)+d1(2); //An2(1,3)=An2(1,3)+d2(1); //An2(2,3)=An2(2,3)+d2(2); An1(0,2) += d1.x(); An1(1,2) += d1.y(); An2(0,2) += d2.x(); An2(1,2) += d2.y(); //% new projection matrices //Pn1 = An1 * [R -R*c1 ]; //Pn2 = An2 * [R -R*c2 ]; vnl_matrix<double> tmp1(3, 4); tmp1.update(R, 0, 0); tmp1.set_column(3, (-R*c1).get_column(0)); vnl_matrix<double> Pn1 = An1 * tmp1; vnl_matrix<double> tmp2(3, 4); tmp2.update(R, 0, 0); tmp2.set_column(3, (-R*c2).get_column(0)); vnl_matrix<double> Pn2 = An2 * tmp2; //% rectifying image transformation //T1 = Pn1(1:3,1:3)* inv(Po1(1:3,1:3)); //T2 = Pn2(1:3,1:3)* inv(Po2(1:3,1:3)); vnl_matrix<double> T1 = Pn1.extract(3, 3, 0, 0) * vnl_matrix_inverse<double>(Po1.extract(3, 3, 0, 0)); vnl_matrix<double> T2 = Pn2.extract(3, 3, 0, 0) * vnl_matrix_inverse<double>(Po2.extract(3, 3, 0, 0)); vcl_cout<<"P1 is:\n "<<Pn1<<vcl_endl; vcl_cout<<"P2 is:\n "<<Pn2<<vcl_endl; vcl_cout<<"T1 is: \n"<<T1<<vcl_endl; vcl_cout<<"T2 is: \n"<<T2<<vcl_endl; // output leftProj = vnl_matrix_fixed<double, 3, 4>(Pn1); rightProj = vnl_matrix_fixed<double, 3, 4>(Pn2); // assert(T1.rows() == 3 && T1.cols() == 3); assert(T2.rows() == 3 && T2.cols() == 3); leftTransform = T1; rightTransform = T2; return true; } class DistanceNode { public: int from_node_id_; int to_node_id_; double distance_; bool operator< (const DistanceNode & node) const { return distance_ < node.distance_; } }; int VpglPlus::unique_match_number(const vpgl_perspective_camera<double> & camera, const vcl_vector<vgl_point_3d<double> > & wld_pts, const vcl_vector<vgl_point_2d<double> > & img_pts, double inlier_distance) { assert(wld_pts.size() > 0 && img_pts.size() > 0); // project to image vcl_vector<vgl_point_2d<double> > proj_pts; for (int i = 0; i<wld_pts.size(); i++) { vgl_point_2d<double> p = (vgl_point_2d<double>)camera.project(wld_pts[i]); proj_pts.push_back(p); } // distance from img_pts to proj_pts vcl_vector<DistanceNode> nodes; for (int i = 0; i<img_pts.size(); i++) { for (int j = 0; j<proj_pts.size(); j++) { double dis = vgl_distance(img_pts[i], proj_pts[j]); if (dis < inlier_distance) { DistanceNode node; node.from_node_id_ = i; node.to_node_id_ = j; node.distance_ = dis; nodes.push_back(node); } } } vcl_sort(nodes.begin(), nodes.end()); vcl_vector<bool> used_img_pts(img_pts.size(), false); vcl_vector<bool> used_proj_pts(proj_pts.size(), false); // remove edges from shortest int edge_num = 0; for (int i = 0; i<nodes.size(); i++) { int from = nodes[i].from_node_id_; int to = nodes[i].to_node_id_; // both nodes are used if (!used_img_pts[from] && !used_proj_pts[to]) { edge_num++; used_img_pts[from] = true; used_proj_pts[to] = true; } if (edge_num >= img_pts.size() || edge_num >= used_proj_pts.size()) { break; } } return edge_num; } bool VpglPlus::writeCamera(const char *fileName, const char *imageName, const vpgl_perspective_camera<double> & camera) { assert(fileName); assert(imageName); FILE *pf = fopen(fileName, "w"); if (!pf) { printf("can not create file %s\n", fileName); return false; } fprintf(pf, "%s\n", imageName); fprintf(pf, "ppx\t ppy\t focal length\t Rx\t Ry\t Rz\t Cx\t Cy\t Cz\n"); double ppx = camera.get_calibration().principal_point().x(); double ppy = camera.get_calibration().principal_point().y(); double fl = camera.get_calibration().get_matrix()[0][0]; double Rx = camera.get_rotation().as_rodrigues()[0]; double Ry = camera.get_rotation().as_rodrigues()[1]; double Rz = camera.get_rotation().as_rodrigues()[2]; double Cx = camera.get_camera_center().x(); double Cy = camera.get_camera_center().y(); double Cz = camera.get_camera_center().z(); fprintf(pf, "%f\t %f\t %f\t %f\t %f\t %f\t %f\t %f\t %f\n", ppx, ppy, fl, Rx, Ry, Rz, Cx, Cy, Cz); fclose(pf); return true; } bool VpglPlus::readCamera(const char *fileName, vcl_string & imageName, vpgl_perspective_camera<double> & camera) { assert(fileName); FILE *pf = fopen(fileName, "r"); if (!pf) { printf("can not open file %s\n", fileName); return false; } char buf[1024] = {NULL}; int num = fscanf(pf, "%s\n", buf); assert(num == 1); imageName = vcl_string(buf); for (int i = 0; i<1; i++) { char lineBuf[BUFSIZ] = {NULL}; fgets(lineBuf, sizeof(lineBuf), pf); vcl_cout<<lineBuf; } double ppx, ppy, fl, rx, ry, rz, cx, cy, cz; int ret = fscanf(pf, "%lf %lf %lf %lf %lf %lf %lf %lf %lf", &ppx, &ppy, &fl, &rx, &ry, &rz, &cx, &cy, &cz); if (ret != 9) { printf("Error: read camera parameters!\n"); return false; } vpgl_calibration_matrix<double> K(fl, vgl_point_2d<double>(ppx, ppy)); vnl_vector_fixed<double, 3> rod(rx, ry, rz); vgl_rotation_3d<double> R(rod); vgl_point_3d<double> cc(cx, cy, cz); camera.set_calibration(K); camera.set_rotation(R); camera.set_camera_center(cc); fclose(pf); return true; } bool VpglPlus::readPTZCamera(const char *fileName, vcl_string & imageName, vnl_vector_fixed<double, 3> &ptz, vgl_point_2d<double> & pp, vgl_point_3d<double> & cc, vnl_vector_fixed<double, 3> & rod) { assert(fileName); FILE *pf = fopen(fileName, "r"); if (!pf) { printf("can not open file %s\n", fileName); return false; } char buf[1024] = {NULL}; int num = fscanf(pf, "%s\n", buf); assert(num == 1); imageName = vcl_string(buf); for (int i = 0; i<1; i++) { char lineBuf[BUFSIZ] = {NULL}; fgets(lineBuf, sizeof(lineBuf), pf); vcl_cout<<lineBuf; } double ppx, ppy, pan, tilt, fl, ccx, ccy, ccz, rodx, rody, rodz; num = fscanf(pf, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &ppx, &ppy, &pan, &tilt, &fl, &ccx, &ccy, &ccz, &rodx, &rody, &rodz); assert(num == 11); pp = vgl_point_2d<double>(ppx, ppy); ptz[0] = pan; ptz[1] = tilt; ptz[2] = fl; cc = vgl_point_3d<double>(ccx, ccy, ccz); rod[0] = rodx; rod[1] = rody; rod[2] = rodz; fclose(pf); return true; } bool VpglPlus::writePTZCamera(const char *fileName, const char *imageName, const vnl_vector_fixed<double, 3> &ptz, const vgl_point_2d<double> & pp, const vgl_point_3d<double> & cc, const vnl_vector_fixed<double, 3> & rod) { FILE *pf = fopen(fileName, "w"); assert(pf); fprintf(pf, "%s\n", imageName); fprintf(pf, "ppx ppy pan tilt focal_length cc_x cc_y cc_z rod_x rod_y rod_z\n"); fprintf(pf, "%f %f\t", pp.x(), pp.y()); fprintf(pf, "%f %f %f\t", ptz[0], ptz[1], ptz[2]); fprintf(pf, "%f %f %f\t", cc.x(), cc.y(), cc.z()); fprintf(pf, "%f %f %f\n", rod[0], rod[1], rod[2]); fclose(pf); return true; }
36.419759
163
0.568982
[ "vector", "model", "3d" ]
e00f6f154757ee20381c87169fb7d20d55c5d549
6,069
cpp
C++
GameServer/Fortune_system.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/Fortune_system.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/Fortune_system.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
1
2022-01-17T09:34:39.000Z
2022-01-17T09:34:39.000Z
#include "stdhdrs.h" #include "Fortune_system.h" #include "Server.h" struct TEMP_FORTUNE { int Item_index; unsigned char Prob_type; int Skill_index; unsigned char Skill_level; int Prob; } Temp_fortune; Fortune_data::Fortune_data(int _skill_index, int _skill_level, int _prob): Skill_index(_skill_index), Skill_level(_skill_level), Prob(_prob) { } Fortune_data::~Fortune_data() { } int Fortune_data::Get_fortune_data_prob() { return Prob; } int Fortune_data::Get_fortune_data_skill_index() { return Skill_index; } int Fortune_data::Get_fortune_data_skill_level() { return Skill_level; } Fortune_head::Fortune_head(int _item_index, int _prob_type): Item_index(_item_index), Prob_type(_prob_type) { } Fortune_head::~Fortune_head() { Fortune_data_clear(); } void Fortune_head::Fortune_data_clear() { Delete_fortune_data_vec(); fd.clear(); } void Fortune_head::Delete_fortune_data_vec() { std::vector<Fortune_data*>::iterator itr; std::vector<Fortune_data*>::iterator itrEnd = fd.end(); for (itr = fd.begin(); itr != itrEnd; ++itr) { Fortune_data* p = *itr; if (p) { delete p; p = NULL; } } } std::vector<Fortune_data*> &Fortune_head::Get_Fortune_data() { return fd; } int Fortune_head::Get_item_index() { return Item_index; } int Fortune_head::Get_prob_type() { return Prob_type; } Fortune_proto_list::Fortune_proto_list() { } Fortune_proto_list::~Fortune_proto_list() { } bool Fortune_proto_list::Make_fortune_proto_list(MYSQL *dbdata) { CDBCmd cmd; cmd.Init(dbdata); CLCString sql(1024); int Head_index = 0; Fortune_head *h = NULL; Fortune_data *d = NULL; sql.Format("SELECT " "fh.a_item_idx AS item_idx, " "fh.a_prob_type AS prob_type, " "fd.a_skill_index AS skill_index, " "fd.a_skill_level AS skill_level, " "fd.a_prob AS prob " "FROM t_fortune_head AS fh, t_fortune_data AS fd " "WHERE fh.a_enable = 1 AND fh.a_item_idx = fd.a_item_idx ORDER BY fh.a_item_idx, fd.a_prob"); cmd.SetQuery(sql); if (!cmd.Open()) { GAMELOG << init("ERROR Loading Fortune list.") << end; return false; } if(cmd.m_nrecords == 0) { GAMELOG << init("NOTICE") << "No data fortune costume" << end; } else { cmd.MoveFirst(); do { memset(&Temp_fortune, 0, sizeof(Temp_fortune)); cmd.GetRec("item_idx", Temp_fortune.Item_index); cmd.GetRec("prob_type", Temp_fortune.Prob_type); cmd.GetRec("skill_index", Temp_fortune.Skill_index); cmd.GetRec("skill_level", Temp_fortune.Skill_level); cmd.GetRec("prob", Temp_fortune.Prob); if (Head_index != Temp_fortune.Item_index) { Head_index = Temp_fortune.Item_index; h = new Fortune_head(Temp_fortune.Item_index, (int)Temp_fortune.Prob_type); fh.push_back(h); } d = new Fortune_data(Temp_fortune.Skill_index, (int)Temp_fortune.Skill_level, Temp_fortune.Prob); h->Get_Fortune_data().push_back(d); } while(cmd.MoveNext()); } return true; } Fortune_head *Fortune_proto_list::Get_fortune_head_proto(int Item_index) { std::vector<Fortune_head*>::iterator itr; Fortune_head *p = new Fortune_head(Item_index, 0); itr = std::find_if(fh.begin(), fh.end(), std::bind2nd(Compare_fortune_list(), p)); if (itr == fh.end()) return NULL; return *itr; } Fortune_data *Fortune_proto_list::Get_fortune_result(Fortune_head *f) { if (f == NULL) return NULL; if (f->Get_prob_type() == Fortune_head::PROB) { if(!Verify_prob(f)) return NULL; int prob = GetRandom(1, Fortune_head::Sum_of_prob); int sum = 0; Fortune_data* p = NULL; std::vector<Fortune_data*>::iterator itr; std::vector<Fortune_data*>::iterator itrEnd = f->Get_Fortune_data().end(); for (itr = f->Get_Fortune_data().begin(); itr != itrEnd; ++itr) { p = *itr; sum = sum + p->Get_fortune_data_prob(); if(prob <= sum) break; } if (itr == f->Get_Fortune_data().end()) return NULL; return p; } else if (f->Get_prob_type() == Fortune_head::RANDOM) { int pos = GetRandom(0, (f->Get_Fortune_data().size()-1)); return f->Get_Fortune_data()[pos]; } else return NULL; } bool Fortune_proto_list::Verify_prob(Fortune_head *f) { int verify_prob = 0; unsigned int size = f->Get_Fortune_data().size(); for (unsigned int i = 0; i < size; ++i) verify_prob = verify_prob + f->Get_Fortune_data()[i]->Get_fortune_data_prob(); if (verify_prob != Fortune_head::Sum_of_prob) return false; return true; } int Fortune_proto_list::Make_fortune(CItem *p) { if (p == NULL || p->m_itemProto == NULL) return Fortune_proto_list::NULL_ITEM; if ( !(p->m_itemProto->getItemTypeIdx() == ITYPE_WEAR && p->m_itemProto->getItemSubTypeIdx() == IWEAR_SUIT) ) return Fortune_proto_list::WRONG_TYPE; if (p->Aleady_got_fortune()) return Fortune_proto_list::ALREADY_GOT_FORTUNE; Fortune_head *f = Get_fortune_head_proto(p->m_itemProto->getItemIndex()); if (f == NULL) return Fortune_proto_list::FORTUNE_HEAD_NULL; Fortune_data *d = Get_fortune_result(f); if (d == NULL) return Fortune_proto_list::FORTUNE_DATA_NULL; p->setPlus(Make_skill_index_level_bit_sum(d)); return Fortune_proto_list::SUCCESS; } int Fortune_proto_list::Make_skill_index_level_bit_sum(Fortune_data *d) { if (d == NULL) return 0; int skill_index = 0, skill_level = 0; skill_index = d->Get_fortune_data_skill_index(); skill_level = d->Get_fortune_data_skill_level(); /** * 두 수를 하나의 변수에 담는다. */ return Make(skill_index, skill_level); } /** * skill_index는 plus의 상위 2Byte, skill_level은 plus의 하위 2Byte를 사용한다. */ int Fortune_proto_list::Make(int skill_index, int skill_level) { int plus = 0; plus = plus | skill_index; plus = plus << 16; plus = plus | skill_level; return plus; } /** * 상위 2Byte를 꺼내어 skill_index에 대입하고, 하위 2Byte는 skill_level에 대입한다. */ void Fortune_proto_list::Resolve_fortune_value(int &skill_index, int &skill_level, int bit_sum_value) { skill_index = 0; skill_level = 0; skill_level = skill_level | bit_sum_value; skill_level = skill_level & 0x0000FFFF; bit_sum_value = bit_sum_value >> 16; skill_index = skill_index | bit_sum_value; }
21.072917
101
0.706212
[ "vector" ]
e0112407eaf94e47bf36fe032f75cfbe3d8f9b2f
3,853
cpp
C++
src/core/integrator/euler.cpp
iit-DLSLab/crocoddyl
2b8b731fae036916ff9b4ce3969e2c96c009593c
[ "BSD-3-Clause" ]
null
null
null
src/core/integrator/euler.cpp
iit-DLSLab/crocoddyl
2b8b731fae036916ff9b4ce3969e2c96c009593c
[ "BSD-3-Clause" ]
null
null
null
src/core/integrator/euler.cpp
iit-DLSLab/crocoddyl
2b8b731fae036916ff9b4ce3969e2c96c009593c
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2018-2019, LAAS-CNRS // Copyright note valid unless otherwise stated in individual files. // All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include "crocoddyl/core/integrator/euler.hpp" namespace crocoddyl { IntegratedActionModelEuler::IntegratedActionModelEuler(DifferentialActionModelAbstract* const model, const double& time_step, const bool& with_cost_residual) : ActionModelAbstract(model->get_state(), model->get_nu(), model->get_nr()), differential_(model), time_step_(time_step), time_step2_(time_step * time_step), with_cost_residual_(with_cost_residual) {} IntegratedActionModelEuler::~IntegratedActionModelEuler() {} void IntegratedActionModelEuler::calc(const boost::shared_ptr<ActionDataAbstract>& data, const Eigen::Ref<const Eigen::VectorXd>& x, const Eigen::Ref<const Eigen::VectorXd>& u) { assert(x.size() == state_.get_nx() && "x has wrong dimension"); assert(u.size() == nu_ && "u has wrong dimension"); // Static casting the data boost::shared_ptr<IntegratedActionDataEuler> d = boost::static_pointer_cast<IntegratedActionDataEuler>(data); // Computing the acceleration and cost differential_->calc(d->differential, x, u); // Computing the next state (discrete time) const Eigen::VectorXd& v = x.tail(differential_->get_state().get_nv()); const Eigen::VectorXd& a = d->differential->xout; d->dx << v * time_step_ + a * time_step2_, a * time_step_; differential_->get_state().integrate(x, d->dx, d->xnext); // Updating the cost value if (with_cost_residual_) { d->r = d->differential->r; } d->cost = d->differential->cost; } void IntegratedActionModelEuler::calcDiff(const boost::shared_ptr<ActionDataAbstract>& data, const Eigen::Ref<const Eigen::VectorXd>& x, const Eigen::Ref<const Eigen::VectorXd>& u, const bool& recalc) { assert(x.size() == state_.get_nx() && "x has wrong dimension"); assert(u.size() == nu_ && "u has wrong dimension"); const unsigned int& nv = differential_->get_state().get_nv(); if (recalc) { calc(data, x, u); } // Static casting the data boost::shared_ptr<IntegratedActionDataEuler> d = boost::static_pointer_cast<IntegratedActionDataEuler>(data); // Computing the derivatives for the time-continuous model (i.e. differential model) differential_->calcDiff(d->differential, x, u, false); differential_->get_state().Jintegrate(x, d->dx, d->dxnext_dx, d->dxnext_ddx); const Eigen::MatrixXd& da_dx = d->differential->Fx; const Eigen::MatrixXd& da_du = d->differential->Fu; d->ddx_dx << da_dx * time_step_, da_dx; d->ddx_du << da_du * time_step_, da_du; for (unsigned int i = 0; i < nv; ++i) { d->ddx_dx(i, i + nv) += 1.; } d->Fx = d->dxnext_dx + time_step_ * d->dxnext_ddx * d->ddx_dx; d->Fu = time_step_ * d->dxnext_ddx * d->ddx_du; d->Lx = d->differential->get_Lx(); d->Lu = d->differential->get_Lu(); d->Lxx = d->differential->get_Lxx(); d->Lxu = d->differential->get_Lxu(); d->Luu = d->differential->get_Luu(); } boost::shared_ptr<ActionDataAbstract> IntegratedActionModelEuler::createData() { return boost::make_shared<IntegratedActionDataEuler>(this); } DifferentialActionModelAbstract* IntegratedActionModelEuler::get_differential() const { return differential_; } const double& IntegratedActionModelEuler::get_dt() const { return time_step_; } void IntegratedActionModelEuler::set_dt(double dt) { time_step_ = dt; time_step2_ = dt * dt; } } // namespace crocoddyl
40.135417
111
0.644952
[ "model" ]
e01249deeebe1ad4d556de80e5af372ab57ac944
560
hpp
C++
include/mt_random.hpp
sovrasov/linear_sde_solver
50a7248d9472889523e59c26b1c6448b8ce220da
[ "MIT" ]
null
null
null
include/mt_random.hpp
sovrasov/linear_sde_solver
50a7248d9472889523e59c26b1c6448b8ce220da
[ "MIT" ]
null
null
null
include/mt_random.hpp
sovrasov/linear_sde_solver
50a7248d9472889523e59c26b1c6448b8ce220da
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <memory> extern "C" { #include <dc.h> } class MTRandom { protected: mt_struct *mGenerator = nullptr; public: MTRandom(int idx, size_t seed_group, size_t seed); ~MTRandom(); double gen_uniform(double lb=0., double ub=1.); double gen_normal(double mu=0., double sigma=1.); }; std::vector<std::unique_ptr<MTRandom>> MT2203Factory(size_t num_engines, size_t group_seed, std::vector<size_t> seeds = {});
22.4
85
0.576786
[ "vector" ]
e0128c177e56a693e30ecf0c60f5b9002e0803e9
5,714
cpp
C++
DDrawCompat/v0.2.1/CompatGdiDcCache.cpp
SamSoneyC/dxwrapper
12bad2da2d453239119039c4ebb76665e09cffcd
[ "Zlib" ]
634
2017-02-09T01:32:58.000Z
2022-03-26T18:14:28.000Z
DDrawCompat/v0.2.1/CompatGdiDcCache.cpp
Almamu/dxwrapper
71a6bfe57404e77a7f66913be850e5048260c416
[ "Zlib" ]
128
2017-03-02T13:30:12.000Z
2022-03-11T07:08:24.000Z
DDrawCompat/v0.2.1/CompatGdiDcCache.cpp
Almamu/dxwrapper
71a6bfe57404e77a7f66913be850e5048260c416
[ "Zlib" ]
58
2017-05-16T14:42:35.000Z
2022-02-21T20:32:02.000Z
#include <cstring> #include <vector> #include "CompatDirectDraw.h" #include "CompatDirectDrawPalette.h" #include "CompatDirectDrawSurface.h" #include "CompatGdiDcCache.h" #include "CompatPrimarySurface.h" #include "Config.h" #include "DDrawCompat\DDrawLog.h" #include "DDrawProcs.h" #include "DDrawRepository.h" namespace Compat21 { namespace { using CompatGdiDcCache::CachedDc; std::vector<CachedDc> g_cache; DWORD g_cacheSize = 0; DWORD g_cacheId = 0; DWORD g_maxUsedCacheSize = 0; DWORD g_ddLockThreadId = 0; IDirectDraw7* g_directDraw = nullptr; IDirectDrawPalette* g_palette = nullptr; PALETTEENTRY g_paletteEntries[256] = {}; void* g_surfaceMemory = nullptr; LONG g_pitch = 0; IDirectDrawSurface7* createGdiSurface(); CachedDc createCachedDc() { CachedDc cachedDc = {}; IDirectDrawSurface7* surface = createGdiSurface(); if (!surface) { return cachedDc; } HDC dc = nullptr; HRESULT result = surface->lpVtbl->GetDC(surface, &dc); if (FAILED(result)) { LOG_ONCE("Failed to create a GDI DC: " << result); surface->lpVtbl->Release(surface); return cachedDc; } // Release DD critical section acquired by IDirectDrawSurface7::GetDC to avoid deadlocks Compat::origProcs.ReleaseDDThreadLock(); cachedDc.surface = surface; cachedDc.dc = dc; cachedDc.cacheId = g_cacheId; return cachedDc; } IDirectDrawSurface7* createGdiSurface() { DDSURFACEDESC2 desc = {}; desc.dwSize = sizeof(desc); desc.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | DDSD_CAPS | DDSD_PITCH | DDSD_LPSURFACE; desc.dwWidth = CompatPrimarySurface::width; desc.dwHeight = CompatPrimarySurface::height; desc.ddpfPixelFormat = CompatPrimarySurface::pixelFormat; desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY; desc.lPitch = g_pitch; desc.lpSurface = g_surfaceMemory; IDirectDrawSurface7* surface = nullptr; HRESULT result = CompatDirectDraw<IDirectDraw7>::s_origVtable.CreateSurface( g_directDraw, &desc, &surface, nullptr); if (FAILED(result)) { LOG_ONCE("Failed to create a GDI surface: " << result); return nullptr; } if (CompatPrimarySurface::pixelFormat.dwRGBBitCount <= 8) { CompatDirectDrawSurface<IDirectDrawSurface7>::s_origVtable.SetPalette(surface, g_palette); } return surface; } void extendCache() { if (g_cacheSize >= Config::preallocatedGdiDcCount) { LOG_ONCE("Warning: Preallocated GDI DC count is insufficient. This may lead to graphical issues."); } if (GetCurrentThreadId() != g_ddLockThreadId) { return; } for (DWORD i = 0; i < Config::preallocatedGdiDcCount; ++i) { CachedDc cachedDc = createCachedDc(); if (!cachedDc.dc) { return; } g_cache.push_back(cachedDc); ++g_cacheSize; } } void releaseCachedDc(CachedDc cachedDc) { // Reacquire DD critical section that was temporarily released after IDirectDrawSurface7::GetDC Compat::origProcs.AcquireDDThreadLock(); HRESULT result = CompatDirectDrawSurface<IDirectDrawSurface7>::s_origVtable.ReleaseDC( cachedDc.surface, cachedDc.dc); if (FAILED(result)) { LOG_ONCE("Failed to release a cached DC: " << result); } CompatDirectDrawSurface<IDirectDrawSurface7>::s_origVtable.Release(cachedDc.surface); } } namespace CompatGdiDcCache { void clear() { for (auto& cachedDc : g_cache) { releaseCachedDc(cachedDc); } g_cache.clear(); g_cacheSize = 0; ++g_cacheId; } CachedDc getDc() { CachedDc cachedDc = {}; if (!g_surfaceMemory) { return cachedDc; } if (g_cache.empty()) { extendCache(); } if (!g_cache.empty()) { cachedDc = g_cache.back(); g_cache.pop_back(); const DWORD usedCacheSize = g_cacheSize - g_cache.size(); if (usedCacheSize > g_maxUsedCacheSize) { g_maxUsedCacheSize = usedCacheSize; Compat::Log() << "GDI used DC cache size: " << g_maxUsedCacheSize; } } return cachedDc; } bool init() { g_directDraw = DDrawRepository::getDirectDraw(); if (g_directDraw) { CompatDirectDraw<IDirectDraw7>::s_origVtable.CreatePalette( g_directDraw, DDPCAPS_8BIT | DDPCAPS_ALLOW256, g_paletteEntries, &g_palette, nullptr); } return nullptr != g_directDraw; } void releaseDc(const CachedDc& cachedDc) { if (cachedDc.cacheId == g_cacheId) { g_cache.push_back(cachedDc); } else { releaseCachedDc(cachedDc); } } void setDdLockThreadId(DWORD ddLockThreadId) { g_ddLockThreadId = ddLockThreadId; } void setSurfaceMemory(void* surfaceMemory, LONG pitch) { if (g_surfaceMemory == surfaceMemory && g_pitch == pitch) { return; } g_surfaceMemory = surfaceMemory; g_pitch = pitch; clear(); } void updatePalette(DWORD startingEntry, DWORD count) { PALETTEENTRY entries[256] = {}; std::memcpy(&entries[startingEntry], &CompatPrimarySurface::paletteEntries[startingEntry], count * sizeof(PALETTEENTRY)); for (DWORD i = startingEntry; i < startingEntry + count; ++i) { if (entries[i].peFlags & PC_RESERVED) { entries[i] = CompatPrimarySurface::paletteEntries[0]; entries[i].peFlags = CompatPrimarySurface::paletteEntries[i].peFlags; } } if (0 != std::memcmp(&g_paletteEntries[startingEntry], &entries[startingEntry], count * sizeof(PALETTEENTRY))) { std::memcpy(&g_paletteEntries[startingEntry], &entries[startingEntry], count * sizeof(PALETTEENTRY)); CompatDirectDrawPalette::s_origVtable.SetEntries( g_palette, 0, startingEntry, count, g_paletteEntries); clear(); } } } }
23.709544
104
0.688309
[ "vector" ]
e012b2779356f9d8f2898f3244a4bb96e9dbcfa3
2,077
cpp
C++
magnum/engine/src/Renderer.cpp
world-of-legends/Alpha_Engine
9457228a635e4370127e9bcc66a0592ad5805e70
[ "Apache-2.0" ]
5
2021-02-01T15:47:28.000Z
2021-02-03T13:41:44.000Z
magnum/engine/src/Renderer.cpp
wings-studio/Alpha_Engine
9457228a635e4370127e9bcc66a0592ad5805e70
[ "Apache-2.0" ]
null
null
null
magnum/engine/src/Renderer.cpp
wings-studio/Alpha_Engine
9457228a635e4370127e9bcc66a0592ad5805e70
[ "Apache-2.0" ]
1
2021-02-03T14:29:28.000Z
2021-02-03T14:29:28.000Z
#include "Renderer.h" Renderer::Renderer() { _cameraObject.setParent(&_scene); (*(_camera = new SceneGraph::Camera3D{ _cameraObject })) .setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 1.0f, 0.01f, 1000.0f)) .setViewport(GL::defaultFramebuffer.viewport().size()); GL::Renderer::enable(GL::Renderer::Feature::DepthTest); GL::Renderer::enable(GL::Renderer::Feature::FaceCulling); _coloredShader .setAmbientColor(0x111111_rgbf) .setSpecularColor(0xffffff_rgbf) .setShininess(80.0f); _texturedShader .setAmbientColor(0x111111_rgbf) .setSpecularColor(0x111111_rgbf) .setShininess(80.0f); PluginManager::Manager<Trade::AbstractImporter> manager; Containers::Pointer<Trade::AbstractImporter> importer = manager.loadAndInstantiate("AnySceneImporter"); if (!importer) std::exit(1); } void Renderer::addCube() { GL::Mesh _mesh = MeshTools::compile(Primitives::cubeSolid()); new ColoredDrawable(_cameraObject, Shaders::Phong(), _mesh, Color4(), drawables); } void ColoredDrawable::draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) { _shader .setDiffuseColor(_color) .setLightPositions({ {camera.cameraMatrix().transformPoint({-3.0f, 10.0f, 10.0f}), 0.0f} }) .setTransformationMatrix(transformationMatrix) .setNormalMatrix(transformationMatrix.normalMatrix()) .setProjectionMatrix(camera.projectionMatrix()) .draw(_mesh); } void TexturedDrawable::draw(const Matrix4& transformationMatrix, SceneGraph::Camera3D& camera) { _shader .setLightPositions({ {camera.cameraMatrix().transformPoint({-3.0f, 10.0f, 10.0f}), 0.0f} }) .setTransformationMatrix(transformationMatrix) .setNormalMatrix(transformationMatrix.normalMatrix()) .setProjectionMatrix(camera.projectionMatrix()) .bindDiffuseTexture(_texture) .draw(_mesh); }
35.810345
107
0.689937
[ "mesh" ]
e02d0f33004934c3b6154ff53537cce528188471
429
cpp
C++
tests/timer.cpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
2
2021-06-19T08:21:38.000Z
2021-08-15T21:37:30.000Z
tests/timer.cpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
null
null
null
tests/timer.cpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
1
2021-04-03T14:27:39.000Z
2021-04-03T14:27:39.000Z
#include <Btk/object.hpp> #include <iostream> #include <thread> using Btk::Timer; int main(){ Timer timer; timer.set_interval(100); timer.set_callback([&timer](){ std::cout << "Timeout interval:" << timer.interval() << std::endl; }).start(); std::this_thread::sleep_for(std::chrono::seconds(1)); timer.set_interval(10); std::this_thread::sleep_for(std::chrono::seconds(1)); timer.stop(); }
28.6
74
0.638695
[ "object" ]
e033954a99dea1c5c59812838d0091196cc422f2
4,175
cpp
C++
src/Util/Loader/XML/XMLParser.cpp
ounols/CSEngine
beebdede6eb223c1ec3ec533ed0eb03b80f68a3b
[ "BSD-2-Clause" ]
37
2021-05-19T12:23:57.000Z
2022-03-21T23:51:30.000Z
src/Util/Loader/XML/XMLParser.cpp
ounols/CSEngine
beebdede6eb223c1ec3ec533ed0eb03b80f68a3b
[ "BSD-2-Clause" ]
3
2021-10-12T11:12:52.000Z
2021-11-28T16:11:19.000Z
src/Util/Loader/XML/XMLParser.cpp
ounols/CSEngine
beebdede6eb223c1ec3ec533ed0eb03b80f68a3b
[ "BSD-2-Clause" ]
4
2021-09-16T15:17:42.000Z
2021-10-02T21:29:38.000Z
#include "XMLParser.h" #include <string> #include "../../MoreComponentFunc.h" #include "../../../Manager/GameObjectMgr.h" using namespace CSE; void XMLParser::parse(std::vector<std::string> values, void* dst, SType type) { if (type == SType::STRING) dst = (void*)values[0].c_str(); else if (type == SType::BOOL) *static_cast<bool*>(dst) = parseBool(values[0].c_str()); else if (type == SType::FLOAT) *static_cast<float*>(dst) = parseFloat(values[0].c_str()); else if (type == SType::INT) *static_cast<int*>(dst) = parseInt(values[0].c_str()); // else if(type == "arr") dst = (void*)parseInt(values[0].c_str()); else if (type == SType::RESOURCE) dst = (void*)parseResources<SResource>(values[0].c_str()); else if (type == SType::TEXTURE) dst = (void*)parseTexture(values[0].c_str()); else if (type == SType::MATERIAL) dst = (void*)parseMaterial(values[0].c_str()); else if (type == SType::COMPONENT) dst = (void*)parseComponent(values[0].c_str()); else if (type == SType::GAME_OBJECT) dst = (void*)parseGameObject(values[0].c_str()); else if (type == SType::VEC2) *static_cast<vec2*>(dst) = parseVec2(values); else if (type == SType::VEC3) *static_cast<vec3*>(dst) = parseVec3(values); else if (type == SType::VEC4) *static_cast<vec4*>(dst) = parseVec4(values); // else if (type == SType::MAT2) *static_cast<mat2*>(dst) = parseMat2(values); // else if (type == SType::MAT3) *static_cast<mat3*>(dst) = parseMat3(values); // else if (type == SType::MAT4) *static_cast<mat4*>(dst) = parseMat4(values); } int XMLParser::parseInt(const char* value) { return std::stoi(value); } float XMLParser::parseFloat(const char* value) { return std::stof(value); } bool XMLParser::parseBool(const char* value) { return strncmp(value, "t", 1); } vec2 XMLParser::parseVec2(std::vector<std::string> values) { return {std::stof(values[0]), std::stof(values[1])}; } vec3 XMLParser::parseVec3(std::vector<std::string> values) { return {std::stof(values[0]), std::stof(values[1]), std::stof(values[2])}; } vec4 XMLParser::parseVec4(std::vector<std::string> values) { return {std::stof(values[0]), std::stof(values[1]), std::stof(values[2]), std::stof(values[3])}; } STexture* XMLParser::parseTexture(const char* value) { return SResource::Create<STexture>(value); } SMaterial* XMLParser::parseMaterial(const char* value) { return SResource::Create<SMaterial>(value); } SComponent* XMLParser::parseComponent(const char* value) { SComponent* comp = CORE->GetCore(GameObjectMgr)->FindComponentByID(value); return comp; } SGameObject* XMLParser::parseGameObject(const char* value) { SGameObject* obj = CORE->GetCore(GameObjectMgr)->FindByID(ConvertSpaceStr(value, true)); return obj; } SType XMLParser::GetType(std::string type) { if (type == "str") return SType::STRING; if (type == "bool") return SType::BOOL; if (type == "float") return SType::FLOAT; if (type == "int") return SType::INT; // if(type == "arr") dst = (void*)parseInt(values[0].c_str()); if (type == "res") return SType::RESOURCE; if (type == "tex") return SType::TEXTURE; if (type == "mat") return SType::MATERIAL; if (type == "comp") return SType::COMPONENT; if (type == "gobj") return SType::GAME_OBJECT; if (type == "vec2") return SType::VEC2; if (type == "vec3") return SType::VEC3; if (type == "vec4") return SType::VEC4; if (type == "mat2") return SType::MAT2; if (type == "mat3") return SType::MAT3; if (type == "mat4") return SType::MAT4; return SType::UNKNOWN; } SType XMLParser::GetType(unsigned int type) { if (type == GL_BOOL) return SType::BOOL; if (type == GL_FLOAT) return SType::FLOAT; if (type == GL_INT) return SType::INT; // if(type == "arr") dst = (void*)parseInt(values[0].c_str()); if (type == GL_SAMPLER_2D) return SType::TEXTURE; if (type == GL_FLOAT_VEC2) return SType::VEC2; if (type == GL_FLOAT_VEC3) return SType::VEC3; if (type == GL_FLOAT_VEC4) return SType::VEC4; if (type == GL_FLOAT_MAT2) return SType::MAT2; if (type == GL_FLOAT_MAT3) return SType::MAT3; if (type == GL_FLOAT_MAT4) return SType::MAT4; return SType::UNKNOWN; }
35.381356
97
0.660359
[ "vector" ]
e03547f0824d30745706abe170c5cbfef14bc3e9
64,030
cxx
C++
com/oleutest/accctrl/client/oactestc.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/oleutest/accctrl/client/oactestc.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/oleutest/accctrl/client/oactestc.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**************************************************************************** File: actestc.cxx Description: Client side of the DCOM IAccessControl test program. ****************************************************************************/ #include <windows.h> #include <ole2.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <accctrl.h> #include "oactest.h" #include <oleext.h> #include <rpcdce.h> /* Internal program parameters */ #define BIG_BUFFER 2048 #define LINE_BUFF_SIZE 200 #define MAX_TOKENS_NUM 20 #define STR_LEN 100 // Define some bogus access masks so that we can verify the // the validation mechanism of DCOM IAccessControl #define BOGUS_ACCESS_RIGHT1 (COM_RIGHTS_EXECUTE*2) #define BOGUS_ACCESS_RIGHT2 (COM_RIGHTS_EXECUTE*4) #define BOGUS_ACCESS_RIGHT3 (COM_RIGHTS_EXECUTE*8) #define BOGUS_ACCESS_RIGHT4 (COM_RIGHTS_EXECUTE*16) // The following structure encapsulates all kinds of information that // can be associated with a trustee. typedef struct tagTRUSTEE_RECORD { DWORD grfAccessPermissions; ACCESS_MODE grfAccessMode; DWORD grfInheritance; PTRUSTEE_W pMultipleTrustee; MULTIPLE_TRUSTEE_OPERATION MultipleTrusteeOperation; TRUSTEE_FORM TrusteeForm; TRUSTEE_TYPE TrusteeType; LPWSTR pwszTrusteeName; PISID pSID; } TRUSTEE_RECORD; /* Global variables */ char pszUserName[STR_LEN]; // User Name char pszBasePath[STR_LEN]; char pszResource[STR_LEN]; // Resource location EXPLICIT_ACCESS_W g_pLocalExplicitAccessList[100]; ULONG g_ulNumOfLocalExplicitAccesses = 0; ACCESS_REQUEST_W g_pLocalAccessRequestList[100]; ULONG g_ulNumOfLocalAccessRequests = 0; PEXPLICIT_ACCESS_W g_pReturnedExplicitAccessList = NULL; ULONG g_ulNumOfExplicitAccessesReturned = 0; TRUSTEE_W g_pLocalTrusteeList[100]; ULONG g_ulNumOfLocalTrustees = 0; TRUSTEE_RECORD g_LocalTrusteeRecord; IAccessControlTest *g_pIAccessControlTest; IUnknown *g_pIUnknown; const CLSID CLSID_COAccessControlTest = {0x20692b00,0xe710,0x11cf,{0xaf,0x0b,0x00,0xaa,0x00,0x44,0xfb,0x89}}; /* Internal function prototyoes */ void Tokenize(char *, char *[], short *); void stringtolower(char *); PISID GetSIDForTrustee(LPWSTR); void AddTrusteeToExplicitAccessList(TRUSTEE_RECORD *, PEXPLICIT_ACCESS_W, ULONG *); void DeleteTrusteeFromExplicitAccessList(ULONG, PEXPLICIT_ACCESS_W, ULONG *); void AddTrusteeToAccessRequestList(TRUSTEE_RECORD *, PACCESS_REQUEST_W, ULONG *); void DeleteTrusteeFromAccessRequestList(ULONG, PACCESS_REQUEST_W, ULONG *); void MapTrusteeRecordToTrustee(TRUSTEE_RECORD *, TRUSTEE_W *); void AddTrusteeToTrusteeList(TRUSTEE_RECORD *, TRUSTEE_W *, ULONG *); void DeleteTrusteeFromTrusteeList(ULONG, TRUSTEE_W *, ULONG *); void DestroyAccessRequestList(PACCESS_REQUEST_W, ULONG *); void DestroyTrusteeList(TRUSTEE_W *, ULONG *); void DestroyExplicitAccessList(PEXPLICIT_ACCESS_W, ULONG *); void PrintEnvironment(void); void DumpTrusteeRecord(TRUSTEE_RECORD *); void DumpAccessRequestList(ULONG, ACCESS_REQUEST_W []); void DumpExplicitAccessList(ULONG, EXPLICIT_ACCESS_W []); void DumpAccessPermissions(DWORD); DWORD StringToAccessPermission(CHAR *); void DumpAccessMode(ACCESS_MODE); void DumpTrusteeList(ULONG, TRUSTEE_W []); void DumpTrustee(TRUSTEE_W *); void DumpMultipleTrusteeOperation(MULTIPLE_TRUSTEE_OPERATION); MULTIPLE_TRUSTEE_OPERATION StringToMultipleTrusteeOperation(CHAR *); void DumpTrusteeType(TRUSTEE_TYPE); TRUSTEE_TYPE StringToTrusteeType(CHAR *); void DumpTrusteeForm(TRUSTEE_FORM); TRUSTEE_FORM StringToTrusteeForm(CHAR *); void DumpSID(PISID); ACCESS_MODE StringToAccessMode(CHAR *); void DumpInheritance(DWORD); DWORD StringToInheritance(CHAR *); void ReleaseExplicitAccessList(ULONG, PEXPLICIT_ACCESS_W); void CopyExplicitAccessList(PEXPLICIT_ACCESS_W, PEXPLICIT_ACCESS_W, ULONG *, ULONG); void ExecTestServer(CHAR *); void ExecRevertAccessRights(void); void ExecCommitAccessRights(void); void ExecGetClassID(void); void ExecInitNewACL(void); void ExecLoadACL(CHAR *); void ExecSaveACL(CHAR *); void ExecGetSizeMax(void); void ExecIsDirty(void); void ExecGrantAccessRights(void); void ExecSetAccessRights(void); void ExecDenyAccessRights(void); void ExecReplaceAllAccessRights(void); void ExecRevokeExplicitAccessRights(void); void ExecIsAccessPermitted(void); void ExecGetEffectiveAccessRights(void); void ExecGetExplicitAccessRights(void); void ExecCleanupProc(); void Usage(char * pszProgramName) { printf("Usage: %s\n", pszProgramName); printf(" -m remote_server_name\n"); exit(1); } void stringtolower ( char *pszString ) { char c; while(c = *pszString) { if(c <= 'Z' && c >= 'A') { *pszString = c - 'A' + 'a'; } pszString++; } } // stringtolower void __cdecl main(int argc, char **argv) { RPC_STATUS status; unsigned long ulCode; WCHAR DummyChar; int i; char aLineBuff[LINE_BUFF_SIZE]; char *aTokens[MAX_TOKENS_NUM]; short iNumOfTokens; SEC_WINNT_AUTH_IDENTITY_A auth_id; UCHAR uname[STR_LEN]; UCHAR domain[STR_LEN]; UCHAR password[STR_LEN]; TRUSTEE_W DummyMultipleTrustee; ULONG ulStrLen; DWORD dwAccessPermission; BOOL biBatchMode = FALSE; HRESULT hr; OLECHAR pwszRemoteServer[1024]; DWORD dwStrLen; /* allow the user to override settings with command line switches */ for (i = 1; i < argc; i++) { if ((*argv[i] == '-') || (*argv[i] == '/')) { switch (tolower(*(argv[i]+1))) { case 'm': // remote server name dwStrLen = MultiByteToWideChar( CP_ACP , NULL , argv[++i] , -1 , pwszRemoteServer , 1024); break; case 'b': biBatchMode = TRUE; break; case 'h': case '?': default: Usage(argv[0]); } } else Usage(argv[0]); } // Initialize the testing environment aTokens[0] = aLineBuff; g_LocalTrusteeRecord.grfAccessPermissions = 0; g_LocalTrusteeRecord.grfAccessMode = GRANT_ACCESS; g_LocalTrusteeRecord.grfInheritance = NO_INHERITANCE; g_LocalTrusteeRecord.pMultipleTrustee = NULL; g_LocalTrusteeRecord.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; g_LocalTrusteeRecord.TrusteeForm = TRUSTEE_IS_NAME; g_LocalTrusteeRecord.TrusteeType = TRUSTEE_IS_USER; g_LocalTrusteeRecord.pwszTrusteeName = NULL; g_LocalTrusteeRecord.pSID = NULL; auth_id.User = uname; auth_id.Domain = domain; auth_id.Password = password; auth_id.Flags = 0x01; // ANSI // Call CoInitialize to initialize the com library hr = CoInitialize(NULL); if(FAILED(hr)) { printf("Failed to initialize the COM library."); exit(hr); } // if // Call CoInitializeSecurity hr = CoInitializeSecurity( NULL , -1 , NULL , NULL , RPC_C_AUTHN_LEVEL_CONNECT , RPC_C_IMP_LEVEL_IMPERSONATE , NULL , EOAC_NONE , NULL ); if(FAILED(hr)) { printf("Failed to initialize the COM call security layer.\n"); exit(hr); } MULTI_QI MultiQI; MultiQI.pIID = &IID_IUnknown; MultiQI.pItf = NULL; COSERVERINFO ServerInfo; ServerInfo.pwszName = pwszRemoteServer; ServerInfo.pAuthInfo = NULL; ServerInfo.dwReserved1 = 0; ServerInfo.dwReserved2 = 0; // Call CoCreateInstance to create an access control test // object hr = CoCreateInstanceEx( CLSID_COAccessControlTest , NULL , CLSCTX_REMOTE_SERVER , &ServerInfo , 1 , &MultiQI); if(FAILED(hr)) { printf("CoCreateInstance failed with exit code %x.\n", hr); exit(hr); } hr = MultiQI.hr; g_pIUnknown = (IUnknown *)MultiQI.pItf; if(FAILED(hr)) { printf("Failed to create an instance of the access control test object.\n"); exit(hr); } hr = g_pIUnknown->QueryInterface(IID_IAccessControlTest, (void **)&g_pIAccessControlTest); if(FAILED(hr)) { printf("Failed to query for the IAccessControlTest interface.\n"); exit(hr); } printf("\n"); PrintEnvironment(); printf("\n"); /* Entering the interactive command loop */ for(;;) { // Print out prompt if (!biBatchMode) { printf("Command>"); } memset(aLineBuff, 0, LINE_BUFF_SIZE); // Read input form user gets(aLineBuff); if (biBatchMode) { printf("%s\n",aLineBuff); } Tokenize(aLineBuff,aTokens,&iNumOfTokens); // Process the tokens stringtolower(aTokens[0]); // Decode and execute command // Ignore comments if (iNumOfTokens == 0) { continue; } if (*aTokens[0] == '#') { continue; } printf("\n"); if (strcmp(aTokens[0],"quit") == 0) { printf("Exit.\n"); ExecCleanupProc(); break; } else if (strcmp(aTokens[0],"exit") == 0) { printf("Exit.\n"); ExecCleanupProc(); break; } else if (strcmp(aTokens[0],"sleep") == 0) { printf("Sleep for %s milliseconds", aTokens[1]); Sleep(atoi(aTokens[1])); } else if (strcmp(aTokens[0], "testserver") == 0) { g_pIAccessControlTest->TestServer(aTokens[1]); printf("Done.\n"); } else if (strcmp(aTokens[0],"switchclientctx") == 0) { printf("User:"); gets((CHAR *)uname); printf("Domain:"); gets((CHAR *)domain); printf("Password:"); gets((CHAR *)password); auth_id.UserLength = strlen((CHAR *)uname); auth_id.DomainLength = strlen((CHAR *)domain); auth_id.PasswordLength = strlen((CHAR *)password); auth_id.Flags = 0x1; /* Set authentication info so that the server is triggered */ /* to cache group info for the client from the domain server */ hr = CoSetProxyBlanket( g_pIAccessControlTest , RPC_C_AUTHN_WINNT , RPC_C_AUTHZ_NONE , NULL , RPC_C_AUTHN_LEVEL_CONNECT , RPC_C_IMP_LEVEL_IMPERSONATE , &auth_id , EOAC_NONE ); printf("CoSetProxyBlanket returned %x\n", hr); if (FAILED(hr)) { exit(hr); } } else if (strcmp(aTokens[0],"toggleaccessperm") == 0) { stringtolower(aTokens[1]); dwAccessPermission = StringToAccessPermission(aTokens[1]); if (g_LocalTrusteeRecord.grfAccessPermissions & dwAccessPermission) { g_LocalTrusteeRecord.grfAccessPermissions &= ~dwAccessPermission; } else { g_LocalTrusteeRecord.grfAccessPermissions |= dwAccessPermission; } printf("Done.\n"); } else if (strcmp(aTokens[0],"set") == 0) { stringtolower(aTokens[1]); if (strcmp(aTokens[1],"trusteename") == 0) { // The old SID in the global trustee record will no longer valid so we // may as well release it to avoid confusion if (g_LocalTrusteeRecord.pSID != NULL) { midl_user_free(g_LocalTrusteeRecord.pSID); g_LocalTrusteeRecord.pSID = NULL; } if (g_LocalTrusteeRecord.pwszTrusteeName != NULL) { midl_user_free(g_LocalTrusteeRecord.pwszTrusteeName); } ulStrLen = MultiByteToWideChar( CP_ACP , 0 , aTokens[2] , -1 , &DummyChar , 0 ); g_LocalTrusteeRecord.pwszTrusteeName = (LPWSTR)midl_user_allocate(sizeof(WCHAR) * (ulStrLen+1)); MultiByteToWideChar( CP_ACP , 0 , aTokens[2] , ulStrLen + 1 , g_LocalTrusteeRecord.pwszTrusteeName , ulStrLen + 1); printf("Done.\n"); } else if (strcmp(aTokens[1], "accessmode") == 0) { stringtolower(aTokens[2]); g_LocalTrusteeRecord.grfAccessMode = StringToAccessMode(aTokens[2]); printf("Done.\n"); } else if (strcmp(aTokens[1], "inheritance") == 0) { stringtolower(aTokens[2]); g_LocalTrusteeRecord.grfInheritance = StringToInheritance(aTokens[2]); printf("Done.\n"); } else if (strcmp(aTokens[1], "multipletrustee") == 0) { stringtolower(aTokens[2]); if (strcmp(aTokens[2], "null") == 0) { g_LocalTrusteeRecord.pMultipleTrustee = NULL; } else { g_LocalTrusteeRecord.pMultipleTrustee = &DummyMultipleTrustee; } printf("Done.\n"); } else if (strcmp(aTokens[1], "multipletrusteeoperation") == 0) { stringtolower(aTokens[2]); g_LocalTrusteeRecord.MultipleTrusteeOperation = StringToMultipleTrusteeOperation(aTokens[2]); printf("Done.\n"); } else if (strcmp(aTokens[1], "trusteeform") == 0) { stringtolower(aTokens[2]); g_LocalTrusteeRecord.TrusteeForm = StringToTrusteeForm(aTokens[2]); printf("Done.\n"); } else if (strcmp(aTokens[1], "trusteetype") == 0) { stringtolower(aTokens[2]); g_LocalTrusteeRecord.TrusteeType = StringToTrusteeType(aTokens[2]); printf("Done.\n"); } else { printf("Invalid environment variable.\n"); } // if } else if (strcmp(aTokens[0], "getsidforcurrenttrustee") == 0) { g_LocalTrusteeRecord.pSID = GetSIDForTrustee(g_LocalTrusteeRecord.pwszTrusteeName); printf("Done.\n"); } else if (strcmp(aTokens[0], "addtrustee") == 0) { stringtolower(aTokens[1]); if (strcmp(aTokens[1], "explicitaccesslist") == 0) { AddTrusteeToExplicitAccessList(&g_LocalTrusteeRecord, g_pLocalExplicitAccessList, &g_ulNumOfLocalExplicitAccesses); printf("Done.\n"); } else if (strcmp(aTokens[1], "accessrequestlist") == 0) { AddTrusteeToAccessRequestList(&g_LocalTrusteeRecord, g_pLocalAccessRequestList, &g_ulNumOfLocalAccessRequests); printf("Done.\n"); } else if (strcmp(aTokens[1], "trusteelist") == 0) { AddTrusteeToTrusteeList(&g_LocalTrusteeRecord, g_pLocalTrusteeList, &g_ulNumOfLocalTrustees); printf("Done.\n"); } else { printf("Unknown list type.\n"); } } else if (strcmp(aTokens[0], "deletetrustee") == 0) { stringtolower(aTokens[2]); if (strcmp(aTokens[2], "localexplicitaccesslist") == 0) { DeleteTrusteeFromExplicitAccessList(atoi(aTokens[1]), g_pLocalExplicitAccessList, &g_ulNumOfLocalExplicitAccesses); printf("Done.\n"); } else if (strcmp(aTokens[2], "accessrequestlist") == 0) { DeleteTrusteeFromAccessRequestList(atoi(aTokens[1]), g_pLocalAccessRequestList, &g_ulNumOfLocalAccessRequests); printf("Done.\n"); } else if (strcmp(aTokens[2], "trusteelist") == 0) { DeleteTrusteeFromTrusteeList(atoi(aTokens[1]), g_pLocalTrusteeList, &g_ulNumOfLocalTrustees); printf("Done.\n"); } else { printf("Unknown list type.\n"); } } else if (strcmp(aTokens[0], "destroy") == 0) { stringtolower(aTokens[1]); if (strcmp(aTokens[1], "localexplicitaccesslist") == 0) { DestroyExplicitAccessList(g_pLocalExplicitAccessList, &g_ulNumOfLocalExplicitAccesses); printf("Done.\n"); } else if (strcmp(aTokens[1], "returnedexplicitaccessslist") == 0) { DestroyExplicitAccessList(g_pReturnedExplicitAccessList, &g_ulNumOfExplicitAccessesReturned); printf("Done.\n"); } else if (strcmp(aTokens[1], "accessrequestlist") == 0) { DestroyAccessRequestList(g_pLocalAccessRequestList, &g_ulNumOfLocalAccessRequests); printf("Done.\n"); } else if (strcmp(aTokens[1], "trusteelist") == 0) { DestroyTrusteeList(g_pLocalTrusteeList, &g_ulNumOfLocalTrustees); } else { printf("Unknown list type."); } } else if (strcmp(aTokens[0], "view") == 0) { stringtolower(aTokens[1]); if (strcmp(aTokens[1], "localexplicitaccesslist") == 0) { DumpExplicitAccessList(g_ulNumOfLocalExplicitAccesses, g_pLocalExplicitAccessList); printf("Done.\n"); } else if (strcmp(aTokens[1], "returnedexplicitaccessslist") == 0) { DumpExplicitAccessList(g_ulNumOfExplicitAccessesReturned, g_pReturnedExplicitAccessList); printf("Done.\n"); } else if (strcmp(aTokens[1], "accessrequestlist") == 0) { DumpAccessRequestList(g_ulNumOfLocalAccessRequests, g_pLocalAccessRequestList); printf("Done.\n"); } else if (strcmp(aTokens[1], "trusteelist") == 0) { DumpTrusteeList(g_ulNumOfLocalTrustees, g_pLocalTrusteeList); printf("Done.\n"); } else if (strcmp(aTokens[1], "trusteerecord") == 0) { DumpTrusteeRecord(&g_LocalTrusteeRecord); printf("Done.\n"); } else if (strcmp(aTokens[1], "localenvironment") == 0) { PrintEnvironment(); } else { printf("Invalid argument."); } } else if (strcmp(aTokens[0], "copyreturnedlist") == 0) { // release the old local explicit access list ReleaseExplicitAccessList(g_ulNumOfLocalExplicitAccesses, g_pLocalExplicitAccessList); // replace the local explicit acccess list with the explicit access list returned // from the last call to GetExplicitAccess CopyExplicitAccessList(g_pLocalExplicitAccessList, g_pReturnedExplicitAccessList, &g_ulNumOfLocalExplicitAccesses, g_ulNumOfExplicitAccessesReturned); printf("Done.\n"); } else if (strcmp(aTokens[0], "exec") == 0) { stringtolower(aTokens[1]); if (strcmp(aTokens[1], "testserver") == 0) { ExecTestServer(aTokens[2]); } else if (strcmp(aTokens[1], "revertaccessrights") == 0) { ExecRevertAccessRights(); } else if (strcmp(aTokens[1], "commitaccessrights") == 0) { ExecCommitAccessRights(); } else if (strcmp(aTokens[1], "getclassid") == 0) { ExecGetClassID(); } else if (strcmp(aTokens[1], "initnewacl") == 0) { ExecInitNewACL(); } else if (strcmp(aTokens[1], "loadacl") == 0) { ExecLoadACL(aTokens[2]); } else if (strcmp(aTokens[1], "saveacl") == 0) { ExecSaveACL(aTokens[2]); } else if (strcmp(aTokens[1], "isdirty") == 0) { ExecIsDirty(); } else if (strcmp(aTokens[1], "getsizemax") == 0) { ExecGetSizeMax(); } else if (strcmp(aTokens[1], "grantaccessrights") == 0) { ExecGrantAccessRights(); } else if (strcmp(aTokens[1], "setaccessrights") == 0) { ExecSetAccessRights(); } else if (strcmp(aTokens[1], "denyaccessrights") == 0) { ExecDenyAccessRights(); } else if (strcmp(aTokens[1], "replaceallaccessrights") == 0) { ExecReplaceAllAccessRights(); } else if (strcmp(aTokens[1], "revokeexplicitaccessrights") == 0) { ExecRevokeExplicitAccessRights(); } else if (strcmp(aTokens[1], "isaccesspermitted") == 0) { ExecIsAccessPermitted(); } else if (strcmp(aTokens[1], "geteffectiveaccessrights") == 0) { ExecGetEffectiveAccessRights(); } else if (strcmp(aTokens[1], "getexplicitaccessrights") == 0) { ExecGetExplicitAccessRights(); } else { printf("Unknown command.\n"); } } else { printf("Unrecognized command.\n"); } // if printf("\n"); } // for exit(0); } // end main() PISID GetSIDForTrustee ( LPWSTR pwszTrusteeName ) { PISID pSID; DWORD dwSize = 0; WCHAR pwszDomain[100]; DWORD dwDomainSize = 100; SID_NAME_USE SIDUse; LookupAccountNameW( NULL , pwszTrusteeName , pSID , &dwSize , pwszDomain , &dwDomainSize , &SIDUse ); pSID = (PISID)midl_user_allocate(dwSize); LookupAccountNameW( NULL , pwszTrusteeName , pSID , &dwSize , pwszDomain , &dwDomainSize , &SIDUse ); return pSID; } void AddTrusteeToExplicitAccessList ( TRUSTEE_RECORD *pTrusteeRecord, PEXPLICIT_ACCESS_W pExplicitAccessList, ULONG *pulNumOfExplicitAccesses ) { PEXPLICIT_ACCESS_W pInsertionPoint; pInsertionPoint = pExplicitAccessList + *pulNumOfExplicitAccesses; pInsertionPoint->grfAccessPermissions = pTrusteeRecord->grfAccessPermissions; pInsertionPoint->grfAccessMode = pTrusteeRecord->grfAccessMode; pInsertionPoint->grfInheritance = pTrusteeRecord->grfInheritance; MapTrusteeRecordToTrustee(pTrusteeRecord, &(pInsertionPoint->Trustee)); (*pulNumOfExplicitAccesses)++; } void DeleteTrusteeFromExplicitAccessList ( ULONG ulIndex, PEXPLICIT_ACCESS_W pExplicitAccessList, ULONG *pulNumOfExplicitAccesses ) { PEXPLICIT_ACCESS_W pDeletionPoint; if(ulIndex >= *pulNumOfExplicitAccesses) { return; } pDeletionPoint = pExplicitAccessList + ulIndex; midl_user_free(pDeletionPoint->Trustee.ptstrName); (*pulNumOfExplicitAccesses)--; memmove(pDeletionPoint, pDeletionPoint + 1, sizeof(EXPLICIT_ACCESS_W) * (*pulNumOfExplicitAccesses - ulIndex)); } void AddTrusteeToAccessRequestList ( TRUSTEE_RECORD *pTrusteeRecord, PACCESS_REQUEST_W pAccessRequestList, ULONG *pulNumOfAccessRequests ) { PACCESS_REQUEST_W pInsertionPoint; pInsertionPoint = pAccessRequestList + *pulNumOfAccessRequests; pInsertionPoint->grfAccessPermissions = pTrusteeRecord->grfAccessPermissions; MapTrusteeRecordToTrustee(pTrusteeRecord, &(pInsertionPoint->Trustee)); (*pulNumOfAccessRequests)++; } void DeleteTrusteeFromAccessRequestList ( ULONG ulIndex, PACCESS_REQUEST_W pAccessRequestList, ULONG *pulNumOfAccessRequests ) { PACCESS_REQUEST_W pDeletionPoint; pDeletionPoint = pAccessRequestList + ulIndex; if (ulIndex >= *pulNumOfAccessRequests) { return; } midl_user_free(pDeletionPoint->Trustee.ptstrName); (*pulNumOfAccessRequests)--; memmove(pDeletionPoint, pDeletionPoint + 1, sizeof(ACCESS_REQUEST_W) * (*pulNumOfAccessRequests - ulIndex)); } void MapTrusteeRecordToTrustee ( TRUSTEE_RECORD *pTrusteeRecord, TRUSTEE_W *pTrustee ) { ULONG ulTrusteeNameLength; pTrustee->pMultipleTrustee = pTrusteeRecord->pMultipleTrustee; pTrustee->MultipleTrusteeOperation = pTrusteeRecord->MultipleTrusteeOperation; pTrustee->TrusteeForm = pTrusteeRecord->TrusteeForm; pTrustee->TrusteeType = pTrusteeRecord->TrusteeType; switch(pTrusteeRecord->TrusteeForm) { case TRUSTEE_IS_SID: if(pTrusteeRecord->pSID== NULL) { pTrustee->ptstrName = NULL; } else { ulTrusteeNameLength = GetSidLengthRequired(pTrusteeRecord->pSID->SubAuthorityCount); pTrustee->ptstrName = (LPWSTR)midl_user_allocate(ulTrusteeNameLength); CopySid(ulTrusteeNameLength, (PSID)(pTrustee->ptstrName), pTrusteeRecord->pSID); } break; case TRUSTEE_IS_NAME: if (pTrusteeRecord->pwszTrusteeName == NULL) { pTrustee->ptstrName = NULL; } else { ulTrusteeNameLength = lstrlenW(pTrusteeRecord->pwszTrusteeName); pTrustee->ptstrName = (LPWSTR)midl_user_allocate((ulTrusteeNameLength + 1) * sizeof(WCHAR)); lstrcpyW(pTrustee->ptstrName, pTrusteeRecord->pwszTrusteeName); } break; } } void AddTrusteeToTrusteeList ( TRUSTEE_RECORD *pTrusteeRecord, TRUSTEE_W *pTrusteeList, ULONG *pulNumOfTrustees ) { TRUSTEE_W *pInsertionPoint; pInsertionPoint = pTrusteeList + *pulNumOfTrustees; MapTrusteeRecordToTrustee(pTrusteeRecord, pInsertionPoint); (*pulNumOfTrustees)++; } void DeleteTrusteeFromTrusteeList ( ULONG ulIndex, TRUSTEE_W *pTrusteeList, ULONG *pulNumOfTrustees ) { TRUSTEE_W *pDeletionPoint; pDeletionPoint = pTrusteeList + ulIndex; if (ulIndex >= *pulNumOfTrustees) { return; } midl_user_free(pDeletionPoint->ptstrName); (*pulNumOfTrustees)--; memmove(pDeletionPoint, pDeletionPoint + 1, sizeof(TRUSTEE_W) * (*pulNumOfTrustees - ulIndex)); } void DestroyAccessRequestList ( PACCESS_REQUEST_W pAccessRequestList, ULONG *pulNumOfAccessRequests ) { ULONG i; PACCESS_REQUEST_W pAccessRequestListPtr; for ( i = 0, pAccessRequestListPtr = pAccessRequestList ; i < *pulNumOfAccessRequests ; i++, pAccessRequestListPtr++) { midl_user_free(pAccessRequestListPtr->Trustee.ptstrName); } *pulNumOfAccessRequests = 0; } void DestroyTrusteeList ( TRUSTEE_W *pTrusteeList, ULONG *pulNumOfTrustees ) { ULONG i; TRUSTEE_W *pTrusteeListPtr; for ( i = 0, pTrusteeListPtr = pTrusteeList ; i < *pulNumOfTrustees ; i++, pTrusteeListPtr++) { midl_user_free(pTrusteeListPtr->ptstrName); } *pulNumOfTrustees = 0; } void DestroyExplicitAccessList ( PEXPLICIT_ACCESS_W pExplicitAccessList, ULONG *pulNumOfExplicitAccesses ) { ReleaseExplicitAccessList(*pulNumOfExplicitAccesses, pExplicitAccessList); *pulNumOfExplicitAccesses = 0; } /* Function: PrintEnvironment Parameter: none Return: void Purpose: This function prints out the current setting of the client side global varibles. */ void PrintEnvironment ( void ) { printf("Local access request list:\n"); DumpAccessRequestList(g_ulNumOfLocalAccessRequests, g_pLocalAccessRequestList); printf("Local explicit access list:\n"); DumpExplicitAccessList(g_ulNumOfLocalExplicitAccesses, g_pLocalExplicitAccessList); printf("Local trustee list:\n"); DumpTrusteeList(g_ulNumOfLocalTrustees, g_pLocalTrusteeList); printf("The explicit access list returned form the last call to GetExplicitAccessRights:\n"); DumpExplicitAccessList(g_ulNumOfExplicitAccessesReturned, g_pReturnedExplicitAccessList); printf("Current trustee record:\n"); DumpTrusteeRecord(&g_LocalTrusteeRecord); } // PrintEnvironment void DumpTrusteeRecord ( TRUSTEE_RECORD *pTrusteeRecord ) { CHAR pszTrusteeName[200]; ULONG ulStrLen; printf("Access permissions:\n"); DumpAccessPermissions(pTrusteeRecord->grfAccessPermissions); printf("Access mode: "); DumpAccessMode(pTrusteeRecord->grfAccessMode); printf("Inheritance: "); DumpInheritance(pTrusteeRecord->grfInheritance); printf("pMultipleTrustree is "); if(pTrusteeRecord->pMultipleTrustee == NULL) { printf("NULL.\n"); } else { printf("non-NULL.\n"); } printf("MultipleTrusteeOperation: "); DumpMultipleTrusteeOperation(pTrusteeRecord->MultipleTrusteeOperation); printf("TrusteeForm: "); DumpTrusteeForm(pTrusteeRecord->TrusteeForm); printf("TrusteeType: "); DumpTrusteeType(pTrusteeRecord->TrusteeType); if (pTrusteeRecord->pwszTrusteeName == NULL) { strcpy(pszTrusteeName, "<NULL>"); } else { ulStrLen = WideCharToMultiByte( CP_ACP , 0 , pTrusteeRecord->pwszTrusteeName , -1 , pszTrusteeName , 200 , NULL , NULL ); } printf("Trustee's name: %s\n", pszTrusteeName); printf("Trustee's SID: \n"); DumpSID(pTrusteeRecord->pSID); printf("\n"); } void DumpAccessRequestList ( ULONG ulNumOfEntries, ACCESS_REQUEST_W pAccessRequestList[] ) { ULONG i; PACCESS_REQUEST_W pLocalAccessRequestListPtr; for (i = 0, pLocalAccessRequestListPtr = pAccessRequestList; i < ulNumOfEntries; i++, pLocalAccessRequestListPtr++) { printf("Access request #%d:\n\n", i); printf("Access permissions: "); DumpAccessPermissions(pLocalAccessRequestListPtr->grfAccessPermissions); printf("Trustee: \n"); DumpTrustee(&(pLocalAccessRequestListPtr->Trustee)); printf("\n"); } } /* Function: DumpLocalExplicitAccessList Parameters: ULONG ulNumOfEntries - Number of EXPLICIT_ACCESS structures in the array EXPLICIT_ACCESS_W pExplicitAccessList - Pointer to an array of EXPLICIT_ACCESS structures to be printed to be printed to the console. Purpose: This function prints an array of explicit access structures to the console */ void DumpExplicitAccessList ( ULONG ulNumOfEntries, EXPLICIT_ACCESS_W pExplicitAccessList[] ) { ULONG i; // Loop counter EXPLICIT_ACCESS_W *pLocalExplicitAccessListPtr; // Local pointer for stepping through the explicit access list for (pLocalExplicitAccessListPtr = pExplicitAccessList, i = 0; i < ulNumOfEntries; i++, pLocalExplicitAccessListPtr++) { printf("Entry #%d.\n\n", i); printf("Access permissions:\n"); DumpAccessPermissions(pLocalExplicitAccessListPtr->grfAccessPermissions); printf("Access mode: "); DumpAccessMode(pLocalExplicitAccessListPtr->grfAccessMode); printf("Inheritance: "); DumpInheritance(pLocalExplicitAccessListPtr->grfInheritance); printf("Trustee:\n"); DumpTrustee(&(pLocalExplicitAccessListPtr->Trustee)); printf("End Of entry #%d.\n\n", i); } // for } // DumpLocalExplicitAccessList void DumpAccessPermissions ( DWORD grfAccessPermissions ) { if(grfAccessPermissions & COM_RIGHTS_EXECUTE) { printf("COM_RIGHTS_EXECUTE\n"); } if(grfAccessPermissions & BOGUS_ACCESS_RIGHT1) { printf("BOGUS_ACCESS_RIGHT1\n"); } if(grfAccessPermissions & BOGUS_ACCESS_RIGHT2) { printf("BOGUS_ACCESS_RIGHT2\n"); } if(grfAccessPermissions & BOGUS_ACCESS_RIGHT3) { printf("BOGUS_ACCESS_RIGHT3\n"); } if(grfAccessPermissions & BOGUS_ACCESS_RIGHT4) { printf("BOGUS_ACCESS_RIGHT4\n"); } } DWORD StringToAccessPermission ( CHAR *pszString ) { if (strcmp(pszString, "com_rights_execute") == 0) { return COM_RIGHTS_EXECUTE; } if (strcmp(pszString, "bogus_access_right1") == 0) { return BOGUS_ACCESS_RIGHT1; } if (strcmp(pszString, "bogus_access_right2") == 0) { return BOGUS_ACCESS_RIGHT2; } if (strcmp(pszString, "bogus_access_right3") == 0) { return BOGUS_ACCESS_RIGHT3; } if (strcmp(pszString, "bogus_access_right4") == 0) { return BOGUS_ACCESS_RIGHT4; } return 0; } void DumpAccessMode ( ACCESS_MODE grfAccessMode ) { switch(grfAccessMode) { case NOT_USED_ACCESS: printf("NOT_USED_ACCESS\n"); break; case GRANT_ACCESS: printf("GRANT_ACCESS\n"); break; case DENY_ACCESS: printf("DENY_ACCESS\n"); break; case SET_ACCESS: printf("SET_ACCESS\n"); break; case REVOKE_ACCESS: printf("REVOKE_ACCESS\n"); break; case SET_AUDIT_SUCCESS: printf("SET_AUDIT_SUCCESS\n"); break; case SET_AUDIT_FAILURE: printf("SET_AUDIT_FAILURE\n"); break; } // switch } // DumpAccessMode void DumpTrusteeList ( ULONG ulNumOfTrustees, TRUSTEE_W pTrusteeList[] ) { ULONG i; PTRUSTEE_W pTrusteeListPtr; for( i = 0, pTrusteeListPtr = pTrusteeList ; i < ulNumOfTrustees ; i++, pTrusteeListPtr++) { printf("Trustee #%d:\n", i); DumpTrustee(pTrusteeListPtr); printf("\n"); } } void DumpTrustee ( TRUSTEE_W *pTrustee ) { char pszTrusteeName[256]; ULONG ulStrLen; printf("pMultipleTrustee is "); if(pTrustee->pMultipleTrustee == NULL) { printf("NULL.\n"); } else { printf("non-NULL.\n"); } printf("MultipleTrusteeOperation: "); DumpMultipleTrusteeOperation(pTrustee->MultipleTrusteeOperation); printf("TrusteeForm: "); DumpTrusteeForm(pTrustee->TrusteeForm); printf("TrusteeType: "); DumpTrusteeType(pTrustee->TrusteeType); switch(pTrustee->TrusteeForm) { case TRUSTEE_IS_NAME: if (pTrustee->ptstrName == NULL) { strcpy(pszTrusteeName, "<NULL>"); } else { ulStrLen = WideCharToMultiByte( CP_ACP , 0 , pTrustee->ptstrName , -1 , pszTrusteeName , 256 , NULL , NULL ); pszTrusteeName[ulStrLen] = '\0'; } printf("Trustee's name is: %s\n", pszTrusteeName); break; case TRUSTEE_IS_SID: printf("Trustee's SID is:\n"); DumpSID((PISID)(pTrustee->ptstrName)); break; } // switch } void DumpMultipleTrusteeOperation ( MULTIPLE_TRUSTEE_OPERATION MultipleTrusteeOperation ) { switch(MultipleTrusteeOperation) { case NO_MULTIPLE_TRUSTEE: printf("NO_MULTIPLE_TRUSTEE\n"); break; case TRUSTEE_IS_IMPERSONATE: printf("TRUSTEE_IS_IMPERSONATE\n"); break; } } MULTIPLE_TRUSTEE_OPERATION StringToMultipleTrusteeOperation ( CHAR *pszString ) { if(strcmp(pszString, "no_multiple_trustee") == 0) { return NO_MULTIPLE_TRUSTEE; } if(strcmp(pszString, "trustee_is_impersonate") == 0) { return TRUSTEE_IS_IMPERSONATE; } return NO_MULTIPLE_TRUSTEE; } void DumpTrusteeType ( TRUSTEE_TYPE TrusteeType ) { switch (TrusteeType) { case TRUSTEE_IS_UNKNOWN: printf("TRUSTEE_IS_UNKNOWN\n"); break; case TRUSTEE_IS_USER: printf("TRUSTEE_IS_USER\n"); break; case TRUSTEE_IS_GROUP: printf("TRSUTEE_IS_GROUP\n"); break; } } TRUSTEE_TYPE StringToTrusteeType ( CHAR *pszString ) { if(strcmp(pszString, "trustee_is_unknown") == 0) { return TRUSTEE_IS_UNKNOWN; } if(strcmp(pszString, "trustee_is_user") == 0) { return TRUSTEE_IS_USER; } if(strcmp(pszString, "trustee_is_group") == 0) { return TRUSTEE_IS_GROUP; } return TRUSTEE_IS_UNKNOWN; } void DumpTrusteeForm ( TRUSTEE_FORM TrusteeForm ) { switch (TrusteeForm) { case TRUSTEE_IS_NAME: printf("TRUSTEE_IS_NAME\n"); break; case TRUSTEE_IS_SID: printf("TRUSTEE_IS_SID\n"); break; } } TRUSTEE_FORM StringToTrusteeForm ( CHAR *pszString ) { if (strcmp(pszString, "trustee_is_name") == 0) { return TRUSTEE_IS_NAME; } if (strcmp(pszString, "trustee_is_sid") == 0) { return TRUSTEE_IS_SID; } return TRUSTEE_IS_NAME; } void DumpSID ( PISID pSID ) { ULONG i; if( pSID == NULL) { printf("<NULL>\n"); } else { printf("Revision: %d\n", pSID->Revision); printf("SubAuthorityCount: %d\n", pSID->SubAuthorityCount); printf("IdentifierAuthority: {%d,%d,%d,%d,%d,%d}\n", (pSID->IdentifierAuthority.Value)[0] , (pSID->IdentifierAuthority.Value)[1] , (pSID->IdentifierAuthority.Value)[2] , (pSID->IdentifierAuthority.Value)[3] , (pSID->IdentifierAuthority.Value)[4] , (pSID->IdentifierAuthority.Value)[5] ); printf("SubAuthorities:\n"); for (i = 0; i < pSID->SubAuthorityCount; i++) { printf("%d\n", pSID->SubAuthority[i]); } } } ACCESS_MODE StringToAccessMode ( CHAR *pszString ) { if(strcmp(pszString, "not_use_access") == 0) { return NOT_USED_ACCESS; } if(strcmp(pszString, "grant_access") == 0) { return GRANT_ACCESS; } if(strcmp(pszString, "set_access") == 0) { return SET_ACCESS; } if(strcmp(pszString, "deny_access") == 0) { return DENY_ACCESS; } if(strcmp(pszString, "revoke_access") == 0) { return REVOKE_ACCESS; } if(strcmp(pszString, "set_audit_success") == 0) { return SET_AUDIT_SUCCESS; } if(strcmp(pszString, "set_audit_failure") == 0) { return SET_AUDIT_FAILURE; } return NOT_USED_ACCESS; } void DumpInheritance ( DWORD grfInheritance ) { switch(grfInheritance) { case NO_INHERITANCE: printf("NO_INHERITANCE\n"); break; case SUB_CONTAINERS_ONLY_INHERIT: printf("SUB_CONTAINERS_ONLY_INHERIT\n"); break; case SUB_OBJECTS_ONLY_INHERIT: printf("SUB_OBJECTS_ONLY_INHERIT\n"); break; case SUB_CONTAINERS_AND_OBJECTS_INHERIT: printf("SUB_CONTAINERS_AND_OBJECTS_INHERIT\n"); break; } } DWORD StringToInheritance ( CHAR *pszString ) { if (strcmp(pszString, "no_inheritance") == 0) { return NO_INHERITANCE; } if (strcmp(pszString, "sub_containers_only_inherit") == 0) { return SUB_CONTAINERS_ONLY_INHERIT; } if (strcmp(pszString, "sub_objects_only_inherit") == 0) { return SUB_OBJECTS_ONLY_INHERIT; } if (strcmp(pszString, "sub_containers_and_objects_inherit") == 0) { return SUB_CONTAINERS_AND_OBJECTS_INHERIT; } return 0; } void ReleaseExplicitAccessList ( ULONG cCount, PEXPLICIT_ACCESS_W pExplicitAccessList ) { ULONG i; for (i = 0; i < cCount; i++) { midl_user_free(pExplicitAccessList[i].Trustee.ptstrName); } if(pExplicitAccessList != g_pLocalExplicitAccessList) { midl_user_free(pExplicitAccessList); } } void CopyExplicitAccessList ( PEXPLICIT_ACCESS_W pTarget, PEXPLICIT_ACCESS_W pSource, ULONG *pcCount, ULONG cCount ) { ULONG i; PEXPLICIT_ACCESS_W pTargetPtr; PEXPLICIT_ACCESS_W pSourcePtr; ULONG ulTrusteeNameSize; for ( i = 0, pTargetPtr = pTarget, pSourcePtr = pSource ; i < cCount ; i++, pTargetPtr++, pSourcePtr++) { memcpy(pTargetPtr, pSourcePtr, sizeof(EXPLICIT_ACCESS)); switch(pTargetPtr->Trustee.TrusteeForm) { case TRUSTEE_IS_SID: ulTrusteeNameSize = GetSidLengthRequired(((PISID)(pTargetPtr->Trustee.ptstrName))->SubAuthorityCount); pTargetPtr->Trustee.ptstrName = (LPWSTR)midl_user_allocate(ulTrusteeNameSize); CopySid(ulTrusteeNameSize, (PISID)(pTargetPtr->Trustee.ptstrName), (PISID)(pSourcePtr->Trustee.ptstrName)); break; case TRUSTEE_IS_NAME: ulTrusteeNameSize = lstrlenW(pSourcePtr->Trustee.ptstrName); pTargetPtr->Trustee.ptstrName = (LPWSTR)midl_user_allocate((ulTrusteeNameSize + 1) * sizeof(WCHAR)); lstrcpyW(pTargetPtr->Trustee.ptstrName, pSourcePtr->Trustee.ptstrName); break; } } *pcCount = cCount; } void ExecTestServer ( CHAR *pszTestString ) { ULONG ulCode; HRESULT hr; printf("Calling TestServer.\n"); g_pIAccessControlTest->TestServer(pszTestString); } // ExecTestServer void ExecRevertAccessRights ( void ) { ULONG ulCode; HRESULT hr; printf("Calling RevertAccessRights.\n"); hr = g_pIAccessControlTest->RevertAccessRights(); if(hr == E_NOTIMPL) { printf("hr is E_NOTIMPL.\n"); } } // ExecRevertAccessRights void ExecCommitAccessRights ( void ) { ULONG ulCode; HRESULT hr; printf("Calling CommitAccessRights.\n"); hr = g_pIAccessControlTest->CommitAccessRights(0); if(hr == E_NOTIMPL) { printf("hr is E_NOTIMPL.\n"); } } // ExecCommitAccessRights void ExecGetClassID ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; CLSID clsid; HRESULT hr; printf("Calling GetClassID.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->GetClassID(&clsid, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); printf("The clsid returned is {%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}.\n" , clsid.Data1, clsid.Data2, clsid.Data3 , clsid.Data4[0], clsid.Data4[1], clsid.Data4[2] , clsid.Data4[3], clsid.Data4[4], clsid.Data4[5] , clsid.Data4[6], clsid.Data4[7]); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecGetSizeMax void ExecInitNewACL ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; printf("Calling InitNewACL.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->InitNewACL(&dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecInitNewACL void ExecLoadACL ( CHAR *pszFilename ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; printf("Calling LoadACL.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->LoadACL(pszFilename, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecLoadACL void ExecSaveACL ( CHAR *pszFilename ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; ULONG ulNumOfBytesWritten; HRESULT hr; printf("Calling SaveACL.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->SaveACL(pszFilename, TRUE, &ulNumOfBytesWritten, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The number of bytes written to the file was %d\n", ulNumOfBytesWritten); printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecSaveACL void ExecGetSizeMax ( void ) { ULONG ulCode; DWORD dwTotalTickCount; DOUBLE dMillisec; ULONG ulNumOfBytesRequired; HRESULT hr; printf("Calling GetSizeMax.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->GetSizeMax(&ulNumOfBytesRequired, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The number of bytes required to save the ACL was %d\n", ulNumOfBytesRequired); printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecGetSizeMax void ExecIsDirty ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; printf("Calling IsDirty.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->IsDirty(&dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); if(hr == S_OK) { printf("The access control object was dirty.\n"); } else { printf("The access control object was clean.\n"); } } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecIsDirty void ExecGrantAccessRights ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; printf("Calling GrantAccessRights.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->GrantAccessRights(g_ulNumOfLocalAccessRequests, (PE_ACCESS_REQUEST)(g_pLocalAccessRequestList), &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecGrantAccessRights void ExecSetAccessRights ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; printf("Calling SetAccessRights.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->SetAccessRights(g_ulNumOfLocalAccessRequests, (PE_ACCESS_REQUEST)g_pLocalAccessRequestList, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecSetAccessRights void ExecDenyAccessRights ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; printf("Calling DenyAccessRights.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->DenyAccessRights(g_ulNumOfLocalAccessRequests, (PE_ACCESS_REQUEST)g_pLocalAccessRequestList, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecDenyAccessRights void ExecReplaceAllAccessRights ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; printf("Calling ReplaceAllAccessRights.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->ReplaceAllAccessRights(g_ulNumOfLocalExplicitAccesses, (PE_EXPLICIT_ACCESS)g_pLocalExplicitAccessList, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecReplaceAllAccessRights void ExecRevokeExplicitAccessRights ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; printf("Calling RevokeExplicitAccessRights.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->RevokeExplicitAccessRights(g_ulNumOfLocalTrustees, (PE_TRUSTEE)g_pLocalTrusteeList, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecRevokeExplicitAccessRights void ExecIsAccessPermitted ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; TRUSTEE_W Trustee; MapTrusteeRecordToTrustee(&g_LocalTrusteeRecord, &Trustee); printf("Calling IsAccessPermitted.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->IsAccessPermitted((PE_TRUSTEE)&Trustee, g_LocalTrusteeRecord.grfAccessPermissions, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if (hr == S_OK) { printf("The current trustee is granted the current set of access rights.\n"); } else if (hr == E_ACCESSDENIED) { printf("The current trustee is denied the current set of access rights.\n"); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecIsAccessPermitted void ExecGetEffectiveAccessRights ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; TRUSTEE_W Trustee; DWORD dwRights; MapTrusteeRecordToTrustee(&g_LocalTrusteeRecord, &Trustee); printf("Calling GetEffectiveAccessRights.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->GetEffectiveAccessRights((PE_TRUSTEE)&Trustee, &dwRights, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); printf("The set of effective access rights available to the current trustee includes:\n"); DumpAccessPermissions(dwRights); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecGetEffectiveAccessRights void ExecGetExplicitAccessRights ( void ) { ULONG ulCode; DOUBLE dMillisec; DWORD dwTotalTickCount; HRESULT hr; // If the global retruned explicit access list pointer is not NULL, // release the old returned explicit access list if (g_pReturnedExplicitAccessList != NULL) { ReleaseExplicitAccessList(g_ulNumOfExplicitAccessesReturned, g_pReturnedExplicitAccessList); } // if g_pReturnedExplicitAccessList = NULL; printf("Calling GetExplicitAccessRights.\n"); dwTotalTickCount = GetTickCount(); hr = g_pIAccessControlTest->GetExplicitAccessRights(&g_ulNumOfExplicitAccessesReturned, (PE_EXPLICIT_ACCESS *)&g_pReturnedExplicitAccessList, &dMillisec); dwTotalTickCount = GetTickCount() - dwTotalTickCount; if(SUCCEEDED(hr)) { printf("The command was executed successfully on the server side with a return code of %x.\n", hr); printf("The number of explicit access structures returned is %d.\n", g_ulNumOfExplicitAccessesReturned); printf("The returned explicit access list is as follows:\n"); DumpExplicitAccessList(g_ulNumOfExplicitAccessesReturned, g_pReturnedExplicitAccessList); } else { printf("Execution of the command failed on the server side with a return code of %x.\n", hr); } // if printf("The time spent on the server side to execute the command was %fms.\n", dMillisec); printf("The total number of clock ticks spent on the DCOM call was %d.\n", dwTotalTickCount); } // ExecGetExplicitAccessRights void ExecCleanupProc ( void ) { ULONG ulCode; // Release the IAccessControlTest pointer g_pIAccessControlTest->Release(); g_pIUnknown->Release(); // Cleanup all the memory allocated for the Local list DestroyAccessRequestList(g_pLocalAccessRequestList, &g_ulNumOfLocalAccessRequests); DestroyTrusteeList(g_pLocalTrusteeList, &g_ulNumOfLocalTrustees); DestroyExplicitAccessList(g_pLocalExplicitAccessList, &g_ulNumOfLocalExplicitAccesses); DestroyExplicitAccessList(g_pReturnedExplicitAccessList, &g_ulNumOfExplicitAccessesReturned); } // ExecCleanupProc /* Function: Tokenize Parameters: [in] char *pLineBuffer [out] char *pTokens[] [out] short *piNumOfTokens Return: void Purpose: This function partition a string of space delimited tokens to null delimited tokens and return pointers to each individual token in pTokens and the number of tokens ion the string in piNumOfTokens. Comment: Memory for the array of char * Tokens should be allocated by the caller. This function is implemented as a simple finite state machine. State 0 - Outside a token State 1 - Inside a token */ void Tokenize ( char * pLineBuffer, char * pTokens[], short * piNumOfTokens ) { short iTokens = 0; // Token index char *pLBuffPtr = pLineBuffer; // Pointer in the line buffer char c; // current character short state = 0; // State of the tokenizing machine for(;;) { c = *pLBuffPtr; switch(state) { case 0: switch(c) { case '\t': // Ignore blanks case ' ': case '\n': break; case '\0': goto end; default: state=1; pTokens[iTokens]=pLBuffPtr; break; } // switch break; case 1: switch(c) { case '\t': case ' ': case '\n': *pLBuffPtr='\0'; iTokens++; state=0; break; case '\0': *pLBuffPtr='\0'; iTokens++; pTokens[iTokens]=pLBuffPtr; goto end; default: break; } break; } pLBuffPtr++; }// switch end: *piNumOfTokens = iTokens; return; } // Tokenize /*********************************************************************/ /* MIDL allocate and free */ /*********************************************************************/ void __RPC_FAR * __RPC_USER midl_user_allocate(size_t len) { return(CoTaskMemAlloc(len)); } void __RPC_USER midl_user_free(void __RPC_FAR * ptr) { CoTaskMemFree(ptr); } /* end file actestc.c */
29.616096
163
0.572856
[ "object" ]
e0362e2d61ac567505120c50a6bdb01070093563
5,017
hpp
C++
ipuma-lib/ipusw/ipumultidriver.hpp
xiamaz/ipuma
f8bc8ac24a5c282cf8c2003cb32bc21c1cb386e2
[ "BSD-3-Clause-LBNL" ]
null
null
null
ipuma-lib/ipusw/ipumultidriver.hpp
xiamaz/ipuma
f8bc8ac24a5c282cf8c2003cb32bc21c1cb386e2
[ "BSD-3-Clause-LBNL" ]
null
null
null
ipuma-lib/ipusw/ipumultidriver.hpp
xiamaz/ipuma
f8bc8ac24a5c282cf8c2003cb32bc21c1cb386e2
[ "BSD-3-Clause-LBNL" ]
null
null
null
#ifndef IPU_MULTI_DRIVER_HPP #define IPU_MULTI_DRIVER_HPP #include "ipuswconfig.hpp" #include "nlohmann/json.hpp" #include <plog/Log.h> using json = nlohmann::json; class IPUMultiDriver { ipu::batchaffine::SWAlgorithm* driver; double clockFrequency; public: IpuSwConfig config; std::atomic<int> totalCmpsProcessed = 0; std::atomic<int> totalBatchesProcessed = 0; IPUMultiDriver(IpuSwConfig config) : config(config) { PLOGD << "Initialize drivers."; driver = new ipu::batchaffine::SWAlgorithm(config.swconfig, config.ipuconfig, 0, 0, config.numDevices); clockFrequency = driver->getTileClockFrequency(); } ~IPUMultiDriver() { delete driver; } void fill_input_buffer(const ipu::RawSequences& a, const ipu::RawSequences& b, std::vector<int32_t>& input_buffer, std::vector<int32_t>& mapping) { ipu::batchaffine::SWAlgorithm::prepare_remote(config.swconfig, config.ipuconfig, a, b, &*input_buffer.begin(), &*input_buffer.end(), mapping.data()); } void submitWait(std::vector<int32_t>& inputBuffer, std::vector<int32_t>& resultBuffer) { auto* job = driver->async_submit_prepared_remote_compare(&*inputBuffer.begin(), &*inputBuffer.end(), &*resultBuffer.begin(), &*resultBuffer.end()); job->join(); PLOGD << "Total engine run time (in s): " << static_cast<double>(job->tick.duration<std::chrono::milliseconds>()) / 1000.0; #ifdef IPUMA_DEBUG // auto [lot, sid] = unpack_slot(slot_token); auto cyclesOuter = job->h2dCycles + job->innerCycles; auto cyclesInner = job->innerCycles; auto timeJob = static_cast<double>(job->tick.accumulate_microseconds()) / 1e6; auto timeBatch = static_cast<double>(job->sb.runTick.accumulate_microseconds()) / 1e6; auto timeOuter = static_cast<double>(cyclesOuter) / clockFrequency; auto timeInner = static_cast<double>(cyclesInner) / clockFrequency; int32_t *meta_input = job->sb.inputs_begin + config.ipuconfig.getTotalBufsize32b(); // GCUPS computation uint64_t cellCount = 0; uint64_t dataCount = 0; for (size_t i = 0; i < config.ipuconfig.getTotalNumberOfComparisons(); i++) { auto a_len = meta_input[4 * i]; auto b_len = meta_input[4 * i + 2]; cellCount += a_len * b_len; dataCount += a_len + b_len; } double GCUPSOuter = static_cast<double>(cellCount) / timeOuter / 1e9; double GCUPSInner = static_cast<double>(cellCount) / timeInner / 1e9; double GCUPSJob = static_cast<double>(cellCount) / timeJob / 1e9; double GCUPSBatch = static_cast<double>(cellCount) / timeBatch / 1e9; double totalTransferSize = config.ipuconfig.getInputBufferSize32b() * 4; auto transferTime = timeOuter - timeInner; auto transferInfoRatio = static_cast<double>(dataCount) / totalTransferSize * 100; auto transferBandwidth = totalTransferSize / transferTime / 1e6; auto transferBandwidthPerVertex = transferBandwidth / config.ipuconfig.tilesUsed; json log = { {"tag", "batch_perf"}, {"cycle_inner", cyclesInner}, {"cycle_outer", cyclesOuter}, {"time_inner", timeInner}, {"time_outer", timeOuter}, {"time_job", timeJob}, {"cell_count", cellCount}, {"gcups_inner", GCUPSInner}, {"gcups_outer", GCUPSOuter}, {"gcups_job", GCUPSJob}, {"gcups_batch", GCUPSBatch}, {"transfer_size_total", totalTransferSize}, {"time_h2d", transferTime}, {"data_count", dataCount}, {"transfer_ratio", transferInfoRatio}, {"transfer_bandwidth", transferBandwidth}, {"transfer_bandwidth_per_vertex", transferBandwidthPerVertex}, }; PLOGD << IPU_JSON_LOG_TAG << log.dump(); #endif delete job; } void fillResults(std::vector<int32_t>& resultBuffer, std::vector<int>& mappingBuffer, ipu::batchaffine::BlockAlignmentResults& results, const int numCmps) { results.scores.resize(numCmps); results.a_range_result.resize(numCmps); results.b_range_result.resize(numCmps); ipu::batchaffine::SWAlgorithm::transferResults( &*resultBuffer.begin(), &*resultBuffer.end(), &*mappingBuffer.begin(), &*mappingBuffer.end(), &*(results.scores.begin()), &*(results.scores.begin() + numCmps), &*(results.a_range_result.begin()), &*(results.a_range_result.begin() + numCmps), &*(results.b_range_result.begin()), &*(results.b_range_result.begin() + numCmps), numCmps); } }; #endif
46.453704
165
0.609926
[ "vector" ]
e042e6fe65269081d71182351c8e19531141a113
29,624
cpp
C++
src/plugins/auto/auto_schedule.cpp
si-eun-kim/openvino
1db4446e2a6ead55d066e0b4e718fa37f509353a
[ "Apache-2.0" ]
2
2021-12-14T15:27:46.000Z
2021-12-14T15:34:16.000Z
src/plugins/auto/auto_schedule.cpp
si-eun-kim/openvino
1db4446e2a6ead55d066e0b4e718fa37f509353a
[ "Apache-2.0" ]
33
2021-09-23T04:14:30.000Z
2022-01-24T13:21:32.000Z
src/plugins/auto/auto_schedule.cpp
si-eun-kim/openvino
1db4446e2a6ead55d066e0b4e718fa37f509353a
[ "Apache-2.0" ]
11
2021-11-09T00:51:40.000Z
2021-11-10T12:04:16.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /////////////////////////////////////////////////////////////////////////////////////////////////// #include "auto_schedule.hpp" #include "async_infer_request.hpp" #include "auto_executable_network.hpp" #include "plugin.hpp" // ------------------------------AutoSchedule---------------------------- namespace MultiDevicePlugin { namespace { std::string GetNetworkPrecision(const IE::CNNNetwork& network) { auto nGraphFunc = network.getFunction(); bool isINTModel = ngraph::op::util::has_op_with_type<ngraph::op::FakeQuantize> (nGraphFunc); if (isINTModel) { return METRIC_VALUE(INT8); } for (auto& node : nGraphFunc->get_ordered_ops()) { if (std::dynamic_pointer_cast<ngraph::opset1::Convolution>(node) || std::dynamic_pointer_cast<ngraph::opset1::GroupConvolution>(node) || std::dynamic_pointer_cast<ngraph::opset1::GroupConvolutionBackpropData>(node) || std::dynamic_pointer_cast<ngraph::opset1::ConvolutionBackpropData>(node)) { auto layerType = node->input(1).get_element_type().get_type_name(); if (layerType == "f32") { return METRIC_VALUE(FP32); } if (layerType == "f16") { return METRIC_VALUE(FP16); } } } return METRIC_VALUE(FP32); } } // namespace void AutoSchedule::GenerateWorkers(const std::string& device, const SoExecNetwork& executableNetwork) { std::string realDeviceName; if (device == "CPU_HELP") { realDeviceName = "CPU"; } else { realDeviceName = device; } auto itNumRequests = std::find_if(_autoSContext->_devicePriorities.cbegin(), _autoSContext->_devicePriorities.cend(), [&realDeviceName](const DeviceInformation & d) { return d.deviceName == realDeviceName; }); unsigned int optimalNum = 0; try { optimalNum = executableNetwork->GetMetric(METRIC_KEY(OPTIMAL_NUMBER_OF_INFER_REQUESTS)).as<unsigned int>(); } catch (const IE::Exception& iie) { IE_THROW() << "Every device used with the Multi-Device should " << "support OPTIMAL_NUMBER_OF_INFER_REQUESTS ExecutableNetwork metric. " << "Failed to query the metric for the " << device << " with error:" << iie.what(); } const auto numRequests = (_autoSContext->_devicePriorities.end() == itNumRequests || itNumRequests->numRequestsPerDevices == -1) ? optimalNum : itNumRequests->numRequestsPerDevices; auto& workerRequests = _workerRequests[device]; auto& idleWorkerRequests = _idleWorkerRequests[device]; workerRequests.resize(numRequests); _inferPipelineTasksDeviceSpecific[device] = std::unique_ptr<IE::ThreadSafeQueue<IE::Task>>(new IE::ThreadSafeQueue<IE::Task>); auto* idleWorkerRequestsPtr = &(idleWorkerRequests); idleWorkerRequests.set_capacity(numRequests); int num = 0; for (auto&& workerRequest : workerRequests) { workerRequest._inferRequest = {executableNetwork->CreateInferRequest(), executableNetwork._so}; auto* workerRequestPtr = &workerRequest; workerRequestPtr->_index = num++; IE_ASSERT(idleWorkerRequests.try_push(std::make_pair(workerRequestPtr->_index, workerRequestPtr)) == true); workerRequest._inferRequest->SetCallback( [workerRequestPtr, this, device, idleWorkerRequestsPtr](std::exception_ptr exceptionPtr) mutable { IdleGuard<NotBusyPriorityWorkerRequests> idleGuard{workerRequestPtr, *idleWorkerRequestsPtr}; workerRequestPtr->_exceptionPtr = exceptionPtr; { auto capturedTask = std::move(workerRequestPtr->_task); capturedTask(); } // try to return the request to the idle list (fails if the overall object destruction has began) if (idleGuard.Release()->try_push(std::make_pair(workerRequestPtr->_index, workerRequestPtr))) { // let's try to pop a task, as we know there is at least one idle request, schedule if succeeded // if no device-agnostic tasks, let's try pop the device specific task, schedule if succeeded IE::Task t; do { _inferPipelineTasks.try_pop(t); } while (t && ScheduleToWorkerInferRequest(std::move(t))); do { _inferPipelineTasksDeviceSpecific[device]->try_pop(t); } while (t && ScheduleToWorkerInferRequest(std::move(t), device)); } }); } } void AutoSchedule::init(const ScheduleContext::Ptr& sContext) { LOG_INFO("[AUTOPLUGIN]ExecutableNetwork start"); // initialize cpuHelpReleasetime _cpuHelpReleaseTime = std::chrono::steady_clock::now(); _multiSContext = std::dynamic_pointer_cast<MultiScheduleContext>(sContext); _autoSContext = std::dynamic_pointer_cast<AutoScheduleContext>(sContext); if (_autoSContext->_core == nullptr) { IE_THROW() << "Please, work with Auto device via InferencEngine::Core object"; } if (_autoSContext->_modelPath.empty() && _autoSContext->_network.getFunction() == nullptr) { IE_THROW() << "AUTO device supports just ngraph network representation"; } _autoSContext->_config[IE::MultiDeviceConfigParams::KEY_MULTI_DEVICE_PRIORITIES] = _autoSContext->_strDevices; std::string profilingTask = "AutoSchedule::AutoSchedule:AutoMode"; bool isCumulative = (_autoSContext->_performanceHint == IE::PluginConfigParams::CUMULATIVE_THROUGHPUT) ? true : false; // loadContext[ACTUALDEVICE] is always enabled, // when there is CPU and there are more than two devices, loadContext[CPU] is enabled _loadContext[ACTUALDEVICE].isEnabled = true; if (_autoSContext->_modelPath.empty()) _loadContext[ACTUALDEVICE].networkPrecision = GetNetworkPrecision(_autoSContext->_network); _loadContext[ACTUALDEVICE].metaDevices = _autoSContext->_devicePriorities; if (isCumulative) { std::list<DeviceInformation> validDevices = _autoSContext->_plugin->GetValidDevice(_autoSContext->_devicePriorities, _loadContext[ACTUALDEVICE].networkPrecision); // check if device priority is enabled bool enableDevicePriority = std::find_if(std::begin(validDevices), std::end(validDevices), [](DeviceInformation& di) { return di.devicePriority > 0; }) != std::end(validDevices); // for the case of -d "AUTO" or "AUTO: -xxx" if (!enableDevicePriority) { std::list<DeviceInformation>::iterator itCPUDevice; int GPUNums = 0, CPUNums = 0; for (auto it = validDevices.begin(); it != validDevices.end(); it++) { if (it->deviceName.find("GPU") != std::string::npos) { GPUNums++; } if (it->deviceName.find("CPU") == 0) { CPUNums++; itCPUDevice = it; } } // remove CPU from default candidate list for Cumulative Throughput mode if (GPUNums >= 2 && CPUNums > 0) { validDevices.erase(itCPUDevice); LOG_INFO("[AUTOPLUGIN]:GPUNums:%d, remove CPU from default candidate list for " "CUMULATIVE_THROUGHPUT", GPUNums); } } std::string deviceName = "MULTI:"; for (auto& device : validDevices) { deviceName += device.deviceName; deviceName += ((device.deviceName == validDevices.back().deviceName) ? "" : ","); } _loadContext[ACTUALDEVICE].deviceInfo.deviceName = deviceName; _loadContext[ACTUALDEVICE].deviceInfo.config[CONFIG_KEY(PERFORMANCE_HINT)] = InferenceEngine::PluginConfigParams::THROUGHPUT; } else { _loadContext[ACTUALDEVICE].deviceInfo = _autoSContext->_plugin->SelectDevice(_autoSContext->_devicePriorities, _loadContext[ACTUALDEVICE].networkPrecision, _autoSContext->_modelPriority); } LOG_INFO("[AUTOPLUGIN]:select device:%s", _loadContext[ACTUALDEVICE].deviceInfo.deviceName.c_str()); bool isActualDevCPU = _loadContext[ACTUALDEVICE].deviceInfo.deviceName.find("CPU") !=std::string::npos; // if Actual device is CPU, disabled _loadContext[CPU], only use _loadContext[ACTUALDEVICE] if (isActualDevCPU || isCumulative) { _loadContext[CPU].isEnabled = false; } else { const auto CPUIter = std::find_if(_autoSContext->_devicePriorities.begin(), _autoSContext->_devicePriorities.end(), [=](const DeviceInformation& d) -> bool { return d.deviceName.find("CPU") != std::string::npos; }); // if have CPU Device, enable _loadContext[CPU] if (CPUIter != _autoSContext->_devicePriorities.end()) { _loadContext[CPU].isEnabled = true; _loadContext[CPU].deviceInfo = *CPUIter; _loadContext[CPU].deviceInfo.config[CONFIG_KEY(PERFORMANCE_HINT)] = IE::PluginConfigParams::LATENCY; _loadContext[CPU].workName = "CPU_HELP"; LOG_INFO("[AUTOPLUGIN]:will load CPU for accelerator"); } else { _loadContext[CPU].isEnabled = false; } } // initialize the rest members of load context for (int i = 0; i < CONTEXTNUM; i++) { if (_loadContext[i].isEnabled) { _loadContext[i].future = _loadContext[i].promise.get_future(); auto* contextPtr = &_loadContext[i]; auto modelPath = _autoSContext->_modelPath; auto network = _autoSContext->_network; _loadContext[i].task = [this, contextPtr, modelPath, network, isCumulative]() mutable { TryToLoadNetWork(*contextPtr, modelPath, network); if (contextPtr->isLoadSuccess) { if (contextPtr->workName.empty()) { contextPtr->workName = contextPtr->deviceInfo.deviceName; } GenerateWorkers(contextPtr->workName, contextPtr->executableNetwork); //need lock { std::lock_guard<std::mutex> lock(_autoSContext->_confMutex); _autoSContext->_config.insert(contextPtr->deviceInfo.config.begin(), contextPtr->deviceInfo.config.end()); } contextPtr->isAlready = true; auto& deviceName = contextPtr->deviceInfo.deviceName; LOG_INFO("[AUTOPLUGIN]:device:%s loading Network finished", deviceName.c_str()); if (!isCumulative) { auto supported_config_keys = _autoSContext->_core->GetMetric(deviceName, METRIC_KEY(SUPPORTED_CONFIG_KEYS)) .as<std::vector<std::string>>(); DEBUG_RUN([this, &contextPtr, &deviceName, &supported_config_keys] { std::lock_guard<std::mutex> lock(_autoSContext->_confMutex); for (const auto& cfg : supported_config_keys) { try { LOG_DEBUG( "[AUTOPLUGIN]:device:%s, GetConfig:%s=%s", deviceName.c_str(), cfg.c_str(), contextPtr->executableNetwork->GetConfig(cfg).as<std::string>().c_str()); } catch (...) { } } }); } } contextPtr->promise.set_value(); // the first load network process finished std::call_once(_firstLoadOC, [this]() { _firstLoadPromise.set_value(); }); }; } } OV_ITT_SCOPED_TASK(itt::domains::MULTIPlugin, openvino::itt::handle(profilingTask)); if (_loadContext[CPU].isEnabled) { _firstLoadFuture = _firstLoadPromise.get_future(); // will not wait for loading accelerator network, // so the executor can't be destroyed before finished the task, // so use executor as a member of AutoSchedule. _executor = _autoSContext->_plugin->executorManager()->getIdleCPUStreamsExecutor( IE::IStreamsExecutor::Config{"AutoDeviceAsyncLoad", static_cast<int>(std::thread::hardware_concurrency()) /* max possible #streams*/, 0 /*default threads per stream, workaround for ticket 62376*/, IE::IStreamsExecutor::ThreadBindingType::NONE}); for (auto&& device : _autoSContext->_devicePriorities) { // initialize containers before run async task _idleWorkerRequests[device.deviceName]; _workerRequests[device.deviceName]; _inferPipelineTasksDeviceSpecific[device.deviceName] = nullptr; } _idleWorkerRequests["CPU_HELP"]; _workerRequests["CPU_HELP"]; _inferPipelineTasksDeviceSpecific["CPU_HELP"] = nullptr; _executor->run(_loadContext[CPU].task); _executor->run(_loadContext[ACTUALDEVICE].task); auto recycleTask = [this]() mutable { WaitActualNetworkReady(); while (!_exitFlag && _loadContext[ACTUALDEVICE].isAlready) { // handle the case of ACTUAL faster than CPU _loadContext[CPU].future.wait(); // clean up helper infer requests // first, wait for all the remaining requests to finish for (auto& iter : _workerRequests["CPU_HELP"]) { iter._inferRequest._ptr->Wait(IE::InferRequest::WaitMode::RESULT_READY); } // late enough to check the idle queue now // second, check the idle queue if all requests are in place size_t destroynum = 0; std::pair<int, WorkerInferRequest*> worker; std::list<Time> cpuHelpAllStartTimes; std::list<Time> cpuHelpAllEndTimes; while (_idleWorkerRequests["CPU_HELP"].try_pop(worker)) { destroynum++; INFO_RUN([&cpuHelpAllStartTimes, &cpuHelpAllEndTimes, &worker]() { cpuHelpAllStartTimes.splice(cpuHelpAllStartTimes.end(), worker.second->_startTimes); cpuHelpAllEndTimes.splice(cpuHelpAllEndTimes.end(), worker.second->_endTimes); }); } INFO_RUN([this, &cpuHelpAllStartTimes, &cpuHelpAllEndTimes]() { cpuHelpAllStartTimes.sort(std::less<Time>()); cpuHelpAllEndTimes.sort(std::less<Time>()); _cpuHelpInferCount = cpuHelpAllStartTimes.size(); IE_ASSERT(_cpuHelpInferCount == cpuHelpAllEndTimes.size()); }); if (destroynum == _workerRequests["CPU_HELP"].size()) { std::lock_guard<std::mutex> lock(_autoSContext->_confMutex); INFO_RUN([this, &cpuHelpAllStartTimes, &cpuHelpAllEndTimes, &destroynum]() { _cpuHelpReleaseTime = std::chrono::steady_clock::now(); if (cpuHelpAllStartTimes.size() >= destroynum + 1) { //remove last worksize num requests, so the fps will be more accuracy cpuHelpAllStartTimes.resize(_cpuHelpInferCount - destroynum); cpuHelpAllEndTimes.resize(_cpuHelpInferCount - destroynum); std::chrono::duration<double, std::milli> durtation = cpuHelpAllEndTimes.back() - cpuHelpAllStartTimes.front(); _cpuHelpFps = cpuHelpAllStartTimes.size() * 1000 / durtation.count(); } }); LOG_INFO("[AUTOPLUGIN] release all work requests of CPU_HELP"); _workerRequests["CPU_HELP"].clear(); _loadContext[CPU].executableNetwork._ptr.reset(); _loadContext[CPU].executableNetwork._so.reset(); LOG_INFO("[AUTOPLUGIN]:helper released!!"); break; } } }; _executor->run(std::move(recycleTask)); } else { // only one device need to load network, do not need to load it async _loadContext[ACTUALDEVICE].task(); _passthroughExeNet = _loadContext[ACTUALDEVICE].executableNetwork; } WaitFirstNetworkReady(); } void AutoSchedule::TryToLoadNetWork(AutoLoadContext& context, const std::string& modelPath, const IE::CNNNetwork& network) { auto& device = context.deviceInfo.deviceName; auto& deviceConfig = context.deviceInfo.config; auto& deviceList = context.metaDevices; bool curDevIsCPU = (device.find("CPU") != std::string::npos); bool curDevIsGPU = (device.find("GPU") != std::string::npos); { std::lock_guard<std::mutex> lock(_autoSContext->_confMutex); if (curDevIsGPU && _loadContext[CPU].isEnabled) { // user does not set the compiling threads // limit the threads num for compiling int maxNumThreads = 0; try { maxNumThreads = _autoSContext->_core->GetConfig(device, GPU_CONFIG_KEY(MAX_NUM_THREADS)).as<int>(); } catch (...) { LOG_DEBUG("[AUTOPLUGIN]: cannot get MAX_NUM_THREADS from GPU"); } if (maxNumThreads == static_cast<int>(std::thread::hardware_concurrency())) { int threadNum = maxNumThreads / 2; deviceConfig[GPU_CONFIG_KEY(MAX_NUM_THREADS)] = std::to_string(threadNum).c_str(); LOG_DEBUG("[AUTO PLUGIN]:gpu streams number for compiling: %s", deviceConfig[GPU_CONFIG_KEY(MAX_NUM_THREADS)].c_str()); } else { // user set the compiling threads num // use the user's val anyway LOG_DEBUG("[AUTOPLUGIN]:user defined compiling threads: %d", maxNumThreads); } } } try { if (!modelPath.empty()) { context.executableNetwork = _autoSContext->_core->LoadNetwork(modelPath, device, deviceConfig); } else { context.executableNetwork = _autoSContext->_core->LoadNetwork(network, device, deviceConfig); } context.isLoadSuccess = true; } catch (const std::exception& e) { context.errMessage += device + ":" + e.what(); context.isLoadSuccess = false; } if (context.isLoadSuccess || curDevIsCPU) { return; } // need to reload network, unregister it's priority // there maybe potential issue. // for example they are dGPU, VPUX, iGPU, customer want to LoadNetwork with // configure 0 dGPU, 1 VPUX, if dGPU load failed, // the result will be not sure, maybe two network are loaded into VPUX, // maybe 0 is loaded to VPUX, 1 is loaded to iGPU _autoSContext->_plugin->UnregisterPriority(_autoSContext->_modelPriority, context.deviceInfo.uniqueName); // remove the current device from deviceList auto eraseDevice = std::find_if(deviceList.begin(), deviceList.end(), [device](DeviceInformation & d) { return d.deviceName == device; }); deviceList.erase(eraseDevice); if (deviceList.empty()) { return; } // select next candidate device try { std::lock_guard<std::mutex> lock(_autoSContext->_confMutex); context.deviceInfo = _autoSContext->_plugin->SelectDevice(deviceList, context.networkPrecision, _autoSContext->_modelPriority); } catch (const std::exception& e) { return; } // if the select device is CPU, need to check the config of _loadContext[CPU] // if they are same, do not need to load again curDevIsCPU = (context.deviceInfo.deviceName.find("CPU") != std::string::npos); if (curDevIsCPU) { auto compare = [](std::map<std::string, std::string>& a, std::map<std::string, std::string>& b) -> bool { if (a.size() != b.size()) { return false; } for (auto& item : a) { auto bIter = b.find(item.first); if (bIter != b.end()) { if (bIter->second != item.second) { return false; } } else { return false; } } return true; }; if (compare(context.deviceInfo.config, _loadContext[CPU].deviceInfo.config)) { return; } } LOG_DEBUG("[AUTOPLUGIN] try to load %s", context.deviceInfo.deviceName.c_str()); // try to load this candidate device TryToLoadNetWork(context, modelPath, network); } void AutoSchedule::WaitFirstNetworkReady() { if (_firstLoadFuture.valid()) { // wait for the first loading finished _firstLoadFuture.wait(); } // check if there is any device that have loaded network successfully for (int i = CONTEXTNUM - 1; i >= 0; i--) { if (_loadContext[i].isEnabled && _loadContext[i].isAlready) { return; } } // the first loading is failed, wait for another loading for (int i = CONTEXTNUM - 1; i >= 0; i--) { if (_loadContext[i].isEnabled) { _loadContext[i].future.wait(); // check if loading is successful if (_loadContext[i].isAlready) { return; } } } //print errMessage for (int i = CONTEXTNUM - 1; i >= 0; i--) { if (_loadContext[i].isEnabled) { LOG_ERROR("[AUTOPLUGIN] load failed, %s", _loadContext[i].errMessage.c_str()); } } IE_THROW() << "[AUTOPLUGIN] load all devices failed"; } void AutoSchedule::WaitActualNetworkReady() const { OV_ITT_SCOPED_TASK(itt::domains::MULTIPlugin, "AutoSchedule::WaitActualNetworkReady"); // Maybe different API will call this function, so add call once here // for every AutoSchedule instance std::call_once(_oc, [this]() { if (_loadContext[ACTUALDEVICE].future.valid()) { _loadContext[ACTUALDEVICE].future.wait(); } }); } bool AutoSchedule::ScheduleToWorkerInferRequest(IE::Task inferPipelineTask, DeviceName preferred_device) { std::vector<DeviceInformation> devices; // AUTO work mode if (!preferred_device.empty()) { // if the device needed by customer is not ready, need to wait for it WaitActualNetworkReady(); // the preferred_device should be the selected device in AUTO work mode if (preferred_device != _loadContext[ACTUALDEVICE].deviceInfo.deviceName) { IE_THROW(NotFound) << "The preferred device should be the selected device"; } devices.push_back(_loadContext[ACTUALDEVICE].deviceInfo); } else { // _acceleratorDevice could be the same as _cpuDevice, such as AUTO:CPU if (_loadContext[ACTUALDEVICE].isAlready) { devices.push_back(_loadContext[ACTUALDEVICE].deviceInfo); } else { // replace deviceName with workName, so schedule can select correct // idleWorkerQueue auto deviceInfo = _loadContext[CPU].deviceInfo; deviceInfo.deviceName = _loadContext[CPU].workName; devices.push_back(std::move(deviceInfo)); } } for (auto&& device : devices) { if (!preferred_device.empty() && (device.deviceName != preferred_device)) { continue; } if (RunPipelineTask(inferPipelineTask, _idleWorkerRequests[device.deviceName], preferred_device)) { return true; } } // no vacant requests this time, storing the task to the respective queue if (!preferred_device.empty()) { _inferPipelineTasksDeviceSpecific[preferred_device]->push(std::move(inferPipelineTask)); } else { _inferPipelineTasks.push(std::move(inferPipelineTask)); } return false; } bool AutoSchedule::RunPipelineTask(IE::Task& inferPipelineTask, NotBusyPriorityWorkerRequests& idleWorkerRequests, const DeviceName& preferred_device) { WorkerInferRequest* workerRequestPtr = nullptr; std::pair<int, WorkerInferRequest*> worker; if (idleWorkerRequests.try_pop(worker)) { workerRequestPtr = worker.second; IdleGuard<NotBusyPriorityWorkerRequests> idleGuard{workerRequestPtr, idleWorkerRequests}; _thisWorkerInferRequest = workerRequestPtr; { auto capturedTask = std::move(inferPipelineTask); capturedTask(); } idleGuard.Release(); return true; } return false; } AutoSchedule::~AutoSchedule() { // this is necessary to guarantee member destroyed after getting future if (_loadContext[CPU].isEnabled) { _exitFlag = true; _loadContext[CPU].future.wait(); WaitActualNetworkReady(); // it's necessary to wait the loading network threads to stop here. _autoSContext->_plugin->executorManager()->clear("AutoDeviceAsyncLoad"); _executor.reset(); } _autoSContext->_plugin->UnregisterPriority(_autoSContext->_modelPriority, _loadContext[ACTUALDEVICE].deviceInfo.uniqueName); LOG_INFO("[AUTOPLUGIN]ExecutableNetwork end"); } IInferPtr AutoSchedule::CreateInferRequestImpl( const std::vector<std::shared_ptr<const ov::Node>>& inputs, const std::vector<std::shared_ptr<const ov::Node>>& outputs) { auto num = _numRequestsCreated++; IE::SoIInferRequestInternal request_to_share_blobs_with; IE::RemoteContext::Ptr ctx = nullptr; if (!_loadContext[CPU].isEnabled && _loadContext[ACTUALDEVICE].isAlready) { try { ctx = _autoSContext->_core->GetDefaultContext( _loadContext[ACTUALDEVICE].deviceInfo.deviceName); } catch (IE::Exception& ex) { // plugin does not support context, say CPU LOG_DEBUG("[AUTOPLUGIN]context not supported for %s, fallback to default memory", _loadContext[ACTUALDEVICE].deviceInfo.deviceName.c_str()); // for dynamic shape support auto& dev_requests = _workerRequests[_loadContext[ACTUALDEVICE].deviceInfo.deviceName]; if (num < dev_requests.size()) { request_to_share_blobs_with = dev_requests.at(num)._inferRequest; } } } return std::make_shared<MultiDeviceInferRequest>(inputs, outputs, request_to_share_blobs_with, ctx); } IInferPtr AutoSchedule::CreateInferRequestImpl(IE::InputsDataMap networkInputs, IE::OutputsDataMap networkOutputs) { auto num = _numRequestsCreated++; SoInfer request_to_share_blobs_with; IE::RemoteContext::Ptr ctx = nullptr; if (!_loadContext[CPU].isEnabled && _loadContext[ACTUALDEVICE].isAlready) { try { ctx = _autoSContext->_core->GetDefaultContext( _loadContext[ACTUALDEVICE].deviceInfo.deviceName); } catch (IE::Exception& ex) { // plugin does not support context LOG_DEBUG("[AUTOPLUGIN]context not supported for %s, fallback to default memory", _loadContext[ACTUALDEVICE].deviceInfo.deviceName.c_str()); auto& dev_requests = _workerRequests[_loadContext[ACTUALDEVICE].deviceInfo.deviceName]; if (num < dev_requests.size()) { request_to_share_blobs_with = dev_requests.at(num)._inferRequest; } } } return std::make_shared<MultiDeviceInferRequest>(networkInputs, networkOutputs, request_to_share_blobs_with, ctx); } IInferPtr AutoSchedule::CreateInferRequest() { auto execNetwork = std::dynamic_pointer_cast<AutoExecutableNetwork>( _autoSContext->_executableNetwork.lock()); if (_passthroughExeNet) { auto res = _passthroughExeNet->CreateInferRequest(); res->setPointerToExecutableNetworkInternal(execNetwork); return res; } IInferPtr syncRequestImpl; if (_multiSContext->_core && _multiSContext->_core->isNewAPI()) syncRequestImpl = CreateInferRequestImpl(execNetwork->_parameters, execNetwork->_results); if (!syncRequestImpl) syncRequestImpl = CreateInferRequestImpl(execNetwork->_networkInputs, execNetwork->_networkOutputs); syncRequestImpl->setPointerToExecutableNetworkInternal(execNetwork); return std::make_shared<AsyncInferRequest>(shared_from_this(), syncRequestImpl, execNetwork->_callbackExecutor); } } // namespace MultiDevicePlugin
49.127695
141
0.601235
[ "object", "shape", "vector" ]
e052c018ee58680dae5a90d885c2fb9175d1b6f6
26,263
cpp
C++
codecs/mfx_codecs/src/MfxDirect3D9.cpp
catid/xrcap
d3c5900c44861e618fd28b4256387725646b85c7
[ "BSD-3-Clause" ]
62
2019-12-21T23:48:28.000Z
2021-11-25T14:29:28.000Z
codecs/mfx_codecs/src/MfxDirect3D9.cpp
catid/xrcap
d3c5900c44861e618fd28b4256387725646b85c7
[ "BSD-3-Clause" ]
5
2020-01-06T19:55:41.000Z
2020-06-19T23:13:24.000Z
codecs/mfx_codecs/src/MfxDirect3D9.cpp
catid/xrcap
d3c5900c44861e618fd28b4256387725646b85c7
[ "BSD-3-Clause" ]
10
2019-12-22T15:53:10.000Z
2021-07-18T09:12:06.000Z
// Copyright (c) 2019 Christopher A. Taylor. All rights reserved. #ifdef _WIN32 #include "MfxDirect3D9.hpp" #include <core_logging.hpp> #include <core_string.hpp> #include <comdef.h> #define D3DFMT_NV12 (D3DFORMAT)MAKEFOURCC('N','V','1','2') #define D3DFMT_YV12 (D3DFORMAT)MAKEFOURCC('Y','V','1','2') #define D3DFMT_NV16 (D3DFORMAT)MAKEFOURCC('N','V','1','6') #define D3DFMT_P010 (D3DFORMAT)MAKEFOURCC('P','0','1','0') #define D3DFMT_P210 (D3DFORMAT)MAKEFOURCC('P','2','1','0') #define D3DFMT_IMC3 (D3DFORMAT)MAKEFOURCC('I','M','C','3') #define D3DFMT_AYUV (D3DFORMAT)MAKEFOURCC('A','Y','U','V') #if (MFX_VERSION >= 1027) #define D3DFMT_Y210 (D3DFORMAT)MAKEFOURCC('Y','2','1','0') #define D3DFMT_Y410 (D3DFORMAT)MAKEFOURCC('Y','4','1','0') #endif #define MFX_FOURCC_IMC3 (MFX_MAKEFOURCC('I','M','C','3')) // This line should be moved into mfxstructures.h in new API version namespace mfx { //------------------------------------------------------------------------------ // Tools std::string HresultString(HRESULT hr) { std::ostringstream oss; oss << _com_error(hr).ErrorMessage() << " [hr=" << hr << "]"; return oss.str(); } bool D3DClearSurface(IDirect3DSurface9* pSurface, bool yuv) { D3DSURFACE_DESC desc{}; HRESULT hr = pSurface->GetDesc(&desc); if (FAILED(hr)) { spdlog::error("D3DClearRGBSurface: pSurface->GetDesc failed: {}", HresultString(hr)); return false; } D3DLOCKED_RECT locked{}; hr = pSurface->LockRect(&locked, 0, D3DLOCK_NOSYSLOCK); if (FAILED(hr)) { spdlog::error("D3DClearRGBSurface: pSurface->LockRect failed: {}", HresultString(hr)); return false; } const unsigned plane_bytes = desc.Height * locked.Pitch; memset(locked.pBits, 100, plane_bytes); if (yuv) { // Clear UV plane also memset((mfxU8*)locked.pBits + plane_bytes, 50, plane_bytes / 2); } pSurface->UnlockRect(); if (FAILED(hr)) { spdlog::error("D3DClearRGBSurface: pSurface->UnlockRect failed: {}", HresultString(hr)); return false; } return true; } D3DFORMAT D3DFormatFromFourCC(mfxU32 four_cc) { switch (four_cc) { case MFX_FOURCC_NV12: return D3DFMT_NV12; case MFX_FOURCC_YV12: return D3DFMT_YV12; case MFX_FOURCC_NV16: return D3DFMT_NV16; case MFX_FOURCC_YUY2: return D3DFMT_YUY2; case MFX_FOURCC_RGB3: return D3DFMT_R8G8B8; case MFX_FOURCC_RGB4: return D3DFMT_A8R8G8B8; case MFX_FOURCC_P8: return D3DFMT_P8; case MFX_FOURCC_P010: return D3DFMT_P010; case MFX_FOURCC_AYUV: return D3DFMT_AYUV; case MFX_FOURCC_P210: return D3DFMT_P210; #if (MFX_VERSION >= 1027) case MFX_FOURCC_Y210: return D3DFMT_Y210; case MFX_FOURCC_Y410: return D3DFMT_Y410; #endif case MFX_FOURCC_A2RGB10: return D3DFMT_A2R10G10B10; case MFX_FOURCC_ABGR16: case MFX_FOURCC_ARGB16: return D3DFMT_A16B16G16R16; case MFX_FOURCC_IMC3: return D3DFMT_IMC3; default: return D3DFMT_UNKNOWN; } } //------------------------------------------------------------------------------ // COMSession void COMSession::Initialize() { HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (FAILED(hr)) { spdlog::warn("Failed to start COM session: Error = {}", hr); } } void COMSession::Shutdown() { CoUninitialize(); } //------------------------------------------------------------------------------ // D3D9Context bool D3D9Context::Initialize(std::shared_ptr<MfxContext> context) { Shutdown(); InitFailed = true; if (!context->SupportsGpuSurfaces) { spdlog::error("MFX context does not support GPU surfaces: Must use system memory on this platform."); return false; } HRESULT hr; hr = ::Direct3DCreate9Ex(D3D_SDK_VERSION, D3D.GetAddressOf()); if (FAILED(hr)) { spdlog::error("D3D9Context creation failed: Direct3DCreate9Ex failed: {}", HresultString(hr)); return false; } const HWND desktop_window = GetDesktopWindow(); D3DPRESENT_PARAMETERS present_params{}; present_params.Windowed = true; present_params.hDeviceWindow = desktop_window; present_params.Flags = D3DPRESENTFLAG_VIDEO; present_params.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; present_params.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // note that this setting leads to an implicit timeBeginPeriod call present_params.BackBufferCount = 1; present_params.BackBufferFormat = D3DFMT_A8R8G8B8; present_params.BackBufferWidth = 512; present_params.BackBufferHeight = 512; present_params.SwapEffect = D3DSWAPEFFECT_DISCARD; // Mark the back buffer lockable if software DXVA2 could be used. // This is because software DXVA2 device requires a lockable render target // for the optimal performance. present_params.Flags |= D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; hr = D3D->CreateDeviceEx(context->GpuAdapterIndex, D3DDEVTYPE_HAL, desktop_window, D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE, &present_params, nullptr, Device.GetAddressOf()); if (FAILED(hr)) { spdlog::error("D3D9Context creation failed: D3D->CreateDeviceEx failed: {}", HresultString(hr)); return false; } hr = Device->ResetEx(&present_params, nullptr); if (FAILED(hr)) { spdlog::warn("D3D9Context creation warning: Device->ResetEx failed: {}", HresultString(hr)); //return false; } hr = Device->Clear(0, nullptr, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0); if (FAILED(hr)) { spdlog::warn("D3D9Context creation warning: Device->Clear failed: {}", HresultString(hr)); //return false; } hr = DXVA2CreateDirect3DDeviceManager9(&ResetToken, Manager.GetAddressOf()); if (FAILED(hr)) { spdlog::error("D3D9Context creation failed: DXVA2CreateDirect3DDeviceManager9 failed: {}", HresultString(hr)); return false; } ManagerHandle = (mfxHDL)Manager.Get(); hr = Manager->ResetDevice(Device.Get(), ResetToken); if (FAILED(hr)) { spdlog::error("D3D9Context creation failed: Manager->ResetDevice failed: {}", HresultString(hr)); return false; } hr = Manager->OpenDeviceHandle(&DeviceHandle); if (FAILED(hr)) { spdlog::error("D3D9Context creation failed: Manager->OpenDeviceHandle failed: {}", HresultString(hr)); return false; } Initialized = true; InitFailed = false; return true; } void D3D9Context::Shutdown() { if (Manager && DeviceHandle) { Manager->CloseDeviceHandle(DeviceHandle); DeviceHandle = nullptr; } ManagerHandle = nullptr; Manager.Reset(); Device.Reset(); D3D.Reset(); Initialized = false; InitFailed = false; } //------------------------------------------------------------------------------ // D3DAllocator bool D3DAllocator::Initialize( std::shared_ptr<MfxContext> context, const mfxVideoParam& video_params) { Context = context; VideoParams = video_params; InitFailed = true; IsVideoMemory = true; CopyAllocator = std::make_unique<SystemAllocator>(); if (!CopyAllocator->Initialize(Context, VideoParams)) { spdlog::error("D3DAllocator init failed: CopyAllocator->Initialize failed"); return false; } D3D = std::make_shared<D3D9Context>(); if (!D3D->Initialize(context)) { spdlog::error("D3DAllocator init failed: D3D->Initialize failed"); return false; } mfxStatus status = Context->Session.SetHandle(MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9, D3D->ManagerHandle); if (status < MFX_ERR_NONE) { spdlog::error("D3DAllocator init failed: Context->Session.SetHandle failed: {} {}", status, MfxStatusToString(status)); return false; } Allocator.pthis = this; Allocator.Alloc = [](mfxHDL pthis, mfxFrameAllocRequest* request, mfxFrameAllocResponse* response) -> mfxStatus { D3DAllocator* thiz = reinterpret_cast<D3DAllocator*>(pthis); return thiz->Alloc(request, response); }; Allocator.Free = [](mfxHDL pthis, mfxFrameAllocResponse* response) -> mfxStatus { D3DAllocator* thiz = reinterpret_cast<D3DAllocator*>(pthis); return thiz->Free(response); }; Allocator.Lock = [](mfxHDL pthis, mfxMemId mid, mfxFrameData* ptr) -> mfxStatus { D3DAllocator* thiz = reinterpret_cast<D3DAllocator*>(pthis); return thiz->Lock(mid, ptr); }; Allocator.Unlock = [](mfxHDL pthis, mfxMemId mid, mfxFrameData* ptr) -> mfxStatus { D3DAllocator* thiz = reinterpret_cast<D3DAllocator*>(pthis); return thiz->Unlock(mid, ptr); }; Allocator.GetHDL = [](mfxHDL pthis, mfxMemId mid, mfxHDL* handle) -> mfxStatus { D3DAllocator* thiz = reinterpret_cast<D3DAllocator*>(pthis); return thiz->GetHDL(mid, handle); }; status = Context->Session.SetFrameAllocator(&Allocator); if (status < MFX_ERR_NONE) { spdlog::error("D3DAllocator init failed: Mfx->Session.SetFrameAllocator failed: {} {}", status, MfxStatusToString(status)); return false; } Initialized = true; InitFailed = false; return true; } void D3DAllocator::Shutdown() { Service.Reset(); D3D.reset(); CopyAllocator.reset(); Context.reset(); AllocatorInitialized = false; Initialized = false; InitFailed = false; } mfxStatus D3DAllocator::Alloc(mfxFrameAllocRequest* request, mfxFrameAllocResponse* response) { std::lock_guard<std::mutex> locker(SurfacesLock); // Note: EncRequest.Type |= WILL_WRITE; // This line is only required for Windows DirectX11 to ensure that surfaces can be written to by the application if (request->Type & MFX_MEMTYPE_SYSTEM_MEMORY) { return MFX_ERR_UNSUPPORTED; } if (0 != (request->Type & MFX_MEMTYPE_FROM_ENCODE)) { spdlog::warn("Refusing to allocate encoder output with D3D: Expecting this in system memory"); return MFX_ERR_UNSUPPORTED; } // Ensure the allocator is initialized if (!InitializeAllocator(request)) { return MFX_ERR_MEMORY_ALLOC; } unsigned needed_count = request->NumFrameSuggested; if (needed_count < 1) { needed_count = 1; } // Allocate array (freed in Free() below) mfxMemId* mids = (mfxMemId*)calloc(needed_count, sizeof(mfxMemId)); if (!mids) { spdlog::error("calloc returned null"); return MFX_ERR_MEMORY_ALLOC; } core::ScopedFunction mids_scope([mids]() { free(mids); }); unsigned mid_write_next = 0; const unsigned surfaces_size = static_cast<unsigned>( Surfaces.size() ); for (unsigned i = 0; i < surfaces_size; ++i) { if (Surfaces[i]->Raw->IsLocked()) { continue; } mids[mid_write_next++] = Surfaces[i]->Mid; if (mid_write_next >= needed_count) { break; } } const unsigned allocate_count = needed_count - mid_write_next; if (allocate_count > 0) { const unsigned first_new_offset = static_cast<unsigned>( Surfaces.size() ); if (SharedHandlesEnabled) { for (unsigned i = 0; i < allocate_count; ++i) { const unsigned array_index = first_new_offset + i; const mfxMemId mid = ArrayIndexToMemId(array_index); std::shared_ptr<D3DVideoSurface> surface = std::make_shared<D3DVideoSurface>(); surface->Allocator = this; surface->Mid = mid; HRESULT hr = Service->CreateSurface( Width, Height, 0, // backbuffers Format, D3DPOOL_DEFAULT, Usage, DXVAType, &surface->VideoSurface, &surface->SharedHandle); if (FAILED(hr) || !surface->VideoSurface || !surface->SharedHandle) { spdlog::error("D3DAllocator: Service->CreateSurface failed: {}", HresultString(hr)); return MFX_ERR_MEMORY_ALLOC; } const auto& info = VideoParams.mfx.FrameInfo; surface->Raw = std::make_shared<RawFrame>(); surface->Raw->Surface.Info = info; surface->Raw->Surface.Data.MemId = mid; // Remember surface even if we end up not using it Surfaces.push_back(surface); mids[mid_write_next++] = mid; } } else { std::vector<IDirect3DSurface9*> surfs(allocate_count); HRESULT hr = Service->CreateSurface( Width, Height, allocate_count - 1, // backbuffers Format, D3DPOOL_DEFAULT, Usage, DXVAType, surfs.data(), nullptr); if (FAILED(hr)) { spdlog::error("D3DAllocator: Service->CreateSurface N={} failed: {}", allocate_count, HresultString(hr)); return MFX_ERR_MEMORY_ALLOC; } for (unsigned i = 0; i < allocate_count; ++i) { const unsigned array_index = first_new_offset + i; const mfxMemId mid = ArrayIndexToMemId(array_index); std::shared_ptr<D3DVideoSurface> surface = std::make_shared<D3DVideoSurface>(); surface->Allocator = this; surface->Mid = mid; surface->VideoSurface = surfs[i]; const auto& info = VideoParams.mfx.FrameInfo; surface->Raw = std::shared_ptr<RawFrame>(); surface->Raw->Surface.Info = info; surface->Raw->Surface.Data.MemId = mid; // Remember surface even if we end up not using it Surfaces.push_back(surface); mids[mid_write_next++] = mid; } } spdlog::debug("Allocated {} D3D surfaces: shared={}", allocate_count, SharedHandlesEnabled); } response->mids = mids; response->NumFrameActual = static_cast<mfxU16>( needed_count ); mids_scope.Cancel(); return MFX_ERR_NONE; } bool D3DAllocator::InitializeAllocator(mfxFrameAllocRequest* request) { unsigned dxva_type = 0; if (0 != (MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET & request->Type)) { dxva_type = DXVA2_VideoProcessorRenderTarget; } else if (0 != (MFX_MEMTYPE_DXVA2_DECODER_TARGET & request->Type)) { dxva_type = DXVA2_VideoDecoderRenderTarget; } else { spdlog::error("D3DAllocator: Request type unsupported: {}", request->Type); return false; } const D3DFORMAT format = D3DFormatFromFourCC(request->Info.FourCC); const bool shared_handles_enabled = (request->Type & MFX_MEMTYPE_EXTERNAL_FRAME) != 0; const unsigned width = request->Info.Width; const unsigned height = request->Info.Height; if (AllocatorInitialized) { if (dxva_type != DXVAType) { spdlog::error("D3DAllocator: DXVA type request mismatch {} != {}", dxva_type, DXVAType); return false; } if (format != Format) { spdlog::error("D3DAllocator: DXVA format request mismatch {} != {}", format, Format); return false; } if (shared_handles_enabled != SharedHandlesEnabled) { spdlog::error("D3DAllocator: SharedHandlesEnabled mismatch"); return false; } if (width != Width || height != Height) { spdlog::error("D3DAllocator: Resolution mismatch {}x{} != {}x{}", width, height, Width, Height); return false; } return true; } if (!D3D) { spdlog::error("D3DAllocator init failed: D3D is null"); return false; } Format = format; DXVAType = dxva_type; SharedHandlesEnabled = shared_handles_enabled; Width = width; Height = height; IID service_id = IID_IDirectXVideoDecoderService; if (dxva_type == DXVA2_VideoProcessorRenderTarget) { service_id = IID_IDirectXVideoProcessorService; } HRESULT hr = D3D->Manager->GetVideoService( D3D->DeviceHandle, service_id, (void**)Service.GetAddressOf()); if (FAILED(hr)) { spdlog::error("D3DAllocator init failed: Manager->OpenDeviceHandle failed: {}", HresultString(hr)); return false; } spdlog::debug("Initialized D3D9 video service for allocations"); AllocatorInitialized = true; return true; } mfxStatus D3DAllocator::Free(mfxFrameAllocResponse* response) { // Be lenient with API usage if (!response || !response->mids || response->NumFrameActual <= 0) { return MFX_ERR_NONE; } // We allocated the `mids` array so we will need to free() it core::ScopedFunction surfaces_scope([response]() { free(response->mids); }); const unsigned surface_count = response->NumFrameActual; for (unsigned i = 0; i < surface_count; ++i) { std::shared_ptr<D3DVideoSurface> surface = GetSurface(response->mids[i]); if (!surface) { continue; } // Error checking if (surface->Allocator != this || surface->Mid != response->mids[i]) { spdlog::error("D3DAllocator: Surface does not match allocator: Stale pointer?"); return MFX_ERR_INCOMPATIBLE_VIDEO_PARAM; } if (surface->Raw->RefCount <= 0) { spdlog::error("D3DAllocator: Surface double-free detected!"); continue; } } return MFX_ERR_NONE; } mfxStatus D3DAllocator::Lock(mfxMemId mid, mfxFrameData* ptr) { std::shared_ptr<D3DVideoSurface> surface = GetSurface(mid); if (!surface) { return MFX_ERR_INVALID_HANDLE; } if (!ptr) { spdlog::error("D3DAllocator: Lock ptr == null"); return MFX_ERR_LOCK_MEMORY; } D3DSURFACE_DESC desc{}; HRESULT hr = surface->VideoSurface->GetDesc(&desc); if (FAILED(hr)) { spdlog::error("D3DAllocator: pSurface->GetDesc failed: {}", HresultString(hr)); return MFX_ERR_LOCK_MEMORY; } D3DLOCKED_RECT locked{}; hr = surface->VideoSurface->LockRect(&locked, 0, D3DLOCK_NOSYSLOCK); if (FAILED(hr)) { spdlog::error("D3DAllocator: pSurface->LockRect failed: {}", HresultString(hr)); return MFX_ERR_LOCK_MEMORY; } switch ((DWORD)desc.Format) { case D3DFMT_NV12: case D3DFMT_P010: ptr->Pitch = (mfxU16)locked.Pitch; ptr->Y = (mfxU8 *)locked.pBits; ptr->U = (mfxU8 *)locked.pBits + desc.Height * locked.Pitch; ptr->V = (desc.Format == D3DFMT_P010) ? ptr->U + 2 : ptr->U + 1; break; case D3DFMT_YV12: ptr->Pitch = (mfxU16)locked.Pitch; ptr->Y = (mfxU8 *)locked.pBits; ptr->V = ptr->Y + desc.Height * locked.Pitch; ptr->U = ptr->V + (desc.Height * locked.Pitch) / 4; break; case D3DFMT_YUY2: ptr->Pitch = (mfxU16)locked.Pitch; ptr->Y = (mfxU8 *)locked.pBits; ptr->U = ptr->Y + 1; ptr->V = ptr->Y + 3; break; case D3DFMT_R8G8B8: ptr->Pitch = (mfxU16)locked.Pitch; ptr->B = (mfxU8 *)locked.pBits; ptr->G = ptr->B + 1; ptr->R = ptr->B + 2; break; case D3DFMT_A8R8G8B8: case D3DFMT_A2R10G10B10: ptr->Pitch = (mfxU16)locked.Pitch; ptr->B = (mfxU8 *)locked.pBits; ptr->G = ptr->B + 1; ptr->R = ptr->B + 2; ptr->A = ptr->B + 3; break; case D3DFMT_P8: ptr->Pitch = (mfxU16)locked.Pitch; ptr->Y = (mfxU8 *)locked.pBits; ptr->U = nullptr; ptr->V = nullptr; break; case D3DFMT_A16B16G16R16: ptr->V16 = (mfxU16*)locked.pBits; ptr->U16 = ptr->V16 + 1; ptr->Y16 = ptr->V16 + 2; ptr->A = (mfxU8*)(ptr->V16 + 3); ptr->PitchHigh = (mfxU16)((mfxU32)locked.Pitch / (1 << 16)); ptr->PitchLow = (mfxU16)((mfxU32)locked.Pitch % (1 << 16)); break; case D3DFMT_IMC3: ptr->Pitch = (mfxU16)locked.Pitch; ptr->Y = (mfxU8 *)locked.pBits; ptr->V = ptr->Y + desc.Height * locked.Pitch; ptr->U = ptr->Y + desc.Height * locked.Pitch *2; break; case D3DFMT_AYUV: ptr->Pitch = (mfxU16)locked.Pitch; ptr->V = (mfxU8 *)locked.pBits; ptr->U = ptr->V + 1; ptr->Y = ptr->V + 2; ptr->A = ptr->V + 3; break; #if (MFX_VERSION >= 1027) case D3DFMT_Y210: ptr->Pitch = (mfxU16)locked.Pitch; ptr->Y16 = (mfxU16 *)locked.pBits; ptr->U16 = ptr->Y16 + 1; ptr->V16 = ptr->Y16 + 3; break; case D3DFMT_Y410: ptr->Pitch = (mfxU16)locked.Pitch; ptr->Y410 = (mfxY410 *)locked.pBits; ptr->Y = nullptr; ptr->V = nullptr; ptr->A = nullptr; break; #endif } return MFX_ERR_NONE; } mfxStatus D3DAllocator::Unlock(mfxMemId mid, mfxFrameData* ptr) { std::shared_ptr<D3DVideoSurface> surface = GetSurface(mid); if (!surface) { return MFX_ERR_INVALID_HANDLE; } HRESULT hr = surface->VideoSurface->UnlockRect(); if (FAILED(hr)) { spdlog::warn("D3DAllocator: pSurface->UnlockRect failed: {}", HresultString(hr)); //return MFX_ERR_LOCK_MEMORY; } // Clear image data references if (ptr) { ptr->Pitch = 0; ptr->R = nullptr; ptr->G = nullptr; ptr->B = nullptr; ptr->A = nullptr; } return MFX_ERR_NONE; } mfxStatus D3DAllocator::GetHDL(mfxMemId mid, mfxHDL* ptr) { if (!ptr) { spdlog::error("D3DAllocator: GetHDL ptr == null"); return MFX_ERR_INVALID_HANDLE; } std::shared_ptr<D3DVideoSurface> surface = GetSurface(mid); if (!surface) { return MFX_ERR_INVALID_HANDLE; } *ptr = (mfxHDL)surface->VideoSurface; return MFX_ERR_NONE; } std::shared_ptr<D3DVideoSurface> D3DAllocator::GetSurface(mfxMemId mid) { if (!mid) { return nullptr; } const unsigned index = (unsigned)(uintptr_t)mid; std::lock_guard<std::mutex> locker(SurfacesLock); if (index > Surfaces.size()) { spdlog::error("D3DAllocator: GetSurface index out of bounds: mid={}", index); return nullptr; } return Surfaces[index - 1]; } frameref_t D3DAllocator::Allocate() { std::lock_guard<std::mutex> locker(SurfacesLock); const unsigned surfaces_size = static_cast<unsigned>( Surfaces.size() ); for (unsigned i = 0; i < surfaces_size; ++i) { auto& surface = Surfaces[i]; if (surface->Raw->IsLocked()) { continue; } // Reset CopyToSystemMemory surface->Raw->Surface.Data.Y = nullptr; // This increments the reference count return std::make_shared<FrameReference>(surface->Raw); } // FIXME: If we can combine all these then refactor later const unsigned array_index = static_cast<unsigned>( Surfaces.size() ); const mfxMemId mid = ArrayIndexToMemId(array_index); std::shared_ptr<D3DVideoSurface> surface = std::make_shared<D3DVideoSurface>(); surface->Allocator = this; surface->Mid = mid; HRESULT hr = Service->CreateSurface( Width, Height, 0, // backbuffers Format, D3DPOOL_DEFAULT, Usage, DXVAType, &surface->VideoSurface, SharedHandlesEnabled ? &surface->SharedHandle : nullptr); if (FAILED(hr) || !surface->VideoSurface) { spdlog::error("D3DAllocator: Service->CreateSurface failed: {}", HresultString(hr)); return nullptr; } const auto& info = VideoParams.mfx.FrameInfo; surface->Raw = std::make_shared<RawFrame>(); surface->Raw->Surface.Info = info; surface->Raw->Surface.Data.MemId = mid; Surfaces.push_back(surface); // This increments the reference count return std::make_shared<FrameReference>(surface->Raw); } frameref_t D3DAllocator::GetFrameById(mfxMemId mid) { std::shared_ptr<D3DVideoSurface> surface = GetSurface(mid); if (!surface) { return nullptr; } // Reset CopyToSystemMemory surface->Raw->Surface.Data.Y = nullptr; // This increments the reference count return std::make_shared<FrameReference>(surface->Raw); } frameref_t D3DAllocator::CopyToSystemMemory(mfx::frameref_t input_frame) { if (!input_frame) { return nullptr; } rawframe_t& input_raw = input_frame->Raw; if (!input_raw) { return nullptr; } frameref_t output_frame = CopyAllocator->Allocate(); if (!output_frame) { return nullptr; } rawframe_t& output_raw = output_frame->Raw; if (!output_raw) { return nullptr; } const mfxMemId mid = input_raw->Surface.Data.MemId; mfxFrameData data{}; mfxStatus status = Lock(mid, &data); if (status < MFX_ERR_NONE) { return false; } core::ScopedFunction lock_scope([this, mid, &data]() { Unlock(mid, &data); }); auto& info = input_raw->Surface.Info; const unsigned pitch = data.Pitch; const unsigned width = info.CropW; const unsigned height = info.CropH; const unsigned plane_bytes = width * height; if (pitch != width) { spdlog::error("D3D format pitch={} width={} unsupported", pitch, width); return false; } if (info.FourCC != MFX_FOURCC_NV12) { spdlog::error("D3D non-NV12 format unsupported: {}", info.FourCC); return false; } uint8_t* dest = output_raw->Data.data(); memcpy(dest, data.Y, plane_bytes); memcpy(dest + plane_bytes, data.UV, plane_bytes / 2); return output_frame; } } // namespace mfx #endif // _WIN32
31.007084
156
0.607166
[ "render", "vector" ]
e059345ee6d9a1df0d143be08ff303437dce97cd
8,495
cpp
C++
dialog.cpp
arutarimu/Smart-Security-Camera
121eee41d51ceb88dcb49419062953ac4fd6452f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
dialog.cpp
arutarimu/Smart-Security-Camera
121eee41d51ceb88dcb49419062953ac4fd6452f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
dialog.cpp
arutarimu/Smart-Security-Camera
121eee41d51ceb88dcb49419062953ac4fd6452f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include "dialog.h" #include "ui_dialog.h" #include "mainwindow.h" /*! * \brief Dialog::Dialog Constructor */ Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); ui->graphicsView->scene()->addItem(&pixmap); } /*! * \brief Dialog::~Dialog Deconstructor */ Dialog::~Dialog() { delete ui; } /*! * \brief loading XML files into Cascade classifier for face detection */ void Dialog::loadFiles() { nestedCascade.load("/home/pi/opencv_build/opencv/data/haarcascades/haarcascade_eye_tree_eyeglasses.xml"); cascade.load("/home/pi/opencv_build/opencv/data/haarcascades/haarcascade_frontalface_default.xml"); } /*! *\brief To capture or stop live video from USB webcam */ void Dialog::on_pushButton_clicked() { this->loadFiles(); if (capture.isOpened()) { ui->pushButton->setText("Start"); capture.release(); return; } capture.open(0); if(capture.isOpened()) { ui->pushButton->setText("Stop"); while(1) { capture >> frame; if (frame.empty()) break; frame1 = frame.clone(); this->detectAndDraw(frame1, cascade,nestedCascade, scale); //!< Detect face and draw circle around it qApp->processEvents(); } } else QMessageBox::about(this,"Error","camera not detected"); } /*! * \brief Dialog::detectAndDraw Detect face and draw circle around it * \param img current frame * \param cascade, For Detection eye if the person wearing eyeglass * \param nestedCascade, For human face detection * \param scale, scale of image from which face is searched */ void Dialog::detectAndDraw(cv::Mat &img, cv::CascadeClassifier &cascade, cv::CascadeClassifier nestedCascade, double scale) { std::vector<cv::Rect> faces, faces2; cv::Mat gray, smallImg; cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); // convert frame to gray scale double fx = 1 / scale; cv::resize(gray, smallImg, cv::Size(), fx, fx, cv::INTER_LINEAR); cv::equalizeHist(smallImg, smallImg); cascade.detectMultiScale(smallImg, faces, 1.1, 2, 0 | cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30)); // Detect faces in frame if (!faces.empty()) { ui->label_2->setText("Face Detected"); //change the status bar into FaceDetection if (ui->checkBox->isChecked()) // see the checkBox this->sendemail(); // send email notification } else { ui->label_2->setText(""); // update the status bar } for (size_t i = 0; i < faces.size(); i++) { cv::Rect r = faces[i]; cv::Mat smallImgROI; std::vector<cv::Rect> nestedObjects; cv::Point center; cv::Scalar color = cv::Scalar(255, 0, 0); // Color for Drawing tool int radius; double aspect_ratio = (double)r.width / r.height; if (0.75 < aspect_ratio && aspect_ratio < 1.3) { center.x = cvRound((r.x + r.width * 0.5) * scale); center.y = cvRound((r.y + r.height * 0.5) * scale); radius = cvRound((r.width + r.height) * 0.25 * scale); circle(img, center, radius, color, 3, 8, 0); } else rectangle(img, CvPoint(cvRound(r.x * scale), cvRound(r.y * scale)), cvPoint(cvRound((r.x + r.width - 1) * scale), cvRound((r.y + r.height - 1) * scale)), color, 3, 8, 0); if (nestedCascade.empty()) continue; smallImgROI = smallImg(r); // Detection of eyes int the input image nestedCascade.detectMultiScale(smallImgROI, nestedObjects, 1.1, 2, 0 | cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30)); // Draw circles around eyes for (size_t j = 0; j < nestedObjects.size(); j++) { cv::Rect nr = nestedObjects[j]; center.x = cvRound((r.x + nr.x + nr.width * 0.5) * scale); center.y = cvRound((r.y + nr.y + nr.height * 0.5) * scale); radius = cvRound((nr.width + nr.height) * 0.25 * scale); circle(img, center, radius, color, 3, 8, 0); } } QImage qimg(img.data, img.cols, img.rows, img.step, QImage::Format_RGB888); pixmap.setPixmap(QPixmap::fromImage(qimg.rgbSwapped())); ui->graphicsView->fitInView(&pixmap, Qt::KeepAspectRatio); } /*! * \brief Dialog::on_pushButton_add_clicked Add UserName and Password to Databse */ void Dialog::on_pushButton_add_clicked() { QString uu = ui->lineEdit_user->text(); QString pp = ui->lineEdit_pass->text(); std::ofstream fin; fin.open("DataBase.txt", std::ios::app); fin << uu.toStdString() << " " << pp.toStdString() << "\n"; QMessageBox::about(this, "DataBase", "UserName and Password added to DataBase"); fin.close(); } /*! * \brief Dialog::on_pushButton_2_clicked Display Database into the GUI */ void Dialog::on_pushButton_2_clicked() { QString filename = "DataBase.txt"; QFile ff(filename); if (!ff.exists()) { qDebug() << "File cannot be found" << filename; } else { { qDebug() << filename << "openning ..."; } QString line; ui->textEdit->clear(); if(ff.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&ff); while(!stream.atEnd()) { line = stream.readLine(); ui->textEdit->setText(ui->textEdit->toPlainText() + line + "\n"); //qDebug() << "line: " << line; } } ff.close(); } } /*! * \brief Dialog::on_pushButton_3_clicked Hide the DataBase shown in GUI */ void Dialog::on_pushButton_3_clicked() { ui->textEdit->clear(); } static size_t payload_source(void* ptr, size_t size, size_t nmemb, void* userp) { struct upload_status { int lines_read; }; static const char* payload_text[] = { "Date: Mton, 29 Nov 2010 21:54:29 +1100\r\n", "To: " "\r\n", "From: " " \r\n", "Cc: " " (Another example User)\r\n", "Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@" "rfcpedant.example.org>\r\n", "Subject: Notification Smart Security\r\n", "\r\n", /* empty line to divide headers from body, see RFC5322 */ "Person at the door.\r\n", "\r\n", NULL }; struct upload_status* upload_ctx = (struct upload_status*)userp; const char* data; if ((size == 0) || (nmemb == 0) || ((size * nmemb) < 1)) { return 0; } data = payload_text[upload_ctx->lines_read]; if (data) { size_t len = strlen(data); memcpy(ptr, data, len); upload_ctx->lines_read++; return len; } return 0; } /*! * \brief Dialog::sendemail() Responsible for sending email */ void Dialog::sendemail() { struct upload_status { int lines_read; }; CURL* curl; CURLcode res = CURLE_OK; struct curl_slist* recipients = NULL; struct upload_status upload_ctx; upload_ctx.lines_read = 0; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_USERNAME, "learncppuwo@gmail.com"); curl_easy_setopt(curl, CURLOPT_PASSWORD, "123654789@abc"); curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:587"); curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL); //curl_easy_setopt(curl, CURLOPT_CAINFO, "C:/repos/Email_Notif/curl-7.66.0-win64-mingw/bin/curl-ca-bundle.crt"); curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM); recipients = curl_slist_append(recipients, TO); recipients = curl_slist_append(recipients, CC); curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); res = curl_easy_perform(curl); if (res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res)); curl_slist_free_all(recipients); curl_easy_cleanup(curl); } }
29.911972
123
0.588935
[ "vector" ]
e05d4ede342cfd343dcba0986ff1dd6608725d96
8,826
cpp
C++
testsuite/TStoredQueryConfig.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
null
null
null
testsuite/TStoredQueryConfig.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
2
2018-04-17T10:02:46.000Z
2019-10-21T08:57:55.000Z
testsuite/TStoredQueryConfig.cpp
nakkim/smartmet-plugin-wfs
851334dd3be1a24b9708f66696f088fdc857a999
[ "MIT" ]
2
2017-05-10T12:03:51.000Z
2021-07-06T07:05:25.000Z
#define BOOST_TEST_MODULE TStoredQueryConfig #define BOOST_TEST_DYN_LINK 1 #include <boost/test/unit_test.hpp> #include <array> #include "ArrayParameterTemplate.h" #include "RequestParameterMap.h" #include "ScalarParameterTemplate.h" #include "StoredQueryConfig.h" #include "WfsException.h" #include "ConfigBuild.h" using namespace boost::unit_test; using SmartMet::Plugin::WFS::RequestParameterMap; test_suite* init_unit_test_suite(int argc, char* argv[]) { const char* name = "StoredQueryConfig tester (parameter support)"; unit_test_log.set_threshold_level(log_messages); framework::master_test_suite().p_name.value = name; BOOST_TEST_MESSAGE(""); BOOST_TEST_MESSAGE(name); BOOST_TEST_MESSAGE(std::string(std::strlen(name), '=')); return NULL; } #if 0 namespace { void log_error() { try { throw; } catch (const std::exception& err) { std::cerr << "C++ exception of type " << Fmi::current_exception_type() << ": " << err.what() << std::endl; throw; } catch (...) { std::cerr << "C++ exception of type " << Fmi::current_exception_type(); throw; } } } #endif #define NO_THROW(x) \ try \ { \ x; \ } \ catch (...) \ { \ BOOST_REQUIRE_NO_THROW(log_error()); \ } // This procedure is here only for putting breakpoint in it void dummy_proc(const char* text) { (void)text; } namespace bw = SmartMet::Plugin::WFS; namespace pt = boost::posix_time; using SmartMet::Spine::Value; using libconfig::Setting; using Test::TestConfig; using Test::add_values; typedef boost::shared_ptr<bw::StoredQueryConfig> StoredQueryConfigP; typedef boost::shared_ptr<bw::ScalarParameterTemplate> ScalarParameterTemplateP; typedef boost::shared_ptr<bw::ArrayParameterTemplate> ArrayParameterTemplateP; #if 0 BOOST_AUTO_TEST_CASE(test_config_create) { BOOST_TEST_MESSAGE("+ [Create test config]"); boost::shared_ptr<TestConfig> raw_config(new TestConfig); raw_config->add_param("foo", "xxx", "string") .min_occurs(1) .max_occurs(1); raw_config->add_param("bar", "xxx", "string[0..4]") .min_occurs(0) .max_occurs(1); raw_config->add_scalar("foo", "${foo}"); raw_config->add_array<3>("bar", {{"foo", "bar", "baz"}}); //SmartMet::Spine::ConfigBase::dump_config(std::cout, *raw_config); } #endif /****************************************************************************************/ BOOST_AUTO_TEST_CASE(test_single_scalar_parameter_without_default) { dummy_proc(__PRETTY_FUNCTION__); BOOST_TEST_MESSAGE("+ [Single scalar parameter without default value]"); boost::shared_ptr<TestConfig> raw_config(new TestConfig); raw_config->add_param("foo", "xxx", "int"); raw_config->add_scalar("p", "${foo}"); int val; RequestParameterMap param_map; StoredQueryConfigP config; ScalarParameterTemplateP param; // SmartMet::Spine::ConfigBase::dump_config(std::cout, *raw_config); BOOST_REQUIRE_NO_THROW(config.reset(new bw::StoredQueryConfig(raw_config, nullptr))); BOOST_REQUIRE_NO_THROW(param.reset(new bw::ScalarParameterTemplate(*config, "p"))); // No mandatory parameter provided BOOST_REQUIRE_THROW(param->get<int64_t>(param_map), Fmi::Exception); // Single parameter provided (must succeed) std::array<int, 1> i001 = {{123}}; Test::add_values<int, 1>(param_map, "foo", i001); BOOST_REQUIRE_NO_THROW(val = param->get<int64_t>(param_map)); BOOST_CHECK_EQUAL(123, val); // Too many parameters provided std::array<int, 1> i002 = {{321}}; Test::add_values<int, 1>(param_map, "foo", i002); BOOST_REQUIRE_THROW(param->get<int64_t>(param_map), Fmi::Exception); } /****************************************************************************************/ BOOST_AUTO_TEST_CASE(test_single_scalar_parameter_with_default_value) { dummy_proc(__PRETTY_FUNCTION__); BOOST_TEST_MESSAGE("+ [Single scalar parameter with default value]"); boost::shared_ptr<TestConfig> raw_config(new TestConfig); raw_config->add_param("foo", "xxx", "int"); raw_config->add_scalar("p", "${foo : 512}"); int val; RequestParameterMap param_map; StoredQueryConfigP config; ScalarParameterTemplateP param; // SmartMet::Spine::ConfigBase::dump_config(std::cout, *raw_config); BOOST_REQUIRE_NO_THROW(config.reset(new bw::StoredQueryConfig(raw_config, nullptr))); BOOST_REQUIRE_NO_THROW(param.reset(new bw::ScalarParameterTemplate(*config, "p"))); // No mandatory parameter provided BOOST_REQUIRE_NO_THROW(val = param->get<int64_t>(param_map)); BOOST_CHECK_EQUAL(512, val); // Single parameter provided (must succeed) std::array<int, 1> i001 = {{123}}; Test::add_values<int, 1>(param_map, "foo", i001); BOOST_REQUIRE_NO_THROW(val = param->get<int64_t>(param_map)); BOOST_CHECK_EQUAL(123, val); // Too many parameters provided std::array<int, 1> i002 = {{321}}; Test::add_values<int, 1>(param_map, "foo", i002); BOOST_REQUIRE_THROW(param->get<int64_t>(param_map), Fmi::Exception); } /****************************************************************************************/ BOOST_AUTO_TEST_CASE(test_single_scalar_parameter_with_lower_limit) { dummy_proc(__PRETTY_FUNCTION__); BOOST_TEST_MESSAGE("+ [Single scalar parameter with lower limit specified]"); boost::shared_ptr<TestConfig> raw_config(new TestConfig); raw_config->add_param("foo", "xxx", "time").lower_limit("2012-01-01T00:00:00Z"); raw_config->add_scalar("p", "${foo}"); pt::ptime val; RequestParameterMap param_map; StoredQueryConfigP config; ScalarParameterTemplateP param; // SmartMet::Spine::ConfigBase::dump_config(std::cout, *raw_config); BOOST_REQUIRE_NO_THROW(config.reset(new bw::StoredQueryConfig(raw_config, nullptr))); BOOST_REQUIRE_NO_THROW(param.reset(new bw::ScalarParameterTemplate(*config, "p"))); // No mandatory parameter provided BOOST_CHECK_THROW(val = param->get<pt::ptime>(param_map), Fmi::Exception); // Single parameter provided and is in allowed range (must succeed) std::array<std::string, 1> s001 = {{"2012-01-02T00:11:22Z"}}; Test::add_values<std::string, 1>(param_map, "foo", s001); BOOST_REQUIRE_NO_THROW(val = param->get<pt::ptime>(param_map)); BOOST_CHECK_EQUAL(std::string("2012-Jan-02 00:11:22"), pt::to_simple_string(val)); // Single parameter provided and is out of allowed range (must succeed) std::array<std::string, 1> s002 = {{"2011-12-31T00:11:22Z"}}; Test::add_values<std::string, 1>(param_map, "foo", s002); BOOST_CHECK_THROW(val = param->get<pt::ptime>(param_map), Fmi::Exception); // Too many values provided std::array<std::string, 1> s003 = {{"2013-06-23T00:11:22Z"}}; Test::add_values<std::string, 1>(param_map, "foo", s003); BOOST_CHECK_THROW(param->get<int64_t>(param_map), Fmi::Exception); } /****************************************************************************************/ BOOST_AUTO_TEST_CASE(test_single_mandatory_array_parameter_with_fixed_length) { dummy_proc(__PRETTY_FUNCTION__); BOOST_TEST_MESSAGE("+ [Single mandatory array parameter of constant size]"); boost::shared_ptr<TestConfig> raw_config(new TestConfig); raw_config->add_param("foo", "xxx", "double[2]").min_occurs(1).max_occurs(1); std::array<std::string, 1> p001 = {{"${foo}"}}; raw_config->add_array<1>("p", p001); std::vector<double> data; RequestParameterMap param_map; StoredQueryConfigP config; ArrayParameterTemplateP param; // SmartMet::Spine::ConfigBase::dump_config(std::cout, *raw_config); BOOST_REQUIRE_NO_THROW(config.reset(new bw::StoredQueryConfig(raw_config, nullptr))); BOOST_REQUIRE_NO_THROW(param.reset(new bw::ArrayParameterTemplate(*config, "p", 2, 2))); // Mandatory array with 2 elements required not provided at all BOOST_CHECK_THROW(param->get_double_array(param_map), Fmi::Exception); // Mandatory array with 2 elements required but only 1 provided std::array<int, 1> i001 = {{123}}; Test::add_values<int, 1>(param_map, "foo", i001); BOOST_CHECK_THROW(param->get_double_array(param_map), Fmi::Exception); // Mandatory array with 2 elements required, 2 provided std::array<int, 1> i002 = {{321}}; Test::add_values<int, 1>(param_map, "foo", i002); BOOST_CHECK_NO_THROW(data = param->get_double_array(param_map)); BOOST_CHECK_EQUAL(2, (int)data.size()); if (data.size() == 2) { BOOST_CHECK_EQUAL(123.0, data.at(0)); BOOST_CHECK_EQUAL(321.0, data.at(1)); } // Mandatory array with 2 elements required, too many provided std::array<int, 1> i003 = {{999}}; Test::add_values<int, 1>(param_map, "foo", i003); BOOST_CHECK_THROW(param->get_double_array(param_map), Fmi::Exception); }
34.342412
96
0.674484
[ "vector" ]
e05de9e42771b3e94efa0a8db57b0d2e7d80fc8f
5,789
cpp
C++
Diff/Diff.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
Diff/Diff.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
Diff/Diff.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//---------------------------------- // (c) Reliable Software 1997 - 2007 //---------------------------------- #include "precompiled.h" #include "Diff.h" #include "DiffRecord.h" #include "CluSum.h" #include "LineCounter.h" #include "ListingWin.h" #include <Ctrl/ProgressMeter.h> #include <File/MemFile.h> #include <Ex/WinEx.h> #include <HashTable.h> int MakePrimish (int x) { // Note: Mersenne primes are numbers that // are one less than 2 to the power of a prime number. // They are not always primes and here // we don't even raise 2 to a prime power, but so what! // It's good enough for a primish number int i; for (i = 0; i < sizeof (int) * 8; i++) { if (x) x >>= 1; else break; } return (1 << i) - 1; } Differ::Differ (char const * bufOld, int lenOld, char const * bufNew, int lenNew, Comparator & comp, Progress::Meter & meter, EditStyle::Source src) : _linesOld (bufOld, lenOld), _linesNew (bufNew, lenNew), _clusterer (_linesOld, _linesNew), _comp (comp), _lenOld (lenOld), _lenNew (lenNew), _src (src), _iStart (0), _iTail (0), _badLines (_linesNew.Count (), false) { int oldCount = _linesOld.Count (); int newCount = _linesNew.Count (); // skip initial similar lines int iEnd = std::min (oldCount, newCount); while (_iStart < iEnd) { Line * line1 = _linesOld.GetLine (_iStart); Line * line2 = _linesNew.GetLine (_iStart); if (!comp.IsSimilar (line1, line2)) break; line2->AddSimilar (0); ++_iStart; } // skip trailing similar lines while (oldCount - _iTail > _iStart && newCount - _iTail > _iStart) { Line * line1 = _linesOld.GetLine (oldCount - _iTail - 1); Line * line2 = _linesNew.GetLine (newCount - _iTail - 1); if (!comp.IsSimilar (line1, line2)) break; line2->AddSimilar (newCount - oldCount); ++_iTail; } CompareLines (oldCount, newCount, comp, meter); if (newCount > THRESHOLD_LINE_COUNT) PrepareOptimisation (); // do the clustering _clusterer.PickUniqueClusters (meter, _badLines, comp); } void Differ::CompareLines (int oldCount, int newCount, Comparator & comp, Progress::Meter & meter) { int size = 1; if (oldCount - _iStart - _iTail > 0) size = MakePrimish (oldCount - _iStart - _iTail); // hash all the lines of the old file Hash::Table hTable (size); for (int i = _iStart; i < oldCount - _iTail; ++i) { Line * line = _linesOld.GetLine (i); hTable.Add (i, line->Buf (), line->Len ()); } // find old lines similar to New lines meter.SetActivity ("Finding similar lines"); meter.SetRange (0, newCount - _iTail - _iStart, 1); for (int j = _iStart; j < newCount - _iTail; ++j) { Line * lineNew = _linesNew.GetLine (j); using Hash::ShortIter; for (ShortIter it (hTable, lineNew->Buf (), lineNew->Len ()); !it.AtEnd (); it.Advance ()) { if (newCount > CRITICAL_LINE_COUNT) { // optimisation for larges files: // Above CRITICAL_LINE_COUNT lines, the search simimilar lines is limited to |shift| <= CRITICAL_SHIFT if (std::abs (j - it.GetValue ()) > CRITICAL_SHIFT) continue; } // it.GetValue () returns line number Line * lineOld = _linesOld.GetLine (it.GetValue ()); if (comp.IsSimilar (lineOld, lineNew)) { // distance to similar line lineNew->AddSimilar (j - it.GetValue ()); } } meter.StepAndCheck (); } } void Differ::Record (DiffRecorder & recorder) { ClusterSort sortedClusters (_clusterer.GetClusterSeq ()); sortedClusters.SortByNewLineNo (); int count = sortedClusters.Count (); for (int i = 0; i < count; i++) { Cluster const * cluster = sortedClusters [i]; int oldL = cluster->OldLineNo (); int newL = cluster->NewLineNo (); int len = cluster->Len (); if (oldL == -1) { recorder.AddCluster (*cluster); // an added line for (int j = 0; j < len; j++) { Line * line = _linesNew.GetLine (newL + j); recorder.AddNewLine (newL + j, *line); } } else if (newL == -1) { // store deleted lines for redundancy // and to be able to go back recorder.AddCluster (*cluster); // a deleted line for (int j = 0; j < len; j++) { Line * line = _linesOld.GetLine (oldL + j); recorder.AddOldLine (oldL + j, *line); } } else { recorder.AddCluster (*cluster); } } } void Differ::Dump (ListingWindow & listWin, LineCounter & counter, Progress::Meter & meter) { ClusterSum cluSum (*this); meter.SetActivity ("Merging lines"); meter.SetRange (0, cluSum.TotalCount (), 1); while (!cluSum.AtEnd ()) { cluSum.DumpCluster (listWin, _src, counter); cluSum.Advance (); meter.StepAndCheck (); } } void Differ::PrepareOptimisation () { int const totalCount = _linesNew.Count (); Assert (totalCount > THRESHOLD_LINE_COUNT); // find the "bad" lines (with frequency over 2%) // Bad line: 100 * similarCount / totalCount > THRESHOLD_PERCENTAGE // or: similarCount > THRESHOLD_PERCENTAGE * totalCount / 100 unsigned maxSimilar = totalCount / 100; Assert (maxSimilar > 0); maxSimilar *= THRESHOLD_PERCENTAGE; std::vector<bool>::iterator it = _badLines.begin (); for (int i = 0; it != _badLines.end (); ++it, ++i) { Line const * lineNew = _linesNew.GetLine (i); unsigned similarCount = lineNew->GetShifts ().size (); if ( similarCount > 0 && similarCount > maxSimilar) { *it = true; // this line is bad } } // protection from exceptional event : too many bad lines for (int k = 0; k < totalCount - MAX_BAD_LINE_STRETCH; k += MAX_BAD_LINE_STRETCH) { std::vector<bool>::iterator itStart = _badLines.begin () + k; std::vector<bool>::iterator itEnd = _badLines.begin () + k + MAX_BAD_LINE_STRETCH; if (std::find (itStart, itEnd, false) == itEnd) // All "bad" *itStart = false; // mark starting line of the bad stretch as good } }
27.436019
106
0.641734
[ "vector" ]
e06276e78ba441ca2a303a30f8caf2e9d1a127bc
33,520
cxx
C++
src/mirorr/mirorr.cxx
NicholasDowson/Mirorr
1d4b1506613129a566fdb8532d3031c3c29cc626
[ "MIT", "Unlicense" ]
null
null
null
src/mirorr/mirorr.cxx
NicholasDowson/Mirorr
1d4b1506613129a566fdb8532d3031c3c29cc626
[ "MIT", "Unlicense" ]
null
null
null
src/mirorr/mirorr.cxx
NicholasDowson/Mirorr
1d4b1506613129a566fdb8532d3031c3c29cc626
[ "MIT", "Unlicense" ]
null
null
null
/*========================================================================= Program: mirorr Module: mirorr.cxx Author: David Rivest-Henault and Nicholas Dowson Created: Mon 11 Feb 2009 Copyright (c) 2009-15 CSIRO. All rights reserved. For complete copyright, license and disclaimer of warranty information see the LICENSE.txt file for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // File for running mirorr registration using an image pyramid. See // comments below for more details. // Revised: 09 Sep 2014 by D Rivest-Henault. Merged new improved GPU Block Matcher // Revised: 26 May 2014 by D Rivest-Henault. More resampling space options // Revised: 04 Apr 2014 by D Rivest-Henault. Handling of non-identity cosine matrix in image headers // Revised: 15 Oct 2013 by D Rivest-Henault. Using intermediate space in classic mode // Revised: 30 Jan 2013 by D Rivest-Henault. Added help for using the --use-gpu-bm on a multi GPUs system // Revised: 15 Dec 2012 by D Rivest-Henault. Added --reg-mod and --nthreads options // Revised: 10 Aug 2010 by N Dowson. Added explicit masking // Revised: 13 Oct 2009 by N Dowson. Removed Transform as template parameter // Revised: 12 Oct 2009 by N Dowson. Added equivalent of -py option and // ability to save resampled fixed image after registration. // Revised: 17 Sep 2009 by N Dowson. Switched moving fixed in naming // convention to align with ITK, plus a host of little things to improve // usability and reduce annoyances. // Revised: 13 Jul 2009 by N Dowson. Modification to set translation // of translation using set offset // Revised: 12 Jun 2009 by N Dowson. Customise various things. Renamed // Revised: 25 Mar 2009 by N Dowson. Added various transformations // Revised: 13 May 2009 by N Dowson. Can read in and output transform files // Revised: 20 Mar 2009 by N Dowson. Can now choose input files. // Revised: 19 Mar 2009 by N Dowson. Generalised to 3D // Revised: 19 Mar 2009 by N Dowson. First version. #include <iostream> #include <string> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <time.h> #include <sys/types.h> #if defined(WIN32) #include <process.h> #endif #include <itkMultiThreader.h> #include <itkImageIOBase.h> #include "itkMirorrPyramidWrapper.h" // By default, a rigid transformation is used. // // If no starting transformation is specified, the algorithm is // initialised so that the two image centres overlap, and the initial // transformation is saved to the name of the fixed image appended // with tfmInitial.tfm. Likewise if no file for storing the final // transform (after registration is specified, the fixed image is // appended with tfmFinal.tfm. // // The algorithm relies on extracting blocks from the moving image and // matching them to the most similar one of the nearby blocks of the // same size (and resolution) in the fixed image. Only those blocks in // the moving image with the greatest with their matching block in the // fixed image are retained. Each of the remaining matches gives a // suggested transformation. The global tranform agreeing with the // majority of suggested translations is then found. Several // iterations are performed at each image scale or resolution at which // the images are being viewed. // // If the \emph{help} argument is used, a short help message is // displayed, but nothing is done. If the \emph{verbose} argument is // specified, the status of the algorithm is updated in the command // line window. This of course may be piped to some test output file // using pipe command \emph{e.g.} milxMirorr args $>$ output.txt. /*! * \page CommandLine * \section mirorr * mirorr is a command line application to register * pairs of 3D images using linear transforms. * * Type mirorr --help for help. */ int main( int argc, char* argv[] ) { namespace po = boost::program_options; namespace fs = boost::filesystem; //Defaults ============================================================ // Declare the supported options. po::options_description all_options( "mirorr\n\n" "Synopsis: The command line interface to a robust registration " "algorithm based on block matching. The algorithm seeks a transform " "from a 'moving' to a 'fixed' image that best aligns the two.\n" "Usage:\n" " mirorr movingImage fixedImage [final.tfm] [start.tfm] ... \n\n" "Other examples:\n" " To apply transform to moving image:\n" " mirorr movingImage fixedImage last.tfm -R --save-reoriented-moving moving_tfmd.nii.gz\n" " To apply inverse transform to fixed image:\n" " mirorr movingImage fixedImage last.tfm -R --save-reoriented-fixed fixed_tfmd.nii.gz\n" " To run fresh registration from a baseline, save moving inplace, and subsequently refine registration:\n" " mirorr moving.nii.gz fixed.nii.gz last.tfm --fresh --reorient-moving --save-reoriented-moving moving.nii.gz\n" " mirorr moving.nii.gz fixed.nii.gz last.tfm refined.tfm --reorient-moving --save-reoriented-moving moving.nii.gz\n" " To reset fixed (or moving) image to identity orientation " "(Useful for baselining fixed image if reorient-fixed was used before):\n" " # mirorr movingImage fixedImage last.tfm --reorient-fixed ## From before\n" " mirorr movingImage fixedImage --fresh --reorient-fixed -R -0 --save-reoriented-fixed baselineFixed.nii.gz\n" ); po::options_description general_options( "General options to set input and output images and transforms"); general_options.add_options() ("moving,m", po::value<std::string>(), "Specify Moving Image") ("fixed,f", po::value<std::string>(), "Specify Fixed Image") ("last-tfm,l", po::value<std::string>()->default_value( std::string("") ), // "File with optimised transformation from moving to fixed image.") ("start-tfm,s", po::value<std::string>()->default_value( std::string("") ), "File with initial transformation (will not be overwritten unless it is the same as last-tfm)") ("tfm-type,t", po::value<std::string>()->default_value("rigid"), "Type of transformation: rigid/affine") ("reg-mode", po::value<std::string>()->default_value("symmetric"), "Registration mode: classic/symmetric") ("do-not-register,R", "Do not run registration, just use transform file to resample the " "fixed and/or moving image.") ("save-reoriented-fixed", po::value<std::string>(), "Save fixed image (in moving image space) after registration. " "If rigid transform, only direction & origin updated, no resampling " "occurs.") ("save-reoriented-moving", po::value<std::string>(), "Save moving image (in fixed image space) after registration. " "If rigid transform, only direction & origin updated, no resampling " "occurs.") ("save-resampled-fixed", po::value<std::string>(), "Save fixed image (resampling on moving image's space and grid) " "after registration. ") ("save-resampled-moving", po::value<std::string>(), "Save moving image (resampling on fixed image's space and grid) " "after registration. ") ("final-interpolator", po::value<std::string>()->default_value("bspline"), "Type of interpolator used to save the final resampled images. Valid options: " "nn, linear, bspline, sinc") ("moving-mask,M", po::value<std::string>()->default_value(""), "Specify Moving Image") ("fixed-mask,F", po::value<std::string>()->default_value(""), "Specify Fixed Image") ("switch-images,S", "Switch images, so transform is from fixed to moving image. " "DEPRECATED - No longer needed with symmetric approach") ("invert-last-tfm,I", "Invert output transform. (Maybe use it with --invert-start-tfm)") ("invert-start-tfm,i", "Invert input transform. (Maybe use it with --invert-last-tfm)") ("nthreads", po::value<int>()->default_value(0), "Number of block matching threads. " "Default is 1 thread per available CPU core.") ("echo-cmd", "Echo the command line. Useful for logging.") ("fresh", "PREVENT use of output tfm as an input if it exists. By default " "if no input is provided and the output exists the output is " "used as an input.") ("help,h", "Produce help message") ("verbose,v", "Request extra verbose output") ("quiet,q", "Request quiet output") ; po::options_description algorithm_options( "Algorithm Options\n" "Control the registration algorithm. \nA hierarchical approach is " "used on an image pyramid. By convention pyramid level 1 indicates " "the moving image is resampled to a resolution of >=16^3. Each increase " "indicates a doubling of resolution. The maximum level ensures the " "moving image is not downsampled at all. The resolutions of the two " "images are matched to ensure approximately equal spacing. " "Zero gives default.\nThe number of block matching iterations may " "also be applied, as can the fraction of image blocks that are " "considered (Low image content blocks are ignored)."); algorithm_options.add_options() ("pyr-start,a", po::value<int>()->default_value(1), "First pyramid level to be processed. (-ve numbers count back from max.)") ("pyr-switch,b", po::value<int>()->default_value(0), // "DEPRECATED Last pyramid level of block matching. Following levels use ITK Mutual " "info. (-ve numbers count back from max. 0==max) DEPRECATED") ("pyr-end,c", po::value<int>()->default_value(0), // "Last pyramid level to be processed. (-ve numbers count back from max. " "0==max)") ("pyr-num,d", po::value<int>()->default_value(1024), "Number of levels in the pyramid (default is to create as many levels " "as maxDataSize > 32)") ("pyr-min-size,e", po::value<int>()->default_value(32), "Minimal image dimension at the first level of the pyramid") ("resampling-mode", po::value<std::string>()->default_value("middle"), //valid: basic, middle, max-resolution, max-size "Inner loop resampling mode: basic, middle, max-resolution, max-size, " "fixed, moving") ("no-bm", "Do not use block matching algorithm (primary registration)") ("use-itk", "DEPRECATED Do not use mutual information maximisation (refining / secondary registration) DEPRECATED") ("iterations,n", po::value<int>()->default_value(0), "Number of iterations. Set negative to halve iterations each pyramid level") ("portion-kept", po::value<double>()->default_value(0.5), "Portion of image, by volume, to consider.") #ifdef USE_OPENCL ("use-gpu-bm", "Use the GPU blockmatcher. This is much faster, but being tested." "When using this GPU implementation on a multi GPUs CUDA system, the " "CUDA_VISIBLE_DEVICES environment variable should be used to restrict the " "visibility of the GPUs to the ones you want to use. " "Specificaly on \"bragg-l.csiro.au\", it is advisable to place the following " "line in your script:" "\"export CUDA_VISIBLE_DEVICES=`gpu-which | sed 's/\"//g'`\"") // #endif ("reorient-fixed", "Reorient fixed image in the RAI direction first, and set to reset " "position with identity directions and zero origin. This enables " "in-place image modification with re-use old transforms.") ("reorient-moving", "Reorient moving image in the RAI direction first, and set to reset " "position with identity directions and zero origin. This enables " "in-place image modification with re-use old transforms.") ("save-fixed", po::value<std::string>(), "Save fixed image (in moving image space) after registration. " "If rigid transform, only direction & origin updated, no resampling " "occurs. DEPRECATED - will be replaced by --save-resampled-fixed") ("save-moving", po::value<std::string>(), "Save moving image (in fixed image space) after registration. " "If rigid transform, only direction & origin updated, no resampling " "occurs. DEPRECATED - will be replaced by --save-resampled-moving") ("no-centering-init,0", "Turn off initialisation of transform to overlap image centres.") ("blockmetric", po::value<std::string>()->default_value("nc"), "metric used: normalized correlation (nc), sum of squared differences (sd), " "correlation ratio (cr), non-parametric window mutual information (mi)" #ifdef USE_NPW ", np windows mutual information (npwmi)" #endif ) #ifdef USE_NPW ("npw-bins", po::value<int>()->default_value(32), "the number of bins in the histogram used by the NPW MI metric" ) #ifndef USE_OPENCL ("npw-scale-factor", po::value<int>()->default_value(2), "render on a bigger framebuffer and scale this down to reduce render error " "this number specifies how many times bigger the framebuffer is" ) ("npw-shape-expansion", "expands shapes when rendering reducing rasterization error " "if it is off (default), the histogram is normalized afterwards" ) #endif #endif ("nhoodwidth", po::value<int>()->default_value(7), "Width of block matching neighbourhood (number of blocks tested along one edge of the neighbourhood [=7])") ("nhoodgap", po::value<int>()->default_value(3), "Gap between block matching neighbourhoods (origin BM space, in pixels [=3])") ("blockwidth", po::value<int>()->default_value(4), "Size of blocks (pixels [=4])") ("blockgap", po::value<int>()->default_value(1), "Gap between blocks in neighbourhood (search BM space, in pixels [=1])") ("itk-srate,z", po::value<double>()->default_value(0.11), "Sample rate for ITK registration (z). Actual sample rate " "is min(n_pixels,max(z*n_pixels,k*bins^.33)") ("itk-metric", po::value<std::string>()->default_value("mmi"), // "metric used: Mattes mutual information (mmi), normalized cross-correlation (ncc), " "gradient difference (gd), Viola and Well mutual information (mi)") ; all_options.add(general_options).add(algorithm_options); //f F h H l L m M n q R s S t v b po::positional_options_description positionalDescription; positionalDescription.add("moving", 1).add("fixed",1).add("last-tfm",1).add("start-tfm",1); po::variables_map variablesMap; po::store(po::command_line_parser(argc, argv). options(all_options). positional(positionalDescription).run(), variablesMap); po::notify(variablesMap); //Opening text ======================================================== time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); std::cout << "------------------------------------------------------------------------\n" << "- CSIRO Mirorr (c) 2009-2015 -\n" << "------------------------------------------------------------------------\n" << "Multimodal Image Registration using blOck-matching and Robust Regression\n" << "By: David Rivest-Henault, Nicholas Dowson, and the AEHRC team\n" << "Build time stamp: <" << __DATE__ << "-" << __TIME__ << ">\n" << "Current time is: " << asctime (timeinfo) << "------------------------------------------------------------------------\n"; //Parse options ======================================================= if (variablesMap.count("echo-cmd")) { #if defined(WIN32) std::cout<<"PID: " << _getpid() << std::endl; #else std::cout<<"PID: " << getpid() << std::endl; #endif for( int ii =0; ii<argc; ++ii ) std::cout << argv[ii] << " " ; std::cout<< std::endl; } else { std::cout << "(use --echo-cmd to get more process information)" << std::endl; } std::cout << "------------------------------------------------------------------------\n" << std::endl; if (variablesMap.count("help")) { std::cout << all_options << std::endl << std::endl; return 1; } //The names of the moving and fixed files are mandatory if( !variablesMap.count("moving") ) { std::cerr << "No moving image supplied. " "Type 'mirorr --help' for usage." <<std::endl; return -1; } if( !variablesMap.count("fixed") ) { std::cerr << "No fixed image supplied. " "Type 'mirorr --help' for usage."<<std::endl; return -1; } //Check dimensionality of input images itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(variablesMap["moving"].as<std::string>().c_str(), itk::ImageIOFactory::ReadMode); //Check file exists else imageIO falls over if( !fs::exists(variablesMap["moving"].as<std::string>()) ) { std::cerr <<"ERROR: " << variablesMap["moving"].as<std::string>() << " not found. Exiting!" << std::endl; return -1; } if( !fs::exists(variablesMap["fixed"].as<std::string>()) ) { std::cerr <<"ERROR: " << variablesMap["fixed"].as<std::string>() << " not found. Exiting!" << std::endl; return -1; } imageIO->SetFileName(variablesMap["moving"].as<std::string>().c_str()); imageIO->ReadImageInformation(); const int nDims = imageIO->GetNumberOfDimensions(); //Return error if dimensionality is not 2 or 3 //We have to template on dimension, so other dimensionalities //would require excess code //Case table for different dimensionalities and transformations //Although this is code verbose and results in large binaries - it results //in efficient code if( nDims != 3 ) { std::cerr << "ERROR: Image dimension is " << nDims << "Only 3 dimensional registrations are currently supported." << std::endl; return -1; } itk::MirorrPyramidWrapper mirorr; //The registration mode need to be set first //***THIS CREATE A NEW (Sym)MirorrRegistrationMethod*** if( variablesMap.count("reg-mode") ) { std::string mode = variablesMap["reg-mode"].as<std::string>(); if( mode == "classic" ) { mirorr.GetRegistrationPyramidObject().SetRegistrationTypeClassic(); } else if( mode == "symmetric" ) { mirorr.GetRegistrationPyramidObject().SetRegistrationTypeSymmetrical(); } else { std::cerr << "ERROR: Unknown reg-mode. Available options are " "'classic' and 'symmetric' (default)." << std::endl; return -1; } } else { mirorr.GetRegistrationPyramidObject().SetRegistrationTypeSymmetrical(); } mirorr.SetProgramName(argv[0]); //Get moving and fixed image file names from command line if( variablesMap.count("switch-images") ) { mirorr.SetMovingName( variablesMap["fixed"].as<std::string>() ); mirorr.SetFixedName( variablesMap["moving"].as<std::string>() ); mirorr.SetMovingMaskName( variablesMap["fixed-mask"].as<std::string>() ); mirorr.SetFixedMaskName( variablesMap["moving-mask"].as<std::string>() ); } else { mirorr.SetMovingName( variablesMap["moving"].as<std::string>() ); mirorr.SetFixedName( variablesMap["fixed"].as<std::string>() ); mirorr.SetMovingMaskName( variablesMap["moving-mask"].as<std::string>() ); mirorr.SetFixedMaskName( variablesMap["fixed-mask"].as<std::string>() ); } mirorr.SetDoReorientFixedInARI( variablesMap.count("reorient-fixed") == true ); mirorr.SetDoReorientMovingInARI( variablesMap.count("reorient-moving") == true ); if( variablesMap.count("no-centering-init") ) mirorr.SetDoInitialiseTransformToCentreImages(false); //Should we bother applying registration bool do_not_register = variablesMap.count("do-not-register") > 0; mirorr.SetDoNotRegister( do_not_register ); //Read in the name of the file for the final transformation or create one //from fixed image name std::string output_transform_file_name = variablesMap["last-tfm"].as<std::string>(); std::string input_transform_file_name = variablesMap["start-tfm"].as<std::string>(); if( output_transform_file_name.empty() && ! do_not_register ) { //Two basenames to catch .nii.gz output_transform_file_name = fs::basename( fs::basename( fs::path(mirorr.GetFixedName()).leaf() ) ); output_transform_file_name += "_tfmFinal.tfm"; std::cerr << "WARNING: No output transform supplied. Setting to: " << output_transform_file_name << std::endl; std::cerr << "INFO: To avoid saving the last transform, use '--last-tfm ignore'" << std::endl; } else if( output_transform_file_name == "ignore" ) { output_transform_file_name = ""; } mirorr.SetFinalTransformName( output_transform_file_name ); //Check if output file exists if( input_transform_file_name.empty() && fs::exists(fs::path(output_transform_file_name)) ) { std::cout << "INFO: Output transform file already exists (" << output_transform_file_name <<") and will be overwritten, "; if( variablesMap.count("fresh") ) std::cout << "and it will NOT be used to initialise registration.\n" << std::endl; else { std::cout << "but it WILL be used to initialise registration.\n" << std::endl; input_transform_file_name = output_transform_file_name; } } //Read in name of the file for the initial transformation or assume //identity transform mirorr.SetInitialTransformName( input_transform_file_name ); //Specify name of file to save fixed image to after registration if(variablesMap.count("save-fixed")) mirorr.SetLastTransformedFixedName( variablesMap["save-fixed"].as<std::string>(), true); if(variablesMap.count("save-moving")) mirorr.SetLastTransformedMovingName( variablesMap["save-moving"].as<std::string>(), true); if(variablesMap.count("save-reoriented-fixed")) mirorr.SetLastTransformedFixedName( variablesMap["save-reoriented-fixed"].as<std::string>() ); if(variablesMap.count("save-reoriented-moving")) mirorr.SetLastTransformedMovingName( variablesMap["save-reoriented-moving"].as<std::string>() ); if(variablesMap.count("save-resampled-fixed")) { if (!mirorr.GetLastTransformedFixedName().empty()) throw std::runtime_error("Cannot use save-resampled-fixed and save-reoriented-fixed arguments at same time."); mirorr.SetLastTransformedFixedName(variablesMap["save-resampled-fixed"].as<std::string>(), true); } if(variablesMap.count("save-resampled-moving")) { if (!mirorr.GetLastTransformedMovingName().empty()) throw std::runtime_error("Cannot use save-resampled-moving and save-reoriented-moving arguments at same time."); mirorr.SetLastTransformedMovingName(variablesMap["save-resampled-moving"].as<std::string>(), true); } if(variablesMap.count("final-interpolator")) { mirorr.SetFinalInterpolatorName(variablesMap["final-interpolator"].as<std::string>()); } if( variablesMap.count("invert-start-tfm") ) mirorr.SetInvertInputTransform( true ); else mirorr.SetInvertInputTransform( false ); if( variablesMap.count("invert-last-tfm") ) mirorr.SetInvertOutputTransform( true ); else mirorr.SetInvertOutputTransform( false ); // Set the number threads if( variablesMap.count("nthreads") ) { int n = variablesMap["nthreads"].as<int>(); if( mirorr.GetVerbosity() >= 2 ) {std::cout << "--nthread: " << n;} if (n==0) { if( mirorr.GetVerbosity() >= 2 ) {std::cout << ". Default multithread implementation" << std::endl;} mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->UseMultiThreadingOn(); // Use default number of threads } else if (n<2) { if( mirorr.GetVerbosity() >= 2 ) {std::cout << ". Singlethreaded implementation" << std::endl;} mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->UseMultiThreadingOff(); } else { if( mirorr.GetVerbosity() >= 2 ) {std::cout << ". Multithread implementation with " << n << " threads" << std::endl;} mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->UseMultiThreadingOn(); mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetNumberOfBlockMatcherThreads(n); itk::MultiThreader::SetGlobalMaximumNumberOfThreads( n ); } } //Store no. iterations mirorr.GetRegistrationPyramidObject().SetMaxIterations( variablesMap["iterations"].as<int>() ); /* //Resampling for non-symmetric registration mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetUseSymResampling( variablesMap.count("basic-resampling") == 0 ); //Resampling type for (semi)symmetric registration mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetUseMaxResampling( variablesMap.count("max-resampling") != 0 ); */ if( variablesMap.count("resampling-mode") ) { std::string mode = variablesMap["resampling-mode"].as<std::string>(); if( mode == "basic" ) { mirorr.GetRegistrationPyramidObject().SetResamplingType(itk::MirorrPyramidWrapper::MirorrType::EResamplingBasic); } else if( mode == "middle" ) { mirorr.GetRegistrationPyramidObject().SetResamplingType(itk::MirorrPyramidWrapper::MirorrType::EResamplingMiddle); } else if( mode == "max-resolution" ) { mirorr.GetRegistrationPyramidObject().SetResamplingType(itk::MirorrPyramidWrapper::MirorrType::EResamplingMaxResolution); } else if( mode == "max-size" ) { mirorr.GetRegistrationPyramidObject().SetResamplingType(itk::MirorrPyramidWrapper::MirorrType::EResamplingMaxSize); } else if( mode == "fixed" ) { mirorr.GetRegistrationPyramidObject().SetResamplingType(itk::MirorrPyramidWrapper::MirorrType::EResamplingFixed); } else if( mode == "moving" ) { mirorr.GetRegistrationPyramidObject().SetResamplingType(itk::MirorrPyramidWrapper::MirorrType::EResamplingMoving); } else { std::cerr << "ERROR: Unknown resampling-mode. Available options are " "'classic' and 'symmetric' (default)." << std::endl; return -1; } } else { mirorr.GetRegistrationPyramidObject().SetResamplingType(itk::MirorrPyramidWrapper::MirorrType::EResamplingMiddle); } //Control pyramid levels that are used int aa = variablesMap["pyr-start"].as<int>(); int bb = variablesMap["pyr-switch"].as<int>(); int cc = variablesMap["pyr-end"].as<int>(); bool do_use_itk = variablesMap.count("use-itk") > 0; int maxLevel = variablesMap["pyr-num"].as<int>(); int minBlockLength = variablesMap["pyr-min-size"].as<int>(); /*if( cc<bb ) //DRH: this can't be here... does not manage negative number + max level is not known at this point { if( do_use_itk ) std::cout<<"WARNING: Switch pyramid level ("<<bb <<") above final level ("<<cc<<"). Increasing final level."<<std::endl; cc = bb; }*/ mirorr.GetRegistrationPyramidObject().GetPyramidScheduleTuner()->SetMinLength(minBlockLength); mirorr.GetRegistrationPyramidObject().GetPyramidScheduleTuner()->SetLevelMin( aa ); mirorr.GetRegistrationPyramidObject().GetPyramidScheduleTuner()->SetLevelMax( cc ); //Lock switch level to end pyramid level if we're not using itk (default) if( !do_use_itk ) bb = cc; else std::cerr<<"WARNING: the use of itk registration is deprecated and will be removed in later versions."<<std::endl; mirorr.GetRegistrationPyramidObject().SetLevelToChangeMethod( bb ); mirorr.GetRegistrationPyramidObject().SetUseBlockMatchingAlgorithm( variablesMap.count("no-bm") == 0 ); mirorr.GetRegistrationPyramidObject().SetUseMutualInformationAlgorithm( do_use_itk ); mirorr.GetRegistrationPyramidObject().SetRequestedSampleRate( variablesMap["itk-srate"].as<double>() ); mirorr.GetRegistrationPyramidObject().GetPyramidScheduleTuner()->SetMaxLevelNumber(maxLevel); //Read in secondary ITK registration metric type { std::string secondaryMetric = variablesMap["itk-metric"].as<std::string>(); if ( secondaryMetric == "mmi" ) { mirorr.GetRegistrationPyramidObject().SetSecondaryRegistrationMetricToMMI(); } else if ( secondaryMetric == "ncc" ) { mirorr.GetRegistrationPyramidObject().SetSecondaryRegistrationMetricToNCC(); } else if ( secondaryMetric == "gd" ) { mirorr.GetRegistrationPyramidObject().SetSecondaryRegistrationMetricToGD(); } else if ( secondaryMetric == "mi" ) { mirorr.GetRegistrationPyramidObject().SetSecondaryRegistrationMetricToMI(); } else { std::cerr << "Error: Unknown itk-metric "; std::cerr << "possible options are: mmi, ncc, gd, and mi." << std::endl; return -1; } } //Read bottom level. This should be at least 0 mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetPortionMatchesKept( variablesMap["portion-kept"].as<double>() ); #ifdef USE_OPENCL if(variablesMap.count("use-gpu-bm")) mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetUseGpuOn(true); else mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetUseGpuOn(false); #endif //What level of verbosity is required mirorr.SetVerbosity(1); if( variablesMap.count("quiet") ) mirorr.SetVerbosity(0); if( variablesMap.count("verbose") ) mirorr.SetVerbosity(2); //Read in the default transform type mirorr.SetTransformType( variablesMap["tfm-type"].as<std::string>() ); //Read in block metric type { std::map<std::string, std::string> metricMap; metricMap["nc"] = "normalized_correlation"; metricMap["sd"] = "sum_of_squared_differences"; metricMap["cr"] = "correlation_ratio"; metricMap["mi"] = "mutual_information"; #ifdef USE_NPW metricMap["npwmi"] = "npw_mutual_information"; #endif std::string blockMetricInput = variablesMap["blockmetric"].as<std::string>(); if ( metricMap.find(blockMetricInput) == metricMap.end() ) { std::cerr << "ERROR: " << blockMetricInput << " is not a valid blockmetric type. Exiting!" << std::endl; std::cerr << "possible options are:" << std::endl; \ for( std::map<std::string,std::string>::iterator it = metricMap.begin(); it != metricMap.end(); ++it ) { std::cerr << " " << it->first << ": " << it->second << std::endl; } return -1; } std::string blockMetricType = metricMap[ blockMetricInput ]; mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetBlockMetricType( blockMetricType ); } //Fill in deep algorithm parameters //Optionally fill in "deep" algorithm parameters { int blockWidth = variablesMap["blockwidth"].as<int>(); int blockGap = variablesMap["blockgap"].as<int>(); int nhoodWidth = variablesMap["nhoodwidth"].as<int>(); int nhoodGap = variablesMap["nhoodgap"].as<int>(); if( blockWidth>0 ) mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetBlockWidth( blockWidth ); if( blockGap>0 ) mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetBlockGap( blockGap ); if( nhoodWidth>0 ) mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetNhoodWidth( nhoodWidth ); if( nhoodGap>0 ) mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetNhoodGap( nhoodGap ); #ifdef USE_NPW //Fill in npw algorithm parameters int NPWbins = variablesMap["npw-bins"].as<int>(); mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetNPWbins( NPWbins ); #ifndef USE_OPENCL int NPWscaleFactor = variablesMap["npw-scale-factor"].as<int>(); int NPWshapeExpansion = ( variablesMap.count("npw-shape-expansion") ? true : false ); mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetNPWscaleFactor( NPWscaleFactor ); mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->SetNPWshapeExpansion( NPWshapeExpansion ); #endif #endif } //Display if( mirorr.GetVerbosity() >= 2 ) { std::string switched = ""; if(variablesMap.count("switch-images")) switched = " (switched)"; std::cout << "Moving Image: " << mirorr.GetMovingName() << switched << std::endl; std::cout << " Fixed Image: " << mirorr.GetFixedName() << switched << std::endl; std::cout << " Data Type: " << imageIO->GetComponentType() << std::endl; std::cout << " Dimensions: " << nDims << std::endl; std::cout << " Transform: " << mirorr.GetTransformType() << std::endl; std::cout << " Output Tfm: " << mirorr.GetFinalTransformName() << std::endl; std::cout << "Block Metric: " << mirorr.GetRegistrationPyramidObject().GetRegistrationObject()->GetBlockMetricType() << std::endl; } mirorr.Update(); time_t rawtimeEnd; /* Seconds since the Epoch. */ time ( &rawtimeEnd ); time_t elapsed = rawtimeEnd - rawtime; std::cout << "\nmirorr ran successfully" << std::endl << "Process started on: " << asctime ( localtime ( &rawtime ) ); std::cout << "Process completed on: " << asctime ( localtime ( &rawtimeEnd ) ) << "Elapsed time is "; if (elapsed/3600 > 0) { std::cout << elapsed/3600 << "h"; } if (elapsed/60 > 0) { std::cout << (elapsed/60)%60 << "m"; } std::cout << elapsed%60 << "s" << std::endl; return 0; }
47.613636
134
0.669511
[ "render", "shape", "transform", "3d" ]
e062f36e467960449596c4c3aae770b4004956d1
208,490
cpp
C++
UWP/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_22Table.cpp
rndmized/OkamiBushi
10ea681f9716d17aa605e0cbb764b7a4b63ae038
[ "MIT" ]
1
2019-09-14T04:39:37.000Z
2019-09-14T04:39:37.000Z
UWP/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_22Table.cpp
rndmized/OkamiBushi
10ea681f9716d17aa605e0cbb764b7a4b63ae038
[ "MIT" ]
null
null
null
UWP/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_22Table.cpp
rndmized/OkamiBushi
10ea681f9716d17aa605e0cbb764b7a4b63ae038
[ "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" // MS.Internal.Xml.Cache.XPathNode[] struct XPathNodeU5BU5D_t47339301; // System.String struct String_t; // System.Xml.XPath.XPathDocument struct XPathDocument_t1673143697; // MS.Internal.Xml.Cache.XPathNodePageInfo struct XPathNodePageInfo_t2343388010; // System.Collections.ArrayList struct ArrayList_t2718874744; // System.Collections.Hashtable struct Hashtable_t1853889766; // MS.Internal.Xml.XPath.XPathScanner struct XPathScanner_t3283201025; // System.Xml.XPath.XPathResultType[] struct XPathResultTypeU5BU5D_t1515527577; // System.Byte[] struct ByteU5BU5D_t4116647657; // System.Char[] struct CharU5BU5D_t3528271667; // System.Collections.Specialized.ListDictionary struct ListDictionary_t1624492310; // System.Collections.Specialized.ListDictionary/DictionaryNode struct DictionaryNode_t417719465; // System.Collections.IEqualityComparer struct IEqualityComparer_t1493878338; // System.Collections.Specialized.NameObjectCollectionBase/NameObjectEntry struct NameObjectEntry_t4224248211; // System.Collections.Specialized.NameObjectCollectionBase/KeysCollection struct KeysCollection_t1318642398; // System.Runtime.Serialization.SerializationInfo struct SerializationInfo_t950877179; // System.StringComparer struct StringComparer_t3301955079; // System.Reflection.MemberInfo struct MemberInfo_t; // System.Collections.ICollection struct ICollection_t3904884886; // System.Runtime.Remoting.ServerIdentity struct ServerIdentity_t2342208608; // System.Collections.IComparer struct IComparer_t1540313114; // System.Collections.IEnumerator struct IEnumerator_t1853284238; // System.Collections.Specialized.NameObjectCollectionBase struct NameObjectCollectionBase_t2091847364; // System.Collections.IHashCodeProvider struct IHashCodeProvider_t267601189; // MS.Internal.Xml.Cache.XPathNodeInfoAtom struct XPathNodeInfoAtom_t1760358141; // System.Void struct Void_t1185182177; // System.Xml.XPath.XPathNavigatorKeyComparer struct XPathNavigatorKeyComparer_t2518900029; // System.Int32[] struct Int32U5BU5D_t385246372; // System.Xml.XmlTextEncoder struct XmlTextEncoder_t1632274355; // System.IO.Stream/ReadWriteTask struct ReadWriteTask_t156472862; // System.Threading.SemaphoreSlim struct SemaphoreSlim_t2974092902; // MS.Internal.Xml.XPath.AstNode struct AstNode_t2514041814; // System.String[] struct StringU5BU5D_t1281789340; // System.Reflection.MethodInfo struct MethodInfo_t; // System.DelegateData struct DelegateData_t1677132599; // System.IO.Compression.DeflateStreamNative/UnmanagedReadOrWrite struct UnmanagedReadOrWrite_t1975956110; // System.IO.Stream struct Stream_t1273022909; // System.IO.Compression.DeflateStream struct DeflateStream_t4175168077; // MS.Internal.Xml.XPath.Operator/Op[] struct OpU5BU5D_t2837398892; // System.Delegate[] struct DelegateU5BU5D_t1703627840; // System.IO.Compression.DeflateStreamNative struct DeflateStreamNative_t1405046456; // System.IAsyncResult struct IAsyncResult_t767004451; // System.AsyncCallback struct AsyncCallback_t3962456242; struct XPathNode_t2208072876_marshaled_pinvoke; struct XPathNode_t2208072876_marshaled_com; #ifndef U3CMODULEU3E_T692745527_H #define U3CMODULEU3E_T692745527_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t692745527 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T692745527_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 XPATHNODEPAGEINFO_T2343388010_H #define XPATHNODEPAGEINFO_T2343388010_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.Cache.XPathNodePageInfo struct XPathNodePageInfo_t2343388010 : public RuntimeObject { public: // System.Int32 MS.Internal.Xml.Cache.XPathNodePageInfo::pageNum int32_t ___pageNum_0; // System.Int32 MS.Internal.Xml.Cache.XPathNodePageInfo::nodeCount int32_t ___nodeCount_1; // MS.Internal.Xml.Cache.XPathNode[] MS.Internal.Xml.Cache.XPathNodePageInfo::pageNext XPathNodeU5BU5D_t47339301* ___pageNext_2; public: inline static int32_t get_offset_of_pageNum_0() { return static_cast<int32_t>(offsetof(XPathNodePageInfo_t2343388010, ___pageNum_0)); } inline int32_t get_pageNum_0() const { return ___pageNum_0; } inline int32_t* get_address_of_pageNum_0() { return &___pageNum_0; } inline void set_pageNum_0(int32_t value) { ___pageNum_0 = value; } inline static int32_t get_offset_of_nodeCount_1() { return static_cast<int32_t>(offsetof(XPathNodePageInfo_t2343388010, ___nodeCount_1)); } inline int32_t get_nodeCount_1() const { return ___nodeCount_1; } inline int32_t* get_address_of_nodeCount_1() { return &___nodeCount_1; } inline void set_nodeCount_1(int32_t value) { ___nodeCount_1 = value; } inline static int32_t get_offset_of_pageNext_2() { return static_cast<int32_t>(offsetof(XPathNodePageInfo_t2343388010, ___pageNext_2)); } inline XPathNodeU5BU5D_t47339301* get_pageNext_2() const { return ___pageNext_2; } inline XPathNodeU5BU5D_t47339301** get_address_of_pageNext_2() { return &___pageNext_2; } inline void set_pageNext_2(XPathNodeU5BU5D_t47339301* value) { ___pageNext_2 = value; Il2CppCodeGenWriteBarrier((&___pageNext_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHNODEPAGEINFO_T2343388010_H #ifndef XPATHNODEINFOATOM_T1760358141_H #define XPATHNODEINFOATOM_T1760358141_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.Cache.XPathNodeInfoAtom struct XPathNodeInfoAtom_t1760358141 : public RuntimeObject { public: // System.String MS.Internal.Xml.Cache.XPathNodeInfoAtom::localName String_t* ___localName_0; // System.String MS.Internal.Xml.Cache.XPathNodeInfoAtom::namespaceUri String_t* ___namespaceUri_1; // System.String MS.Internal.Xml.Cache.XPathNodeInfoAtom::prefix String_t* ___prefix_2; // System.String MS.Internal.Xml.Cache.XPathNodeInfoAtom::baseUri String_t* ___baseUri_3; // MS.Internal.Xml.Cache.XPathNode[] MS.Internal.Xml.Cache.XPathNodeInfoAtom::pageParent XPathNodeU5BU5D_t47339301* ___pageParent_4; // MS.Internal.Xml.Cache.XPathNode[] MS.Internal.Xml.Cache.XPathNodeInfoAtom::pageSibling XPathNodeU5BU5D_t47339301* ___pageSibling_5; // MS.Internal.Xml.Cache.XPathNode[] MS.Internal.Xml.Cache.XPathNodeInfoAtom::pageSimilar XPathNodeU5BU5D_t47339301* ___pageSimilar_6; // System.Xml.XPath.XPathDocument MS.Internal.Xml.Cache.XPathNodeInfoAtom::doc XPathDocument_t1673143697 * ___doc_7; // System.Int32 MS.Internal.Xml.Cache.XPathNodeInfoAtom::lineNumBase int32_t ___lineNumBase_8; // System.Int32 MS.Internal.Xml.Cache.XPathNodeInfoAtom::linePosBase int32_t ___linePosBase_9; // System.Int32 MS.Internal.Xml.Cache.XPathNodeInfoAtom::hashCode int32_t ___hashCode_10; // System.Int32 MS.Internal.Xml.Cache.XPathNodeInfoAtom::localNameHash int32_t ___localNameHash_11; // MS.Internal.Xml.Cache.XPathNodePageInfo MS.Internal.Xml.Cache.XPathNodeInfoAtom::pageInfo XPathNodePageInfo_t2343388010 * ___pageInfo_12; public: inline static int32_t get_offset_of_localName_0() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___localName_0)); } inline String_t* get_localName_0() const { return ___localName_0; } inline String_t** get_address_of_localName_0() { return &___localName_0; } inline void set_localName_0(String_t* value) { ___localName_0 = value; Il2CppCodeGenWriteBarrier((&___localName_0), value); } inline static int32_t get_offset_of_namespaceUri_1() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___namespaceUri_1)); } inline String_t* get_namespaceUri_1() const { return ___namespaceUri_1; } inline String_t** get_address_of_namespaceUri_1() { return &___namespaceUri_1; } inline void set_namespaceUri_1(String_t* value) { ___namespaceUri_1 = value; Il2CppCodeGenWriteBarrier((&___namespaceUri_1), value); } inline static int32_t get_offset_of_prefix_2() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___prefix_2)); } inline String_t* get_prefix_2() const { return ___prefix_2; } inline String_t** get_address_of_prefix_2() { return &___prefix_2; } inline void set_prefix_2(String_t* value) { ___prefix_2 = value; Il2CppCodeGenWriteBarrier((&___prefix_2), value); } inline static int32_t get_offset_of_baseUri_3() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___baseUri_3)); } inline String_t* get_baseUri_3() const { return ___baseUri_3; } inline String_t** get_address_of_baseUri_3() { return &___baseUri_3; } inline void set_baseUri_3(String_t* value) { ___baseUri_3 = value; Il2CppCodeGenWriteBarrier((&___baseUri_3), value); } inline static int32_t get_offset_of_pageParent_4() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___pageParent_4)); } inline XPathNodeU5BU5D_t47339301* get_pageParent_4() const { return ___pageParent_4; } inline XPathNodeU5BU5D_t47339301** get_address_of_pageParent_4() { return &___pageParent_4; } inline void set_pageParent_4(XPathNodeU5BU5D_t47339301* value) { ___pageParent_4 = value; Il2CppCodeGenWriteBarrier((&___pageParent_4), value); } inline static int32_t get_offset_of_pageSibling_5() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___pageSibling_5)); } inline XPathNodeU5BU5D_t47339301* get_pageSibling_5() const { return ___pageSibling_5; } inline XPathNodeU5BU5D_t47339301** get_address_of_pageSibling_5() { return &___pageSibling_5; } inline void set_pageSibling_5(XPathNodeU5BU5D_t47339301* value) { ___pageSibling_5 = value; Il2CppCodeGenWriteBarrier((&___pageSibling_5), value); } inline static int32_t get_offset_of_pageSimilar_6() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___pageSimilar_6)); } inline XPathNodeU5BU5D_t47339301* get_pageSimilar_6() const { return ___pageSimilar_6; } inline XPathNodeU5BU5D_t47339301** get_address_of_pageSimilar_6() { return &___pageSimilar_6; } inline void set_pageSimilar_6(XPathNodeU5BU5D_t47339301* value) { ___pageSimilar_6 = value; Il2CppCodeGenWriteBarrier((&___pageSimilar_6), value); } inline static int32_t get_offset_of_doc_7() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___doc_7)); } inline XPathDocument_t1673143697 * get_doc_7() const { return ___doc_7; } inline XPathDocument_t1673143697 ** get_address_of_doc_7() { return &___doc_7; } inline void set_doc_7(XPathDocument_t1673143697 * value) { ___doc_7 = value; Il2CppCodeGenWriteBarrier((&___doc_7), value); } inline static int32_t get_offset_of_lineNumBase_8() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___lineNumBase_8)); } inline int32_t get_lineNumBase_8() const { return ___lineNumBase_8; } inline int32_t* get_address_of_lineNumBase_8() { return &___lineNumBase_8; } inline void set_lineNumBase_8(int32_t value) { ___lineNumBase_8 = value; } inline static int32_t get_offset_of_linePosBase_9() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___linePosBase_9)); } inline int32_t get_linePosBase_9() const { return ___linePosBase_9; } inline int32_t* get_address_of_linePosBase_9() { return &___linePosBase_9; } inline void set_linePosBase_9(int32_t value) { ___linePosBase_9 = value; } inline static int32_t get_offset_of_hashCode_10() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___hashCode_10)); } inline int32_t get_hashCode_10() const { return ___hashCode_10; } inline int32_t* get_address_of_hashCode_10() { return &___hashCode_10; } inline void set_hashCode_10(int32_t value) { ___hashCode_10 = value; } inline static int32_t get_offset_of_localNameHash_11() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___localNameHash_11)); } inline int32_t get_localNameHash_11() const { return ___localNameHash_11; } inline int32_t* get_address_of_localNameHash_11() { return &___localNameHash_11; } inline void set_localNameHash_11(int32_t value) { ___localNameHash_11 = value; } inline static int32_t get_offset_of_pageInfo_12() { return static_cast<int32_t>(offsetof(XPathNodeInfoAtom_t1760358141, ___pageInfo_12)); } inline XPathNodePageInfo_t2343388010 * get_pageInfo_12() const { return ___pageInfo_12; } inline XPathNodePageInfo_t2343388010 ** get_address_of_pageInfo_12() { return &___pageInfo_12; } inline void set_pageInfo_12(XPathNodePageInfo_t2343388010 * value) { ___pageInfo_12 = value; Il2CppCodeGenWriteBarrier((&___pageInfo_12), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHNODEINFOATOM_T1760358141_H #ifndef STRINGCOLLECTION_T167406615_H #define STRINGCOLLECTION_T167406615_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.StringCollection struct StringCollection_t167406615 : public RuntimeObject { public: // System.Collections.ArrayList System.Collections.Specialized.StringCollection::data ArrayList_t2718874744 * ___data_0; public: inline static int32_t get_offset_of_data_0() { return static_cast<int32_t>(offsetof(StringCollection_t167406615, ___data_0)); } inline ArrayList_t2718874744 * get_data_0() const { return ___data_0; } inline ArrayList_t2718874744 ** get_address_of_data_0() { return &___data_0; } inline void set_data_0(ArrayList_t2718874744 * value) { ___data_0 = value; Il2CppCodeGenWriteBarrier((&___data_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRINGCOLLECTION_T167406615_H #ifndef XPATHNODEHELPER_T2230825274_H #define XPATHNODEHELPER_T2230825274_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.Cache.XPathNodeHelper struct XPathNodeHelper_t2230825274 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHNODEHELPER_T2230825274_H #ifndef STRINGDICTIONARY_T120437468_H #define STRINGDICTIONARY_T120437468_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.StringDictionary struct StringDictionary_t120437468 : public RuntimeObject { public: // System.Collections.Hashtable System.Collections.Specialized.StringDictionary::contents Hashtable_t1853889766 * ___contents_0; public: inline static int32_t get_offset_of_contents_0() { return static_cast<int32_t>(offsetof(StringDictionary_t120437468, ___contents_0)); } inline Hashtable_t1853889766 * get_contents_0() const { return ___contents_0; } inline Hashtable_t1853889766 ** get_address_of_contents_0() { return &___contents_0; } inline void set_contents_0(Hashtable_t1853889766 * value) { ___contents_0 = value; Il2CppCodeGenWriteBarrier((&___contents_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRINGDICTIONARY_T120437468_H #ifndef VALUETYPE_T3640485471_H #define VALUETYPE_T3640485471_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t3640485471 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t3640485471_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t3640485471_marshaled_com { }; #endif // VALUETYPE_T3640485471_H #ifndef XPATHPARSER_T618394529_H #define XPATHPARSER_T618394529_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.XPathParser struct XPathParser_t618394529 : public RuntimeObject { public: // MS.Internal.Xml.XPath.XPathScanner MS.Internal.Xml.XPath.XPathParser::scanner XPathScanner_t3283201025 * ___scanner_0; // System.Int32 MS.Internal.Xml.XPath.XPathParser::parseDepth int32_t ___parseDepth_1; public: inline static int32_t get_offset_of_scanner_0() { return static_cast<int32_t>(offsetof(XPathParser_t618394529, ___scanner_0)); } inline XPathScanner_t3283201025 * get_scanner_0() const { return ___scanner_0; } inline XPathScanner_t3283201025 ** get_address_of_scanner_0() { return &___scanner_0; } inline void set_scanner_0(XPathScanner_t3283201025 * value) { ___scanner_0 = value; Il2CppCodeGenWriteBarrier((&___scanner_0), value); } inline static int32_t get_offset_of_parseDepth_1() { return static_cast<int32_t>(offsetof(XPathParser_t618394529, ___parseDepth_1)); } inline int32_t get_parseDepth_1() const { return ___parseDepth_1; } inline int32_t* get_address_of_parseDepth_1() { return &___parseDepth_1; } inline void set_parseDepth_1(int32_t value) { ___parseDepth_1 = value; } }; struct XPathParser_t618394529_StaticFields { public: // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray1 XPathResultTypeU5BU5D_t1515527577* ___temparray1_2; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray2 XPathResultTypeU5BU5D_t1515527577* ___temparray2_3; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray3 XPathResultTypeU5BU5D_t1515527577* ___temparray3_4; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray4 XPathResultTypeU5BU5D_t1515527577* ___temparray4_5; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray5 XPathResultTypeU5BU5D_t1515527577* ___temparray5_6; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray6 XPathResultTypeU5BU5D_t1515527577* ___temparray6_7; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray7 XPathResultTypeU5BU5D_t1515527577* ___temparray7_8; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray8 XPathResultTypeU5BU5D_t1515527577* ___temparray8_9; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser::temparray9 XPathResultTypeU5BU5D_t1515527577* ___temparray9_10; // System.Collections.Hashtable MS.Internal.Xml.XPath.XPathParser::functionTable Hashtable_t1853889766 * ___functionTable_11; // System.Collections.Hashtable MS.Internal.Xml.XPath.XPathParser::AxesTable Hashtable_t1853889766 * ___AxesTable_12; public: inline static int32_t get_offset_of_temparray1_2() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray1_2)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray1_2() const { return ___temparray1_2; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray1_2() { return &___temparray1_2; } inline void set_temparray1_2(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray1_2 = value; Il2CppCodeGenWriteBarrier((&___temparray1_2), value); } inline static int32_t get_offset_of_temparray2_3() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray2_3)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray2_3() const { return ___temparray2_3; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray2_3() { return &___temparray2_3; } inline void set_temparray2_3(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray2_3 = value; Il2CppCodeGenWriteBarrier((&___temparray2_3), value); } inline static int32_t get_offset_of_temparray3_4() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray3_4)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray3_4() const { return ___temparray3_4; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray3_4() { return &___temparray3_4; } inline void set_temparray3_4(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray3_4 = value; Il2CppCodeGenWriteBarrier((&___temparray3_4), value); } inline static int32_t get_offset_of_temparray4_5() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray4_5)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray4_5() const { return ___temparray4_5; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray4_5() { return &___temparray4_5; } inline void set_temparray4_5(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray4_5 = value; Il2CppCodeGenWriteBarrier((&___temparray4_5), value); } inline static int32_t get_offset_of_temparray5_6() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray5_6)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray5_6() const { return ___temparray5_6; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray5_6() { return &___temparray5_6; } inline void set_temparray5_6(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray5_6 = value; Il2CppCodeGenWriteBarrier((&___temparray5_6), value); } inline static int32_t get_offset_of_temparray6_7() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray6_7)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray6_7() const { return ___temparray6_7; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray6_7() { return &___temparray6_7; } inline void set_temparray6_7(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray6_7 = value; Il2CppCodeGenWriteBarrier((&___temparray6_7), value); } inline static int32_t get_offset_of_temparray7_8() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray7_8)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray7_8() const { return ___temparray7_8; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray7_8() { return &___temparray7_8; } inline void set_temparray7_8(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray7_8 = value; Il2CppCodeGenWriteBarrier((&___temparray7_8), value); } inline static int32_t get_offset_of_temparray8_9() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray8_9)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray8_9() const { return ___temparray8_9; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray8_9() { return &___temparray8_9; } inline void set_temparray8_9(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray8_9 = value; Il2CppCodeGenWriteBarrier((&___temparray8_9), value); } inline static int32_t get_offset_of_temparray9_10() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___temparray9_10)); } inline XPathResultTypeU5BU5D_t1515527577* get_temparray9_10() const { return ___temparray9_10; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_temparray9_10() { return &___temparray9_10; } inline void set_temparray9_10(XPathResultTypeU5BU5D_t1515527577* value) { ___temparray9_10 = value; Il2CppCodeGenWriteBarrier((&___temparray9_10), value); } inline static int32_t get_offset_of_functionTable_11() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___functionTable_11)); } inline Hashtable_t1853889766 * get_functionTable_11() const { return ___functionTable_11; } inline Hashtable_t1853889766 ** get_address_of_functionTable_11() { return &___functionTable_11; } inline void set_functionTable_11(Hashtable_t1853889766 * value) { ___functionTable_11 = value; Il2CppCodeGenWriteBarrier((&___functionTable_11), value); } inline static int32_t get_offset_of_AxesTable_12() { return static_cast<int32_t>(offsetof(XPathParser_t618394529_StaticFields, ___AxesTable_12)); } inline Hashtable_t1853889766 * get_AxesTable_12() const { return ___AxesTable_12; } inline Hashtable_t1853889766 ** get_address_of_AxesTable_12() { return &___AxesTable_12; } inline void set_AxesTable_12(Hashtable_t1853889766 * value) { ___AxesTable_12 = value; Il2CppCodeGenWriteBarrier((&___AxesTable_12), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHPARSER_T618394529_H #ifndef ATTRIBUTE_T861562559_H #define ATTRIBUTE_T861562559_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Attribute struct Attribute_t861562559 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTE_T861562559_H #ifndef BASE64ENCODER_T3938083961_H #define BASE64ENCODER_T3938083961_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.Base64Encoder struct Base64Encoder_t3938083961 : public RuntimeObject { public: // System.Byte[] System.Xml.Base64Encoder::leftOverBytes ByteU5BU5D_t4116647657* ___leftOverBytes_0; // System.Int32 System.Xml.Base64Encoder::leftOverBytesCount int32_t ___leftOverBytesCount_1; // System.Char[] System.Xml.Base64Encoder::charsLine CharU5BU5D_t3528271667* ___charsLine_2; public: inline static int32_t get_offset_of_leftOverBytes_0() { return static_cast<int32_t>(offsetof(Base64Encoder_t3938083961, ___leftOverBytes_0)); } inline ByteU5BU5D_t4116647657* get_leftOverBytes_0() const { return ___leftOverBytes_0; } inline ByteU5BU5D_t4116647657** get_address_of_leftOverBytes_0() { return &___leftOverBytes_0; } inline void set_leftOverBytes_0(ByteU5BU5D_t4116647657* value) { ___leftOverBytes_0 = value; Il2CppCodeGenWriteBarrier((&___leftOverBytes_0), value); } inline static int32_t get_offset_of_leftOverBytesCount_1() { return static_cast<int32_t>(offsetof(Base64Encoder_t3938083961, ___leftOverBytesCount_1)); } inline int32_t get_leftOverBytesCount_1() const { return ___leftOverBytesCount_1; } inline int32_t* get_address_of_leftOverBytesCount_1() { return &___leftOverBytesCount_1; } inline void set_leftOverBytesCount_1(int32_t value) { ___leftOverBytesCount_1 = value; } inline static int32_t get_offset_of_charsLine_2() { return static_cast<int32_t>(offsetof(Base64Encoder_t3938083961, ___charsLine_2)); } inline CharU5BU5D_t3528271667* get_charsLine_2() const { return ___charsLine_2; } inline CharU5BU5D_t3528271667** get_address_of_charsLine_2() { return &___charsLine_2; } inline void set_charsLine_2(CharU5BU5D_t3528271667* value) { ___charsLine_2 = value; Il2CppCodeGenWriteBarrier((&___charsLine_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BASE64ENCODER_T3938083961_H #ifndef BINHEXENCODER_T1687308627_H #define BINHEXENCODER_T1687308627_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.BinHexEncoder struct BinHexEncoder_t1687308627 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BINHEXENCODER_T1687308627_H #ifndef SR_T167583545_H #define SR_T167583545_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // SR struct SR_t167583545 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SR_T167583545_H #ifndef ASTNODE_T2514041814_H #define ASTNODE_T2514041814_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.AstNode struct AstNode_t2514041814 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASTNODE_T2514041814_H #ifndef INCREMENTALREADDECODER_T3011954239_H #define INCREMENTALREADDECODER_T3011954239_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.IncrementalReadDecoder struct IncrementalReadDecoder_t3011954239 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INCREMENTALREADDECODER_T3011954239_H #ifndef RES_T3627928856_H #define RES_T3627928856_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.Res struct Res_t3627928856 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RES_T3627928856_H #ifndef BITS_T3566938933_H #define BITS_T3566938933_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.Bits struct Bits_t3566938933 : public RuntimeObject { public: public: }; struct Bits_t3566938933_StaticFields { public: // System.UInt32 System.Xml.Bits::MASK_0101010101010101 uint32_t ___MASK_0101010101010101_0; // System.UInt32 System.Xml.Bits::MASK_0011001100110011 uint32_t ___MASK_0011001100110011_1; // System.UInt32 System.Xml.Bits::MASK_0000111100001111 uint32_t ___MASK_0000111100001111_2; // System.UInt32 System.Xml.Bits::MASK_0000000011111111 uint32_t ___MASK_0000000011111111_3; // System.UInt32 System.Xml.Bits::MASK_1111111111111111 uint32_t ___MASK_1111111111111111_4; public: inline static int32_t get_offset_of_MASK_0101010101010101_0() { return static_cast<int32_t>(offsetof(Bits_t3566938933_StaticFields, ___MASK_0101010101010101_0)); } inline uint32_t get_MASK_0101010101010101_0() const { return ___MASK_0101010101010101_0; } inline uint32_t* get_address_of_MASK_0101010101010101_0() { return &___MASK_0101010101010101_0; } inline void set_MASK_0101010101010101_0(uint32_t value) { ___MASK_0101010101010101_0 = value; } inline static int32_t get_offset_of_MASK_0011001100110011_1() { return static_cast<int32_t>(offsetof(Bits_t3566938933_StaticFields, ___MASK_0011001100110011_1)); } inline uint32_t get_MASK_0011001100110011_1() const { return ___MASK_0011001100110011_1; } inline uint32_t* get_address_of_MASK_0011001100110011_1() { return &___MASK_0011001100110011_1; } inline void set_MASK_0011001100110011_1(uint32_t value) { ___MASK_0011001100110011_1 = value; } inline static int32_t get_offset_of_MASK_0000111100001111_2() { return static_cast<int32_t>(offsetof(Bits_t3566938933_StaticFields, ___MASK_0000111100001111_2)); } inline uint32_t get_MASK_0000111100001111_2() const { return ___MASK_0000111100001111_2; } inline uint32_t* get_address_of_MASK_0000111100001111_2() { return &___MASK_0000111100001111_2; } inline void set_MASK_0000111100001111_2(uint32_t value) { ___MASK_0000111100001111_2 = value; } inline static int32_t get_offset_of_MASK_0000000011111111_3() { return static_cast<int32_t>(offsetof(Bits_t3566938933_StaticFields, ___MASK_0000000011111111_3)); } inline uint32_t get_MASK_0000000011111111_3() const { return ___MASK_0000000011111111_3; } inline uint32_t* get_address_of_MASK_0000000011111111_3() { return &___MASK_0000000011111111_3; } inline void set_MASK_0000000011111111_3(uint32_t value) { ___MASK_0000000011111111_3 = value; } inline static int32_t get_offset_of_MASK_1111111111111111_4() { return static_cast<int32_t>(offsetof(Bits_t3566938933_StaticFields, ___MASK_1111111111111111_4)); } inline uint32_t get_MASK_1111111111111111_4() const { return ___MASK_1111111111111111_4; } inline uint32_t* get_address_of_MASK_1111111111111111_4() { return &___MASK_1111111111111111_4; } inline void set_MASK_1111111111111111_4(uint32_t value) { ___MASK_1111111111111111_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BITS_T3566938933_H #ifndef BINARYCOMPATIBILITY_T2660327299_H #define BINARYCOMPATIBILITY_T2660327299_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.BinaryCompatibility struct BinaryCompatibility_t2660327299 : public RuntimeObject { public: public: }; struct BinaryCompatibility_t2660327299_StaticFields { public: // System.Boolean System.Xml.BinaryCompatibility::_targetsAtLeast_Desktop_V4_5_2 bool ____targetsAtLeast_Desktop_V4_5_2_0; public: inline static int32_t get_offset_of__targetsAtLeast_Desktop_V4_5_2_0() { return static_cast<int32_t>(offsetof(BinaryCompatibility_t2660327299_StaticFields, ____targetsAtLeast_Desktop_V4_5_2_0)); } inline bool get__targetsAtLeast_Desktop_V4_5_2_0() const { return ____targetsAtLeast_Desktop_V4_5_2_0; } inline bool* get_address_of__targetsAtLeast_Desktop_V4_5_2_0() { return &____targetsAtLeast_Desktop_V4_5_2_0; } inline void set__targetsAtLeast_Desktop_V4_5_2_0(bool value) { ____targetsAtLeast_Desktop_V4_5_2_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BINARYCOMPATIBILITY_T2660327299_H #ifndef NODEKEYVALUECOLLECTION_T1279341543_H #define NODEKEYVALUECOLLECTION_T1279341543_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.ListDictionary/NodeKeyValueCollection struct NodeKeyValueCollection_t1279341543 : public RuntimeObject { public: // System.Collections.Specialized.ListDictionary System.Collections.Specialized.ListDictionary/NodeKeyValueCollection::list ListDictionary_t1624492310 * ___list_0; // System.Boolean System.Collections.Specialized.ListDictionary/NodeKeyValueCollection::isKeys bool ___isKeys_1; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(NodeKeyValueCollection_t1279341543, ___list_0)); } inline ListDictionary_t1624492310 * get_list_0() const { return ___list_0; } inline ListDictionary_t1624492310 ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(ListDictionary_t1624492310 * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((&___list_0), value); } inline static int32_t get_offset_of_isKeys_1() { return static_cast<int32_t>(offsetof(NodeKeyValueCollection_t1279341543, ___isKeys_1)); } inline bool get_isKeys_1() const { return ___isKeys_1; } inline bool* get_address_of_isKeys_1() { return &___isKeys_1; } inline void set_isKeys_1(bool value) { ___isKeys_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NODEKEYVALUECOLLECTION_T1279341543_H #ifndef NODEENUMERATOR_T3248827953_H #define NODEENUMERATOR_T3248827953_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.ListDictionary/NodeEnumerator struct NodeEnumerator_t3248827953 : public RuntimeObject { public: // System.Collections.Specialized.ListDictionary System.Collections.Specialized.ListDictionary/NodeEnumerator::list ListDictionary_t1624492310 * ___list_0; // System.Collections.Specialized.ListDictionary/DictionaryNode System.Collections.Specialized.ListDictionary/NodeEnumerator::current DictionaryNode_t417719465 * ___current_1; // System.Int32 System.Collections.Specialized.ListDictionary/NodeEnumerator::version int32_t ___version_2; // System.Boolean System.Collections.Specialized.ListDictionary/NodeEnumerator::start bool ___start_3; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(NodeEnumerator_t3248827953, ___list_0)); } inline ListDictionary_t1624492310 * get_list_0() const { return ___list_0; } inline ListDictionary_t1624492310 ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(ListDictionary_t1624492310 * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((&___list_0), value); } inline static int32_t get_offset_of_current_1() { return static_cast<int32_t>(offsetof(NodeEnumerator_t3248827953, ___current_1)); } inline DictionaryNode_t417719465 * get_current_1() const { return ___current_1; } inline DictionaryNode_t417719465 ** get_address_of_current_1() { return &___current_1; } inline void set_current_1(DictionaryNode_t417719465 * value) { ___current_1 = value; Il2CppCodeGenWriteBarrier((&___current_1), value); } inline static int32_t get_offset_of_version_2() { return static_cast<int32_t>(offsetof(NodeEnumerator_t3248827953, ___version_2)); } inline int32_t get_version_2() const { return ___version_2; } inline int32_t* get_address_of_version_2() { return &___version_2; } inline void set_version_2(int32_t value) { ___version_2 = value; } inline static int32_t get_offset_of_start_3() { return static_cast<int32_t>(offsetof(NodeEnumerator_t3248827953, ___start_3)); } inline bool get_start_3() const { return ___start_3; } inline bool* get_address_of_start_3() { return &___start_3; } inline void set_start_3(bool value) { ___start_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NODEENUMERATOR_T3248827953_H #ifndef NODEKEYVALUEENUMERATOR_T642906510_H #define NODEKEYVALUEENUMERATOR_T642906510_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.ListDictionary/NodeKeyValueCollection/NodeKeyValueEnumerator struct NodeKeyValueEnumerator_t642906510 : public RuntimeObject { public: // System.Collections.Specialized.ListDictionary System.Collections.Specialized.ListDictionary/NodeKeyValueCollection/NodeKeyValueEnumerator::list ListDictionary_t1624492310 * ___list_0; // System.Collections.Specialized.ListDictionary/DictionaryNode System.Collections.Specialized.ListDictionary/NodeKeyValueCollection/NodeKeyValueEnumerator::current DictionaryNode_t417719465 * ___current_1; // System.Int32 System.Collections.Specialized.ListDictionary/NodeKeyValueCollection/NodeKeyValueEnumerator::version int32_t ___version_2; // System.Boolean System.Collections.Specialized.ListDictionary/NodeKeyValueCollection/NodeKeyValueEnumerator::isKeys bool ___isKeys_3; // System.Boolean System.Collections.Specialized.ListDictionary/NodeKeyValueCollection/NodeKeyValueEnumerator::start bool ___start_4; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(NodeKeyValueEnumerator_t642906510, ___list_0)); } inline ListDictionary_t1624492310 * get_list_0() const { return ___list_0; } inline ListDictionary_t1624492310 ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(ListDictionary_t1624492310 * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((&___list_0), value); } inline static int32_t get_offset_of_current_1() { return static_cast<int32_t>(offsetof(NodeKeyValueEnumerator_t642906510, ___current_1)); } inline DictionaryNode_t417719465 * get_current_1() const { return ___current_1; } inline DictionaryNode_t417719465 ** get_address_of_current_1() { return &___current_1; } inline void set_current_1(DictionaryNode_t417719465 * value) { ___current_1 = value; Il2CppCodeGenWriteBarrier((&___current_1), value); } inline static int32_t get_offset_of_version_2() { return static_cast<int32_t>(offsetof(NodeKeyValueEnumerator_t642906510, ___version_2)); } inline int32_t get_version_2() const { return ___version_2; } inline int32_t* get_address_of_version_2() { return &___version_2; } inline void set_version_2(int32_t value) { ___version_2 = value; } inline static int32_t get_offset_of_isKeys_3() { return static_cast<int32_t>(offsetof(NodeKeyValueEnumerator_t642906510, ___isKeys_3)); } inline bool get_isKeys_3() const { return ___isKeys_3; } inline bool* get_address_of_isKeys_3() { return &___isKeys_3; } inline void set_isKeys_3(bool value) { ___isKeys_3 = value; } inline static int32_t get_offset_of_start_4() { return static_cast<int32_t>(offsetof(NodeKeyValueEnumerator_t642906510, ___start_4)); } inline bool get_start_4() const { return ___start_4; } inline bool* get_address_of_start_4() { return &___start_4; } inline void set_start_4(bool value) { ___start_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NODEKEYVALUEENUMERATOR_T642906510_H #ifndef NAMEOBJECTCOLLECTIONBASE_T2091847364_H #define NAMEOBJECTCOLLECTIONBASE_T2091847364_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.NameObjectCollectionBase struct NameObjectCollectionBase_t2091847364 : public RuntimeObject { public: // System.Boolean System.Collections.Specialized.NameObjectCollectionBase::_readOnly bool ____readOnly_0; // System.Collections.ArrayList System.Collections.Specialized.NameObjectCollectionBase::_entriesArray ArrayList_t2718874744 * ____entriesArray_1; // System.Collections.IEqualityComparer System.Collections.Specialized.NameObjectCollectionBase::_keyComparer RuntimeObject* ____keyComparer_2; // System.Collections.Hashtable modreq(System.Runtime.CompilerServices.IsVolatile) System.Collections.Specialized.NameObjectCollectionBase::_entriesTable Hashtable_t1853889766 * ____entriesTable_3; // System.Collections.Specialized.NameObjectCollectionBase/NameObjectEntry modreq(System.Runtime.CompilerServices.IsVolatile) System.Collections.Specialized.NameObjectCollectionBase::_nullKeyEntry NameObjectEntry_t4224248211 * ____nullKeyEntry_4; // System.Collections.Specialized.NameObjectCollectionBase/KeysCollection System.Collections.Specialized.NameObjectCollectionBase::_keys KeysCollection_t1318642398 * ____keys_5; // System.Runtime.Serialization.SerializationInfo System.Collections.Specialized.NameObjectCollectionBase::_serializationInfo SerializationInfo_t950877179 * ____serializationInfo_6; // System.Int32 System.Collections.Specialized.NameObjectCollectionBase::_version int32_t ____version_7; // System.Object System.Collections.Specialized.NameObjectCollectionBase::_syncRoot RuntimeObject * ____syncRoot_8; public: inline static int32_t get_offset_of__readOnly_0() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____readOnly_0)); } inline bool get__readOnly_0() const { return ____readOnly_0; } inline bool* get_address_of__readOnly_0() { return &____readOnly_0; } inline void set__readOnly_0(bool value) { ____readOnly_0 = value; } inline static int32_t get_offset_of__entriesArray_1() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____entriesArray_1)); } inline ArrayList_t2718874744 * get__entriesArray_1() const { return ____entriesArray_1; } inline ArrayList_t2718874744 ** get_address_of__entriesArray_1() { return &____entriesArray_1; } inline void set__entriesArray_1(ArrayList_t2718874744 * value) { ____entriesArray_1 = value; Il2CppCodeGenWriteBarrier((&____entriesArray_1), value); } inline static int32_t get_offset_of__keyComparer_2() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____keyComparer_2)); } inline RuntimeObject* get__keyComparer_2() const { return ____keyComparer_2; } inline RuntimeObject** get_address_of__keyComparer_2() { return &____keyComparer_2; } inline void set__keyComparer_2(RuntimeObject* value) { ____keyComparer_2 = value; Il2CppCodeGenWriteBarrier((&____keyComparer_2), value); } inline static int32_t get_offset_of__entriesTable_3() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____entriesTable_3)); } inline Hashtable_t1853889766 * get__entriesTable_3() const { return ____entriesTable_3; } inline Hashtable_t1853889766 ** get_address_of__entriesTable_3() { return &____entriesTable_3; } inline void set__entriesTable_3(Hashtable_t1853889766 * value) { ____entriesTable_3 = value; Il2CppCodeGenWriteBarrier((&____entriesTable_3), value); } inline static int32_t get_offset_of__nullKeyEntry_4() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____nullKeyEntry_4)); } inline NameObjectEntry_t4224248211 * get__nullKeyEntry_4() const { return ____nullKeyEntry_4; } inline NameObjectEntry_t4224248211 ** get_address_of__nullKeyEntry_4() { return &____nullKeyEntry_4; } inline void set__nullKeyEntry_4(NameObjectEntry_t4224248211 * value) { ____nullKeyEntry_4 = value; Il2CppCodeGenWriteBarrier((&____nullKeyEntry_4), value); } inline static int32_t get_offset_of__keys_5() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____keys_5)); } inline KeysCollection_t1318642398 * get__keys_5() const { return ____keys_5; } inline KeysCollection_t1318642398 ** get_address_of__keys_5() { return &____keys_5; } inline void set__keys_5(KeysCollection_t1318642398 * value) { ____keys_5 = value; Il2CppCodeGenWriteBarrier((&____keys_5), value); } inline static int32_t get_offset_of__serializationInfo_6() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____serializationInfo_6)); } inline SerializationInfo_t950877179 * get__serializationInfo_6() const { return ____serializationInfo_6; } inline SerializationInfo_t950877179 ** get_address_of__serializationInfo_6() { return &____serializationInfo_6; } inline void set__serializationInfo_6(SerializationInfo_t950877179 * value) { ____serializationInfo_6 = value; Il2CppCodeGenWriteBarrier((&____serializationInfo_6), value); } inline static int32_t get_offset_of__version_7() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____version_7)); } inline int32_t get__version_7() const { return ____version_7; } inline int32_t* get_address_of__version_7() { return &____version_7; } inline void set__version_7(int32_t value) { ____version_7 = value; } inline static int32_t get_offset_of__syncRoot_8() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364, ____syncRoot_8)); } inline RuntimeObject * get__syncRoot_8() const { return ____syncRoot_8; } inline RuntimeObject ** get_address_of__syncRoot_8() { return &____syncRoot_8; } inline void set__syncRoot_8(RuntimeObject * value) { ____syncRoot_8 = value; Il2CppCodeGenWriteBarrier((&____syncRoot_8), value); } }; struct NameObjectCollectionBase_t2091847364_StaticFields { public: // System.StringComparer System.Collections.Specialized.NameObjectCollectionBase::defaultComparer StringComparer_t3301955079 * ___defaultComparer_9; public: inline static int32_t get_offset_of_defaultComparer_9() { return static_cast<int32_t>(offsetof(NameObjectCollectionBase_t2091847364_StaticFields, ___defaultComparer_9)); } inline StringComparer_t3301955079 * get_defaultComparer_9() const { return ___defaultComparer_9; } inline StringComparer_t3301955079 ** get_address_of_defaultComparer_9() { return &___defaultComparer_9; } inline void set_defaultComparer_9(StringComparer_t3301955079 * value) { ___defaultComparer_9 = value; Il2CppCodeGenWriteBarrier((&___defaultComparer_9), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NAMEOBJECTCOLLECTIONBASE_T2091847364_H #ifndef DICTIONARYNODE_T417719465_H #define DICTIONARYNODE_T417719465_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.ListDictionary/DictionaryNode struct DictionaryNode_t417719465 : public RuntimeObject { public: // System.Object System.Collections.Specialized.ListDictionary/DictionaryNode::key RuntimeObject * ___key_0; // System.Object System.Collections.Specialized.ListDictionary/DictionaryNode::value RuntimeObject * ___value_1; // System.Collections.Specialized.ListDictionary/DictionaryNode System.Collections.Specialized.ListDictionary/DictionaryNode::next DictionaryNode_t417719465 * ___next_2; public: inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(DictionaryNode_t417719465, ___key_0)); } inline RuntimeObject * get_key_0() const { return ___key_0; } inline RuntimeObject ** get_address_of_key_0() { return &___key_0; } inline void set_key_0(RuntimeObject * value) { ___key_0 = value; Il2CppCodeGenWriteBarrier((&___key_0), value); } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(DictionaryNode_t417719465, ___value_1)); } inline RuntimeObject * get_value_1() const { return ___value_1; } inline RuntimeObject ** get_address_of_value_1() { return &___value_1; } inline void set_value_1(RuntimeObject * value) { ___value_1 = value; Il2CppCodeGenWriteBarrier((&___value_1), value); } inline static int32_t get_offset_of_next_2() { return static_cast<int32_t>(offsetof(DictionaryNode_t417719465, ___next_2)); } inline DictionaryNode_t417719465 * get_next_2() const { return ___next_2; } inline DictionaryNode_t417719465 ** get_address_of_next_2() { return &___next_2; } inline void set_next_2(DictionaryNode_t417719465 * value) { ___next_2 = value; Il2CppCodeGenWriteBarrier((&___next_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DICTIONARYNODE_T417719465_H #ifndef INSTANCEDESCRIPTOR_T657473484_H #define INSTANCEDESCRIPTOR_T657473484_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.Design.Serialization.InstanceDescriptor struct InstanceDescriptor_t657473484 : public RuntimeObject { public: // System.Reflection.MemberInfo System.ComponentModel.Design.Serialization.InstanceDescriptor::member MemberInfo_t * ___member_0; // System.Collections.ICollection System.ComponentModel.Design.Serialization.InstanceDescriptor::arguments RuntimeObject* ___arguments_1; // System.Boolean System.ComponentModel.Design.Serialization.InstanceDescriptor::isComplete bool ___isComplete_2; public: inline static int32_t get_offset_of_member_0() { return static_cast<int32_t>(offsetof(InstanceDescriptor_t657473484, ___member_0)); } inline MemberInfo_t * get_member_0() const { return ___member_0; } inline MemberInfo_t ** get_address_of_member_0() { return &___member_0; } inline void set_member_0(MemberInfo_t * value) { ___member_0 = value; Il2CppCodeGenWriteBarrier((&___member_0), value); } inline static int32_t get_offset_of_arguments_1() { return static_cast<int32_t>(offsetof(InstanceDescriptor_t657473484, ___arguments_1)); } inline RuntimeObject* get_arguments_1() const { return ___arguments_1; } inline RuntimeObject** get_address_of_arguments_1() { return &___arguments_1; } inline void set_arguments_1(RuntimeObject* value) { ___arguments_1 = value; Il2CppCodeGenWriteBarrier((&___arguments_1), value); } inline static int32_t get_offset_of_isComplete_2() { return static_cast<int32_t>(offsetof(InstanceDescriptor_t657473484, ___isComplete_2)); } inline bool get_isComplete_2() const { return ___isComplete_2; } inline bool* get_address_of_isComplete_2() { return &___isComplete_2; } inline void set_isComplete_2(bool value) { ___isComplete_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INSTANCEDESCRIPTOR_T657473484_H #ifndef XPATHITEM_T4250588140_H #define XPATHITEM_T4250588140_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.XPath.XPathItem struct XPathItem_t4250588140 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHITEM_T4250588140_H #ifndef MARSHALBYREFOBJECT_T2760389100_H #define MARSHALBYREFOBJECT_T2760389100_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MarshalByRefObject struct MarshalByRefObject_t2760389100 : public RuntimeObject { public: // System.Runtime.Remoting.ServerIdentity System.MarshalByRefObject::_identity ServerIdentity_t2342208608 * ____identity_0; public: inline static int32_t get_offset_of__identity_0() { return static_cast<int32_t>(offsetof(MarshalByRefObject_t2760389100, ____identity_0)); } inline ServerIdentity_t2342208608 * get__identity_0() const { return ____identity_0; } inline ServerIdentity_t2342208608 ** get_address_of__identity_0() { return &____identity_0; } inline void set__identity_0(ServerIdentity_t2342208608 * value) { ____identity_0 = value; Il2CppCodeGenWriteBarrier((&____identity_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.MarshalByRefObject struct MarshalByRefObject_t2760389100_marshaled_pinvoke { ServerIdentity_t2342208608 * ____identity_0; }; // Native definition for COM marshalling of System.MarshalByRefObject struct MarshalByRefObject_t2760389100_marshaled_com { ServerIdentity_t2342208608 * ____identity_0; }; #endif // MARSHALBYREFOBJECT_T2760389100_H #ifndef LISTDICTIONARY_T1624492310_H #define LISTDICTIONARY_T1624492310_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.ListDictionary struct ListDictionary_t1624492310 : public RuntimeObject { public: // System.Collections.Specialized.ListDictionary/DictionaryNode System.Collections.Specialized.ListDictionary::head DictionaryNode_t417719465 * ___head_0; // System.Int32 System.Collections.Specialized.ListDictionary::version int32_t ___version_1; // System.Int32 System.Collections.Specialized.ListDictionary::count int32_t ___count_2; // System.Collections.IComparer System.Collections.Specialized.ListDictionary::comparer RuntimeObject* ___comparer_3; // System.Object System.Collections.Specialized.ListDictionary::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of_head_0() { return static_cast<int32_t>(offsetof(ListDictionary_t1624492310, ___head_0)); } inline DictionaryNode_t417719465 * get_head_0() const { return ___head_0; } inline DictionaryNode_t417719465 ** get_address_of_head_0() { return &___head_0; } inline void set_head_0(DictionaryNode_t417719465 * value) { ___head_0 = value; Il2CppCodeGenWriteBarrier((&___head_0), value); } inline static int32_t get_offset_of_version_1() { return static_cast<int32_t>(offsetof(ListDictionary_t1624492310, ___version_1)); } inline int32_t get_version_1() const { return ___version_1; } inline int32_t* get_address_of_version_1() { return &___version_1; } inline void set_version_1(int32_t value) { ___version_1 = value; } inline static int32_t get_offset_of_count_2() { return static_cast<int32_t>(offsetof(ListDictionary_t1624492310, ___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_comparer_3() { return static_cast<int32_t>(offsetof(ListDictionary_t1624492310, ___comparer_3)); } inline RuntimeObject* get_comparer_3() const { return ___comparer_3; } inline RuntimeObject** get_address_of_comparer_3() { return &___comparer_3; } inline void set_comparer_3(RuntimeObject* value) { ___comparer_3 = value; Il2CppCodeGenWriteBarrier((&___comparer_3), value); } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(ListDictionary_t1624492310, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((&____syncRoot_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LISTDICTIONARY_T1624492310_H #ifndef HYBRIDDICTIONARY_T4070033136_H #define HYBRIDDICTIONARY_T4070033136_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.HybridDictionary struct HybridDictionary_t4070033136 : public RuntimeObject { public: // System.Collections.Specialized.ListDictionary System.Collections.Specialized.HybridDictionary::list ListDictionary_t1624492310 * ___list_0; // System.Collections.Hashtable System.Collections.Specialized.HybridDictionary::hashtable Hashtable_t1853889766 * ___hashtable_1; // System.Boolean System.Collections.Specialized.HybridDictionary::caseInsensitive bool ___caseInsensitive_2; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(HybridDictionary_t4070033136, ___list_0)); } inline ListDictionary_t1624492310 * get_list_0() const { return ___list_0; } inline ListDictionary_t1624492310 ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(ListDictionary_t1624492310 * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((&___list_0), value); } inline static int32_t get_offset_of_hashtable_1() { return static_cast<int32_t>(offsetof(HybridDictionary_t4070033136, ___hashtable_1)); } inline Hashtable_t1853889766 * get_hashtable_1() const { return ___hashtable_1; } inline Hashtable_t1853889766 ** get_address_of_hashtable_1() { return &___hashtable_1; } inline void set_hashtable_1(Hashtable_t1853889766 * value) { ___hashtable_1 = value; Il2CppCodeGenWriteBarrier((&___hashtable_1), value); } inline static int32_t get_offset_of_caseInsensitive_2() { return static_cast<int32_t>(offsetof(HybridDictionary_t4070033136, ___caseInsensitive_2)); } inline bool get_caseInsensitive_2() const { return ___caseInsensitive_2; } inline bool* get_address_of_caseInsensitive_2() { return &___caseInsensitive_2; } inline void set_caseInsensitive_2(bool value) { ___caseInsensitive_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // HYBRIDDICTIONARY_T4070033136_H #ifndef NAMEOBJECTENTRY_T4224248211_H #define NAMEOBJECTENTRY_T4224248211_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.NameObjectCollectionBase/NameObjectEntry struct NameObjectEntry_t4224248211 : public RuntimeObject { public: // System.String System.Collections.Specialized.NameObjectCollectionBase/NameObjectEntry::Key String_t* ___Key_0; // System.Object System.Collections.Specialized.NameObjectCollectionBase/NameObjectEntry::Value RuntimeObject * ___Value_1; public: inline static int32_t get_offset_of_Key_0() { return static_cast<int32_t>(offsetof(NameObjectEntry_t4224248211, ___Key_0)); } inline String_t* get_Key_0() const { return ___Key_0; } inline String_t** get_address_of_Key_0() { return &___Key_0; } inline void set_Key_0(String_t* value) { ___Key_0 = value; Il2CppCodeGenWriteBarrier((&___Key_0), value); } inline static int32_t get_offset_of_Value_1() { return static_cast<int32_t>(offsetof(NameObjectEntry_t4224248211, ___Value_1)); } inline RuntimeObject * get_Value_1() const { return ___Value_1; } inline RuntimeObject ** get_address_of_Value_1() { return &___Value_1; } inline void set_Value_1(RuntimeObject * value) { ___Value_1 = value; Il2CppCodeGenWriteBarrier((&___Value_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NAMEOBJECTENTRY_T4224248211_H #ifndef ORDEREDDICTIONARYKEYVALUECOLLECTION_T1788601968_H #define ORDEREDDICTIONARYKEYVALUECOLLECTION_T1788601968_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.OrderedDictionary/OrderedDictionaryKeyValueCollection struct OrderedDictionaryKeyValueCollection_t1788601968 : public RuntimeObject { public: // System.Collections.ArrayList System.Collections.Specialized.OrderedDictionary/OrderedDictionaryKeyValueCollection::_objects ArrayList_t2718874744 * ____objects_0; // System.Boolean System.Collections.Specialized.OrderedDictionary/OrderedDictionaryKeyValueCollection::isKeys bool ___isKeys_1; public: inline static int32_t get_offset_of__objects_0() { return static_cast<int32_t>(offsetof(OrderedDictionaryKeyValueCollection_t1788601968, ____objects_0)); } inline ArrayList_t2718874744 * get__objects_0() const { return ____objects_0; } inline ArrayList_t2718874744 ** get_address_of__objects_0() { return &____objects_0; } inline void set__objects_0(ArrayList_t2718874744 * value) { ____objects_0 = value; Il2CppCodeGenWriteBarrier((&____objects_0), value); } inline static int32_t get_offset_of_isKeys_1() { return static_cast<int32_t>(offsetof(OrderedDictionaryKeyValueCollection_t1788601968, ___isKeys_1)); } inline bool get_isKeys_1() const { return ___isKeys_1; } inline bool* get_address_of_isKeys_1() { return &___isKeys_1; } inline void set_isKeys_1(bool value) { ___isKeys_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ORDEREDDICTIONARYKEYVALUECOLLECTION_T1788601968_H #ifndef ORDEREDDICTIONARY_T2617496293_H #define ORDEREDDICTIONARY_T2617496293_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.OrderedDictionary struct OrderedDictionary_t2617496293 : public RuntimeObject { public: // System.Collections.ArrayList System.Collections.Specialized.OrderedDictionary::_objectsArray ArrayList_t2718874744 * ____objectsArray_0; // System.Collections.Hashtable System.Collections.Specialized.OrderedDictionary::_objectsTable Hashtable_t1853889766 * ____objectsTable_1; // System.Int32 System.Collections.Specialized.OrderedDictionary::_initialCapacity int32_t ____initialCapacity_2; // System.Collections.IEqualityComparer System.Collections.Specialized.OrderedDictionary::_comparer RuntimeObject* ____comparer_3; // System.Boolean System.Collections.Specialized.OrderedDictionary::_readOnly bool ____readOnly_4; // System.Object System.Collections.Specialized.OrderedDictionary::_syncRoot RuntimeObject * ____syncRoot_5; // System.Runtime.Serialization.SerializationInfo System.Collections.Specialized.OrderedDictionary::_siInfo SerializationInfo_t950877179 * ____siInfo_6; public: inline static int32_t get_offset_of__objectsArray_0() { return static_cast<int32_t>(offsetof(OrderedDictionary_t2617496293, ____objectsArray_0)); } inline ArrayList_t2718874744 * get__objectsArray_0() const { return ____objectsArray_0; } inline ArrayList_t2718874744 ** get_address_of__objectsArray_0() { return &____objectsArray_0; } inline void set__objectsArray_0(ArrayList_t2718874744 * value) { ____objectsArray_0 = value; Il2CppCodeGenWriteBarrier((&____objectsArray_0), value); } inline static int32_t get_offset_of__objectsTable_1() { return static_cast<int32_t>(offsetof(OrderedDictionary_t2617496293, ____objectsTable_1)); } inline Hashtable_t1853889766 * get__objectsTable_1() const { return ____objectsTable_1; } inline Hashtable_t1853889766 ** get_address_of__objectsTable_1() { return &____objectsTable_1; } inline void set__objectsTable_1(Hashtable_t1853889766 * value) { ____objectsTable_1 = value; Il2CppCodeGenWriteBarrier((&____objectsTable_1), value); } inline static int32_t get_offset_of__initialCapacity_2() { return static_cast<int32_t>(offsetof(OrderedDictionary_t2617496293, ____initialCapacity_2)); } inline int32_t get__initialCapacity_2() const { return ____initialCapacity_2; } inline int32_t* get_address_of__initialCapacity_2() { return &____initialCapacity_2; } inline void set__initialCapacity_2(int32_t value) { ____initialCapacity_2 = value; } inline static int32_t get_offset_of__comparer_3() { return static_cast<int32_t>(offsetof(OrderedDictionary_t2617496293, ____comparer_3)); } inline RuntimeObject* get__comparer_3() const { return ____comparer_3; } inline RuntimeObject** get_address_of__comparer_3() { return &____comparer_3; } inline void set__comparer_3(RuntimeObject* value) { ____comparer_3 = value; Il2CppCodeGenWriteBarrier((&____comparer_3), value); } inline static int32_t get_offset_of__readOnly_4() { return static_cast<int32_t>(offsetof(OrderedDictionary_t2617496293, ____readOnly_4)); } inline bool get__readOnly_4() const { return ____readOnly_4; } inline bool* get_address_of__readOnly_4() { return &____readOnly_4; } inline void set__readOnly_4(bool value) { ____readOnly_4 = value; } inline static int32_t get_offset_of__syncRoot_5() { return static_cast<int32_t>(offsetof(OrderedDictionary_t2617496293, ____syncRoot_5)); } inline RuntimeObject * get__syncRoot_5() const { return ____syncRoot_5; } inline RuntimeObject ** get_address_of__syncRoot_5() { return &____syncRoot_5; } inline void set__syncRoot_5(RuntimeObject * value) { ____syncRoot_5 = value; Il2CppCodeGenWriteBarrier((&____syncRoot_5), value); } inline static int32_t get_offset_of__siInfo_6() { return static_cast<int32_t>(offsetof(OrderedDictionary_t2617496293, ____siInfo_6)); } inline SerializationInfo_t950877179 * get__siInfo_6() const { return ____siInfo_6; } inline SerializationInfo_t950877179 ** get_address_of__siInfo_6() { return &____siInfo_6; } inline void set__siInfo_6(SerializationInfo_t950877179 * value) { ____siInfo_6 = value; Il2CppCodeGenWriteBarrier((&____siInfo_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ORDEREDDICTIONARY_T2617496293_H #ifndef ORDEREDDICTIONARYENUMERATOR_T1215437281_H #define ORDEREDDICTIONARYENUMERATOR_T1215437281_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.OrderedDictionary/OrderedDictionaryEnumerator struct OrderedDictionaryEnumerator_t1215437281 : public RuntimeObject { public: // System.Int32 System.Collections.Specialized.OrderedDictionary/OrderedDictionaryEnumerator::_objectReturnType int32_t ____objectReturnType_0; // System.Collections.IEnumerator System.Collections.Specialized.OrderedDictionary/OrderedDictionaryEnumerator::arrayEnumerator RuntimeObject* ___arrayEnumerator_1; public: inline static int32_t get_offset_of__objectReturnType_0() { return static_cast<int32_t>(offsetof(OrderedDictionaryEnumerator_t1215437281, ____objectReturnType_0)); } inline int32_t get__objectReturnType_0() const { return ____objectReturnType_0; } inline int32_t* get_address_of__objectReturnType_0() { return &____objectReturnType_0; } inline void set__objectReturnType_0(int32_t value) { ____objectReturnType_0 = value; } inline static int32_t get_offset_of_arrayEnumerator_1() { return static_cast<int32_t>(offsetof(OrderedDictionaryEnumerator_t1215437281, ___arrayEnumerator_1)); } inline RuntimeObject* get_arrayEnumerator_1() const { return ___arrayEnumerator_1; } inline RuntimeObject** get_address_of_arrayEnumerator_1() { return &___arrayEnumerator_1; } inline void set_arrayEnumerator_1(RuntimeObject* value) { ___arrayEnumerator_1 = value; Il2CppCodeGenWriteBarrier((&___arrayEnumerator_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ORDEREDDICTIONARYENUMERATOR_T1215437281_H #ifndef NAMEOBJECTKEYSENUMERATOR_T3824388371_H #define NAMEOBJECTKEYSENUMERATOR_T3824388371_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.NameObjectCollectionBase/NameObjectKeysEnumerator struct NameObjectKeysEnumerator_t3824388371 : public RuntimeObject { public: // System.Int32 System.Collections.Specialized.NameObjectCollectionBase/NameObjectKeysEnumerator::_pos int32_t ____pos_0; // System.Collections.Specialized.NameObjectCollectionBase System.Collections.Specialized.NameObjectCollectionBase/NameObjectKeysEnumerator::_coll NameObjectCollectionBase_t2091847364 * ____coll_1; // System.Int32 System.Collections.Specialized.NameObjectCollectionBase/NameObjectKeysEnumerator::_version int32_t ____version_2; public: inline static int32_t get_offset_of__pos_0() { return static_cast<int32_t>(offsetof(NameObjectKeysEnumerator_t3824388371, ____pos_0)); } inline int32_t get__pos_0() const { return ____pos_0; } inline int32_t* get_address_of__pos_0() { return &____pos_0; } inline void set__pos_0(int32_t value) { ____pos_0 = value; } inline static int32_t get_offset_of__coll_1() { return static_cast<int32_t>(offsetof(NameObjectKeysEnumerator_t3824388371, ____coll_1)); } inline NameObjectCollectionBase_t2091847364 * get__coll_1() const { return ____coll_1; } inline NameObjectCollectionBase_t2091847364 ** get_address_of__coll_1() { return &____coll_1; } inline void set__coll_1(NameObjectCollectionBase_t2091847364 * value) { ____coll_1 = value; Il2CppCodeGenWriteBarrier((&____coll_1), value); } inline static int32_t get_offset_of__version_2() { return static_cast<int32_t>(offsetof(NameObjectKeysEnumerator_t3824388371, ____version_2)); } inline int32_t get__version_2() const { return ____version_2; } inline int32_t* get_address_of__version_2() { return &____version_2; } inline void set__version_2(int32_t value) { ____version_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NAMEOBJECTKEYSENUMERATOR_T3824388371_H #ifndef COMPATIBLECOMPARER_T4154576053_H #define COMPATIBLECOMPARER_T4154576053_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.CompatibleComparer struct CompatibleComparer_t4154576053 : public RuntimeObject { public: // System.Collections.IComparer System.Collections.Specialized.CompatibleComparer::_comparer RuntimeObject* ____comparer_0; // System.Collections.IHashCodeProvider System.Collections.Specialized.CompatibleComparer::_hcp RuntimeObject* ____hcp_2; public: inline static int32_t get_offset_of__comparer_0() { return static_cast<int32_t>(offsetof(CompatibleComparer_t4154576053, ____comparer_0)); } inline RuntimeObject* get__comparer_0() const { return ____comparer_0; } inline RuntimeObject** get_address_of__comparer_0() { return &____comparer_0; } inline void set__comparer_0(RuntimeObject* value) { ____comparer_0 = value; Il2CppCodeGenWriteBarrier((&____comparer_0), value); } inline static int32_t get_offset_of__hcp_2() { return static_cast<int32_t>(offsetof(CompatibleComparer_t4154576053, ____hcp_2)); } inline RuntimeObject* get__hcp_2() const { return ____hcp_2; } inline RuntimeObject** get_address_of__hcp_2() { return &____hcp_2; } inline void set__hcp_2(RuntimeObject* value) { ____hcp_2 = value; Il2CppCodeGenWriteBarrier((&____hcp_2), value); } }; struct CompatibleComparer_t4154576053_StaticFields { public: // System.Collections.IComparer modreq(System.Runtime.CompilerServices.IsVolatile) System.Collections.Specialized.CompatibleComparer::defaultComparer RuntimeObject* ___defaultComparer_1; // System.Collections.IHashCodeProvider modreq(System.Runtime.CompilerServices.IsVolatile) System.Collections.Specialized.CompatibleComparer::defaultHashProvider RuntimeObject* ___defaultHashProvider_3; public: inline static int32_t get_offset_of_defaultComparer_1() { return static_cast<int32_t>(offsetof(CompatibleComparer_t4154576053_StaticFields, ___defaultComparer_1)); } inline RuntimeObject* get_defaultComparer_1() const { return ___defaultComparer_1; } inline RuntimeObject** get_address_of_defaultComparer_1() { return &___defaultComparer_1; } inline void set_defaultComparer_1(RuntimeObject* value) { ___defaultComparer_1 = value; Il2CppCodeGenWriteBarrier((&___defaultComparer_1), value); } inline static int32_t get_offset_of_defaultHashProvider_3() { return static_cast<int32_t>(offsetof(CompatibleComparer_t4154576053_StaticFields, ___defaultHashProvider_3)); } inline RuntimeObject* get_defaultHashProvider_3() const { return ___defaultHashProvider_3; } inline RuntimeObject** get_address_of_defaultHashProvider_3() { return &___defaultHashProvider_3; } inline void set_defaultHashProvider_3(RuntimeObject* value) { ___defaultHashProvider_3 = value; Il2CppCodeGenWriteBarrier((&___defaultHashProvider_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMPATIBLECOMPARER_T4154576053_H #ifndef KEYSCOLLECTION_T1318642398_H #define KEYSCOLLECTION_T1318642398_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.NameObjectCollectionBase/KeysCollection struct KeysCollection_t1318642398 : public RuntimeObject { public: // System.Collections.Specialized.NameObjectCollectionBase System.Collections.Specialized.NameObjectCollectionBase/KeysCollection::_coll NameObjectCollectionBase_t2091847364 * ____coll_0; public: inline static int32_t get_offset_of__coll_0() { return static_cast<int32_t>(offsetof(KeysCollection_t1318642398, ____coll_0)); } inline NameObjectCollectionBase_t2091847364 * get__coll_0() const { return ____coll_0; } inline NameObjectCollectionBase_t2091847364 ** get_address_of__coll_0() { return &____coll_0; } inline void set__coll_0(NameObjectCollectionBase_t2091847364 * value) { ____coll_0 = value; Il2CppCodeGenWriteBarrier((&____coll_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // KEYSCOLLECTION_T1318642398_H #ifndef XPATHNODE_T2208072876_H #define XPATHNODE_T2208072876_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.Cache.XPathNode struct XPathNode_t2208072876 { public: // MS.Internal.Xml.Cache.XPathNodeInfoAtom MS.Internal.Xml.Cache.XPathNode::info XPathNodeInfoAtom_t1760358141 * ___info_0; // System.UInt16 MS.Internal.Xml.Cache.XPathNode::idxSibling uint16_t ___idxSibling_1; // System.UInt16 MS.Internal.Xml.Cache.XPathNode::idxParent uint16_t ___idxParent_2; // System.UInt16 MS.Internal.Xml.Cache.XPathNode::idxSimilar uint16_t ___idxSimilar_3; // System.UInt16 MS.Internal.Xml.Cache.XPathNode::posOffset uint16_t ___posOffset_4; // System.UInt32 MS.Internal.Xml.Cache.XPathNode::props uint32_t ___props_5; // System.String MS.Internal.Xml.Cache.XPathNode::value String_t* ___value_6; public: inline static int32_t get_offset_of_info_0() { return static_cast<int32_t>(offsetof(XPathNode_t2208072876, ___info_0)); } inline XPathNodeInfoAtom_t1760358141 * get_info_0() const { return ___info_0; } inline XPathNodeInfoAtom_t1760358141 ** get_address_of_info_0() { return &___info_0; } inline void set_info_0(XPathNodeInfoAtom_t1760358141 * value) { ___info_0 = value; Il2CppCodeGenWriteBarrier((&___info_0), value); } inline static int32_t get_offset_of_idxSibling_1() { return static_cast<int32_t>(offsetof(XPathNode_t2208072876, ___idxSibling_1)); } inline uint16_t get_idxSibling_1() const { return ___idxSibling_1; } inline uint16_t* get_address_of_idxSibling_1() { return &___idxSibling_1; } inline void set_idxSibling_1(uint16_t value) { ___idxSibling_1 = value; } inline static int32_t get_offset_of_idxParent_2() { return static_cast<int32_t>(offsetof(XPathNode_t2208072876, ___idxParent_2)); } inline uint16_t get_idxParent_2() const { return ___idxParent_2; } inline uint16_t* get_address_of_idxParent_2() { return &___idxParent_2; } inline void set_idxParent_2(uint16_t value) { ___idxParent_2 = value; } inline static int32_t get_offset_of_idxSimilar_3() { return static_cast<int32_t>(offsetof(XPathNode_t2208072876, ___idxSimilar_3)); } inline uint16_t get_idxSimilar_3() const { return ___idxSimilar_3; } inline uint16_t* get_address_of_idxSimilar_3() { return &___idxSimilar_3; } inline void set_idxSimilar_3(uint16_t value) { ___idxSimilar_3 = value; } inline static int32_t get_offset_of_posOffset_4() { return static_cast<int32_t>(offsetof(XPathNode_t2208072876, ___posOffset_4)); } inline uint16_t get_posOffset_4() const { return ___posOffset_4; } inline uint16_t* get_address_of_posOffset_4() { return &___posOffset_4; } inline void set_posOffset_4(uint16_t value) { ___posOffset_4 = value; } inline static int32_t get_offset_of_props_5() { return static_cast<int32_t>(offsetof(XPathNode_t2208072876, ___props_5)); } inline uint32_t get_props_5() const { return ___props_5; } inline uint32_t* get_address_of_props_5() { return &___props_5; } inline void set_props_5(uint32_t value) { ___props_5 = value; } inline static int32_t get_offset_of_value_6() { return static_cast<int32_t>(offsetof(XPathNode_t2208072876, ___value_6)); } inline String_t* get_value_6() const { return ___value_6; } inline String_t** get_address_of_value_6() { return &___value_6; } inline void set_value_6(String_t* value) { ___value_6 = value; Il2CppCodeGenWriteBarrier((&___value_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of MS.Internal.Xml.Cache.XPathNode struct XPathNode_t2208072876_marshaled_pinvoke { XPathNodeInfoAtom_t1760358141 * ___info_0; uint16_t ___idxSibling_1; uint16_t ___idxParent_2; uint16_t ___idxSimilar_3; uint16_t ___posOffset_4; uint32_t ___props_5; char* ___value_6; }; // Native definition for COM marshalling of MS.Internal.Xml.Cache.XPathNode struct XPathNode_t2208072876_marshaled_com { XPathNodeInfoAtom_t1760358141 * ___info_0; uint16_t ___idxSibling_1; uint16_t ___idxParent_2; uint16_t ___idxSimilar_3; uint16_t ___posOffset_4; uint32_t ___props_5; Il2CppChar* ___value_6; }; #endif // XPATHNODE_T2208072876_H #ifndef VARIABLE_T262588068_H #define VARIABLE_T262588068_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Variable struct Variable_t262588068 : public AstNode_t2514041814 { public: // System.String MS.Internal.Xml.XPath.Variable::localname String_t* ___localname_0; // System.String MS.Internal.Xml.XPath.Variable::prefix String_t* ___prefix_1; public: inline static int32_t get_offset_of_localname_0() { return static_cast<int32_t>(offsetof(Variable_t262588068, ___localname_0)); } inline String_t* get_localname_0() const { return ___localname_0; } inline String_t** get_address_of_localname_0() { return &___localname_0; } inline void set_localname_0(String_t* value) { ___localname_0 = value; Il2CppCodeGenWriteBarrier((&___localname_0), value); } inline static int32_t get_offset_of_prefix_1() { return static_cast<int32_t>(offsetof(Variable_t262588068, ___prefix_1)); } inline String_t* get_prefix_1() const { return ___prefix_1; } inline String_t** get_address_of_prefix_1() { return &___prefix_1; } inline void set_prefix_1(String_t* value) { ___prefix_1 = value; Il2CppCodeGenWriteBarrier((&___prefix_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VARIABLE_T262588068_H #ifndef ROOT_T720671714_H #define ROOT_T720671714_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Root struct Root_t720671714 : public AstNode_t2514041814 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ROOT_T720671714_H #ifndef XPATHNODEREF_T3498189018_H #define XPATHNODEREF_T3498189018_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.Cache.XPathNodeRef struct XPathNodeRef_t3498189018 { public: // MS.Internal.Xml.Cache.XPathNode[] MS.Internal.Xml.Cache.XPathNodeRef::page XPathNodeU5BU5D_t47339301* ___page_0; // System.Int32 MS.Internal.Xml.Cache.XPathNodeRef::idx int32_t ___idx_1; public: inline static int32_t get_offset_of_page_0() { return static_cast<int32_t>(offsetof(XPathNodeRef_t3498189018, ___page_0)); } inline XPathNodeU5BU5D_t47339301* get_page_0() const { return ___page_0; } inline XPathNodeU5BU5D_t47339301** get_address_of_page_0() { return &___page_0; } inline void set_page_0(XPathNodeU5BU5D_t47339301* value) { ___page_0 = value; Il2CppCodeGenWriteBarrier((&___page_0), value); } inline static int32_t get_offset_of_idx_1() { return static_cast<int32_t>(offsetof(XPathNodeRef_t3498189018, ___idx_1)); } inline int32_t get_idx_1() const { return ___idx_1; } inline int32_t* get_address_of_idx_1() { return &___idx_1; } inline void set_idx_1(int32_t value) { ___idx_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of MS.Internal.Xml.Cache.XPathNodeRef struct XPathNodeRef_t3498189018_marshaled_pinvoke { XPathNode_t2208072876_marshaled_pinvoke* ___page_0; int32_t ___idx_1; }; // Native definition for COM marshalling of MS.Internal.Xml.Cache.XPathNodeRef struct XPathNodeRef_t3498189018_marshaled_com { XPathNode_t2208072876_marshaled_com* ___page_0; int32_t ___idx_1; }; #endif // XPATHNODEREF_T3498189018_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 VOID_T1185182177_H #define VOID_T1185182177_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t1185182177 { public: union { struct { }; uint8_t Void_t1185182177__padding[1]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1185182177_H #ifndef GCHANDLE_T3351438187_H #define GCHANDLE_T3351438187_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.InteropServices.GCHandle struct GCHandle_t3351438187 { public: // System.Int32 System.Runtime.InteropServices.GCHandle::handle int32_t ___handle_0; public: inline static int32_t get_offset_of_handle_0() { return static_cast<int32_t>(offsetof(GCHandle_t3351438187, ___handle_0)); } inline int32_t get_handle_0() const { return ___handle_0; } inline int32_t* get_address_of_handle_0() { return &___handle_0; } inline void set_handle_0(int32_t value) { ___handle_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GCHANDLE_T3351438187_H #ifndef XPATHNAVIGATOR_T787956054_H #define XPATHNAVIGATOR_T787956054_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.XPath.XPathNavigator struct XPathNavigator_t787956054 : public XPathItem_t4250588140 { public: public: }; struct XPathNavigator_t787956054_StaticFields { public: // System.Xml.XPath.XPathNavigatorKeyComparer System.Xml.XPath.XPathNavigator::comparer XPathNavigatorKeyComparer_t2518900029 * ___comparer_0; // System.Char[] System.Xml.XPath.XPathNavigator::NodeTypeLetter CharU5BU5D_t3528271667* ___NodeTypeLetter_1; // System.Char[] System.Xml.XPath.XPathNavigator::UniqueIdTbl CharU5BU5D_t3528271667* ___UniqueIdTbl_2; // System.Int32[] System.Xml.XPath.XPathNavigator::ContentKindMasks Int32U5BU5D_t385246372* ___ContentKindMasks_3; public: inline static int32_t get_offset_of_comparer_0() { return static_cast<int32_t>(offsetof(XPathNavigator_t787956054_StaticFields, ___comparer_0)); } inline XPathNavigatorKeyComparer_t2518900029 * get_comparer_0() const { return ___comparer_0; } inline XPathNavigatorKeyComparer_t2518900029 ** get_address_of_comparer_0() { return &___comparer_0; } inline void set_comparer_0(XPathNavigatorKeyComparer_t2518900029 * value) { ___comparer_0 = value; Il2CppCodeGenWriteBarrier((&___comparer_0), value); } inline static int32_t get_offset_of_NodeTypeLetter_1() { return static_cast<int32_t>(offsetof(XPathNavigator_t787956054_StaticFields, ___NodeTypeLetter_1)); } inline CharU5BU5D_t3528271667* get_NodeTypeLetter_1() const { return ___NodeTypeLetter_1; } inline CharU5BU5D_t3528271667** get_address_of_NodeTypeLetter_1() { return &___NodeTypeLetter_1; } inline void set_NodeTypeLetter_1(CharU5BU5D_t3528271667* value) { ___NodeTypeLetter_1 = value; Il2CppCodeGenWriteBarrier((&___NodeTypeLetter_1), value); } inline static int32_t get_offset_of_UniqueIdTbl_2() { return static_cast<int32_t>(offsetof(XPathNavigator_t787956054_StaticFields, ___UniqueIdTbl_2)); } inline CharU5BU5D_t3528271667* get_UniqueIdTbl_2() const { return ___UniqueIdTbl_2; } inline CharU5BU5D_t3528271667** get_address_of_UniqueIdTbl_2() { return &___UniqueIdTbl_2; } inline void set_UniqueIdTbl_2(CharU5BU5D_t3528271667* value) { ___UniqueIdTbl_2 = value; Il2CppCodeGenWriteBarrier((&___UniqueIdTbl_2), value); } inline static int32_t get_offset_of_ContentKindMasks_3() { return static_cast<int32_t>(offsetof(XPathNavigator_t787956054_StaticFields, ___ContentKindMasks_3)); } inline Int32U5BU5D_t385246372* get_ContentKindMasks_3() const { return ___ContentKindMasks_3; } inline Int32U5BU5D_t385246372** get_address_of_ContentKindMasks_3() { return &___ContentKindMasks_3; } inline void set_ContentKindMasks_3(Int32U5BU5D_t385246372* value) { ___ContentKindMasks_3 = value; Il2CppCodeGenWriteBarrier((&___ContentKindMasks_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHNAVIGATOR_T787956054_H #ifndef XMLCHARTYPE_T2277243275_H #define XMLCHARTYPE_T2277243275_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.XmlCharType struct XmlCharType_t2277243275 { public: // System.Byte[] System.Xml.XmlCharType::charProperties ByteU5BU5D_t4116647657* ___charProperties_2; public: inline static int32_t get_offset_of_charProperties_2() { return static_cast<int32_t>(offsetof(XmlCharType_t2277243275, ___charProperties_2)); } inline ByteU5BU5D_t4116647657* get_charProperties_2() const { return ___charProperties_2; } inline ByteU5BU5D_t4116647657** get_address_of_charProperties_2() { return &___charProperties_2; } inline void set_charProperties_2(ByteU5BU5D_t4116647657* value) { ___charProperties_2 = value; Il2CppCodeGenWriteBarrier((&___charProperties_2), value); } }; struct XmlCharType_t2277243275_StaticFields { public: // System.Object System.Xml.XmlCharType::s_Lock RuntimeObject * ___s_Lock_0; // System.Byte[] modreq(System.Runtime.CompilerServices.IsVolatile) System.Xml.XmlCharType::s_CharProperties ByteU5BU5D_t4116647657* ___s_CharProperties_1; public: inline static int32_t get_offset_of_s_Lock_0() { return static_cast<int32_t>(offsetof(XmlCharType_t2277243275_StaticFields, ___s_Lock_0)); } inline RuntimeObject * get_s_Lock_0() const { return ___s_Lock_0; } inline RuntimeObject ** get_address_of_s_Lock_0() { return &___s_Lock_0; } inline void set_s_Lock_0(RuntimeObject * value) { ___s_Lock_0 = value; Il2CppCodeGenWriteBarrier((&___s_Lock_0), value); } inline static int32_t get_offset_of_s_CharProperties_1() { return static_cast<int32_t>(offsetof(XmlCharType_t2277243275_StaticFields, ___s_CharProperties_1)); } inline ByteU5BU5D_t4116647657* get_s_CharProperties_1() const { return ___s_CharProperties_1; } inline ByteU5BU5D_t4116647657** get_address_of_s_CharProperties_1() { return &___s_CharProperties_1; } inline void set_s_CharProperties_1(ByteU5BU5D_t4116647657* value) { ___s_CharProperties_1 = value; Il2CppCodeGenWriteBarrier((&___s_CharProperties_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Xml.XmlCharType struct XmlCharType_t2277243275_marshaled_pinvoke { uint8_t* ___charProperties_2; }; // Native definition for COM marshalling of System.Xml.XmlCharType struct XmlCharType_t2277243275_marshaled_com { uint8_t* ___charProperties_2; }; #endif // XMLCHARTYPE_T2277243275_H #ifndef INT32_T2950945753_H #define INT32_T2950945753_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 struct Int32_t2950945753 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_0)); } inline int32_t get_m_value_0() const { return ___m_value_0; } inline int32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int32_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32_T2950945753_H #ifndef BINHEXDECODER_T1474272384_H #define BINHEXDECODER_T1474272384_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.BinHexDecoder struct BinHexDecoder_t1474272384 : public IncrementalReadDecoder_t3011954239 { public: // System.Byte[] System.Xml.BinHexDecoder::buffer ByteU5BU5D_t4116647657* ___buffer_0; // System.Int32 System.Xml.BinHexDecoder::curIndex int32_t ___curIndex_1; // System.Int32 System.Xml.BinHexDecoder::endIndex int32_t ___endIndex_2; // System.Boolean System.Xml.BinHexDecoder::hasHalfByteCached bool ___hasHalfByteCached_3; // System.Byte System.Xml.BinHexDecoder::cachedHalfByte uint8_t ___cachedHalfByte_4; public: inline static int32_t get_offset_of_buffer_0() { return static_cast<int32_t>(offsetof(BinHexDecoder_t1474272384, ___buffer_0)); } inline ByteU5BU5D_t4116647657* get_buffer_0() const { return ___buffer_0; } inline ByteU5BU5D_t4116647657** get_address_of_buffer_0() { return &___buffer_0; } inline void set_buffer_0(ByteU5BU5D_t4116647657* value) { ___buffer_0 = value; Il2CppCodeGenWriteBarrier((&___buffer_0), value); } inline static int32_t get_offset_of_curIndex_1() { return static_cast<int32_t>(offsetof(BinHexDecoder_t1474272384, ___curIndex_1)); } inline int32_t get_curIndex_1() const { return ___curIndex_1; } inline int32_t* get_address_of_curIndex_1() { return &___curIndex_1; } inline void set_curIndex_1(int32_t value) { ___curIndex_1 = value; } inline static int32_t get_offset_of_endIndex_2() { return static_cast<int32_t>(offsetof(BinHexDecoder_t1474272384, ___endIndex_2)); } inline int32_t get_endIndex_2() const { return ___endIndex_2; } inline int32_t* get_address_of_endIndex_2() { return &___endIndex_2; } inline void set_endIndex_2(int32_t value) { ___endIndex_2 = value; } inline static int32_t get_offset_of_hasHalfByteCached_3() { return static_cast<int32_t>(offsetof(BinHexDecoder_t1474272384, ___hasHalfByteCached_3)); } inline bool get_hasHalfByteCached_3() const { return ___hasHalfByteCached_3; } inline bool* get_address_of_hasHalfByteCached_3() { return &___hasHalfByteCached_3; } inline void set_hasHalfByteCached_3(bool value) { ___hasHalfByteCached_3 = value; } inline static int32_t get_offset_of_cachedHalfByte_4() { return static_cast<int32_t>(offsetof(BinHexDecoder_t1474272384, ___cachedHalfByte_4)); } inline uint8_t get_cachedHalfByte_4() const { return ___cachedHalfByte_4; } inline uint8_t* get_address_of_cachedHalfByte_4() { return &___cachedHalfByte_4; } inline void set_cachedHalfByte_4(uint8_t value) { ___cachedHalfByte_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BINHEXDECODER_T1474272384_H #ifndef XMLTEXTWRITERBASE64ENCODER_T4259465041_H #define XMLTEXTWRITERBASE64ENCODER_T4259465041_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.XmlTextWriterBase64Encoder struct XmlTextWriterBase64Encoder_t4259465041 : public Base64Encoder_t3938083961 { public: // System.Xml.XmlTextEncoder System.Xml.XmlTextWriterBase64Encoder::xmlTextEncoder XmlTextEncoder_t1632274355 * ___xmlTextEncoder_3; public: inline static int32_t get_offset_of_xmlTextEncoder_3() { return static_cast<int32_t>(offsetof(XmlTextWriterBase64Encoder_t4259465041, ___xmlTextEncoder_3)); } inline XmlTextEncoder_t1632274355 * get_xmlTextEncoder_3() const { return ___xmlTextEncoder_3; } inline XmlTextEncoder_t1632274355 ** get_address_of_xmlTextEncoder_3() { return &___xmlTextEncoder_3; } inline void set_xmlTextEncoder_3(XmlTextEncoder_t1632274355 * value) { ___xmlTextEncoder_3 = value; Il2CppCodeGenWriteBarrier((&___xmlTextEncoder_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XMLTEXTWRITERBASE64ENCODER_T4259465041_H #ifndef INCREMENTALREADDUMMYDECODER_T2572367147_H #define INCREMENTALREADDUMMYDECODER_T2572367147_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.IncrementalReadDummyDecoder struct IncrementalReadDummyDecoder_t2572367147 : public IncrementalReadDecoder_t3011954239 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INCREMENTALREADDUMMYDECODER_T2572367147_H #ifndef STREAM_T1273022909_H #define STREAM_T1273022909_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.Stream struct Stream_t1273022909 : public MarshalByRefObject_t2760389100 { public: // System.IO.Stream/ReadWriteTask System.IO.Stream::_activeReadWriteTask ReadWriteTask_t156472862 * ____activeReadWriteTask_2; // System.Threading.SemaphoreSlim System.IO.Stream::_asyncActiveSemaphore SemaphoreSlim_t2974092902 * ____asyncActiveSemaphore_3; public: inline static int32_t get_offset_of__activeReadWriteTask_2() { return static_cast<int32_t>(offsetof(Stream_t1273022909, ____activeReadWriteTask_2)); } inline ReadWriteTask_t156472862 * get__activeReadWriteTask_2() const { return ____activeReadWriteTask_2; } inline ReadWriteTask_t156472862 ** get_address_of__activeReadWriteTask_2() { return &____activeReadWriteTask_2; } inline void set__activeReadWriteTask_2(ReadWriteTask_t156472862 * value) { ____activeReadWriteTask_2 = value; Il2CppCodeGenWriteBarrier((&____activeReadWriteTask_2), value); } inline static int32_t get_offset_of__asyncActiveSemaphore_3() { return static_cast<int32_t>(offsetof(Stream_t1273022909, ____asyncActiveSemaphore_3)); } inline SemaphoreSlim_t2974092902 * get__asyncActiveSemaphore_3() const { return ____asyncActiveSemaphore_3; } inline SemaphoreSlim_t2974092902 ** get_address_of__asyncActiveSemaphore_3() { return &____asyncActiveSemaphore_3; } inline void set__asyncActiveSemaphore_3(SemaphoreSlim_t2974092902 * value) { ____asyncActiveSemaphore_3 = value; Il2CppCodeGenWriteBarrier((&____asyncActiveSemaphore_3), value); } }; struct Stream_t1273022909_StaticFields { public: // System.IO.Stream System.IO.Stream::Null Stream_t1273022909 * ___Null_1; public: inline static int32_t get_offset_of_Null_1() { return static_cast<int32_t>(offsetof(Stream_t1273022909_StaticFields, ___Null_1)); } inline Stream_t1273022909 * get_Null_1() const { return ___Null_1; } inline Stream_t1273022909 ** get_address_of_Null_1() { return &___Null_1; } inline void set_Null_1(Stream_t1273022909 * value) { ___Null_1 = value; Il2CppCodeGenWriteBarrier((&___Null_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STREAM_T1273022909_H #ifndef ENUM_T4135868527_H #define ENUM_T4135868527_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t4135868527 : public ValueType_t3640485471 { public: public: }; struct Enum_t4135868527_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t3528271667* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t3528271667* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t3528271667** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t3528271667* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t4135868527_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t4135868527_marshaled_com { }; #endif // ENUM_T4135868527_H #ifndef __STATICARRAYINITTYPESIZEU3D256_T1757367633_H #define __STATICARRAYINITTYPESIZEU3D256_T1757367633_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=256 struct __StaticArrayInitTypeSizeU3D256_t1757367633 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D256_t1757367633__padding[256]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D256_T1757367633_H #ifndef __STATICARRAYINITTYPESIZEU3D128_T531529102_H #define __STATICARRAYINITTYPESIZEU3D128_T531529102_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=128 struct __StaticArrayInitTypeSizeU3D128_t531529102 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D128_t531529102__padding[128]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D128_T531529102_H #ifndef __STATICARRAYINITTYPESIZEU3D12_T2710994318_H #define __STATICARRAYINITTYPESIZEU3D12_T2710994318_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=12 struct __StaticArrayInitTypeSizeU3D12_t2710994318 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D12_t2710994318__padding[12]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D12_T2710994318_H #ifndef __STATICARRAYINITTYPESIZEU3D3_T3217885683_H #define __STATICARRAYINITTYPESIZEU3D3_T3217885683_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=3 struct __StaticArrayInitTypeSizeU3D3_t3217885683 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D3_t3217885683__padding[3]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D3_T3217885683_H #ifndef __STATICARRAYINITTYPESIZEU3D44_T3517366764_H #define __STATICARRAYINITTYPESIZEU3D44_T3517366764_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=44 struct __StaticArrayInitTypeSizeU3D44_t3517366764 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D44_t3517366764__padding[44]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D44_T3517366764_H #ifndef __STATICARRAYINITTYPESIZEU3D6_T3217689075_H #define __STATICARRAYINITTYPESIZEU3D6_T3217689075_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=6 struct __StaticArrayInitTypeSizeU3D6_t3217689075 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D6_t3217689075__padding[6]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D6_T3217689075_H #ifndef __STATICARRAYINITTYPESIZEU3D9_T3218278899_H #define __STATICARRAYINITTYPESIZEU3D9_T3218278899_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=9 struct __StaticArrayInitTypeSizeU3D9_t3218278899 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D9_t3218278899__padding[9]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D9_T3218278899_H #ifndef __STATICARRAYINITTYPESIZEU3D32_T2711125390_H #define __STATICARRAYINITTYPESIZEU3D32_T2711125390_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=32 struct __StaticArrayInitTypeSizeU3D32_t2711125390 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D32_t2711125390__padding[32]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D32_T2711125390_H #ifndef __STATICARRAYINITTYPESIZEU3D14_T3517563372_H #define __STATICARRAYINITTYPESIZEU3D14_T3517563372_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=14 struct __StaticArrayInitTypeSizeU3D14_t3517563372 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D14_t3517563372__padding[14]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D14_T3517563372_H #ifndef GROUP_T100818710_H #define GROUP_T100818710_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Group struct Group_t100818710 : public AstNode_t2514041814 { public: // MS.Internal.Xml.XPath.AstNode MS.Internal.Xml.XPath.Group::groupNode AstNode_t2514041814 * ___groupNode_0; public: inline static int32_t get_offset_of_groupNode_0() { return static_cast<int32_t>(offsetof(Group_t100818710, ___groupNode_0)); } inline AstNode_t2514041814 * get_groupNode_0() const { return ___groupNode_0; } inline AstNode_t2514041814 ** get_address_of_groupNode_0() { return &___groupNode_0; } inline void set_groupNode_0(AstNode_t2514041814 * value) { ___groupNode_0 = value; Il2CppCodeGenWriteBarrier((&___groupNode_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GROUP_T100818710_H #ifndef ROOTDESIGNERSERIALIZERATTRIBUTE_T3074689342_H #define ROOTDESIGNERSERIALIZERATTRIBUTE_T3074689342_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute struct RootDesignerSerializerAttribute_t3074689342 : public Attribute_t861562559 { public: // System.Boolean System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::reloadable bool ___reloadable_0; // System.String System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::serializerTypeName String_t* ___serializerTypeName_1; // System.String System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::serializerBaseTypeName String_t* ___serializerBaseTypeName_2; // System.String System.ComponentModel.Design.Serialization.RootDesignerSerializerAttribute::typeId String_t* ___typeId_3; public: inline static int32_t get_offset_of_reloadable_0() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_t3074689342, ___reloadable_0)); } inline bool get_reloadable_0() const { return ___reloadable_0; } inline bool* get_address_of_reloadable_0() { return &___reloadable_0; } inline void set_reloadable_0(bool value) { ___reloadable_0 = value; } inline static int32_t get_offset_of_serializerTypeName_1() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_t3074689342, ___serializerTypeName_1)); } inline String_t* get_serializerTypeName_1() const { return ___serializerTypeName_1; } inline String_t** get_address_of_serializerTypeName_1() { return &___serializerTypeName_1; } inline void set_serializerTypeName_1(String_t* value) { ___serializerTypeName_1 = value; Il2CppCodeGenWriteBarrier((&___serializerTypeName_1), value); } inline static int32_t get_offset_of_serializerBaseTypeName_2() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_t3074689342, ___serializerBaseTypeName_2)); } inline String_t* get_serializerBaseTypeName_2() const { return ___serializerBaseTypeName_2; } inline String_t** get_address_of_serializerBaseTypeName_2() { return &___serializerBaseTypeName_2; } inline void set_serializerBaseTypeName_2(String_t* value) { ___serializerBaseTypeName_2 = value; Il2CppCodeGenWriteBarrier((&___serializerBaseTypeName_2), value); } inline static int32_t get_offset_of_typeId_3() { return static_cast<int32_t>(offsetof(RootDesignerSerializerAttribute_t3074689342, ___typeId_3)); } inline String_t* get_typeId_3() const { return ___typeId_3; } inline String_t** get_address_of_typeId_3() { return &___typeId_3; } inline void set_typeId_3(String_t* value) { ___typeId_3 = value; Il2CppCodeGenWriteBarrier((&___typeId_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ROOTDESIGNERSERIALIZERATTRIBUTE_T3074689342_H #ifndef FILTER_T1571657935_H #define FILTER_T1571657935_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Filter struct Filter_t1571657935 : public AstNode_t2514041814 { public: // MS.Internal.Xml.XPath.AstNode MS.Internal.Xml.XPath.Filter::input AstNode_t2514041814 * ___input_0; // MS.Internal.Xml.XPath.AstNode MS.Internal.Xml.XPath.Filter::condition AstNode_t2514041814 * ___condition_1; public: inline static int32_t get_offset_of_input_0() { return static_cast<int32_t>(offsetof(Filter_t1571657935, ___input_0)); } inline AstNode_t2514041814 * get_input_0() const { return ___input_0; } inline AstNode_t2514041814 ** get_address_of_input_0() { return &___input_0; } inline void set_input_0(AstNode_t2514041814 * value) { ___input_0 = value; Il2CppCodeGenWriteBarrier((&___input_0), value); } inline static int32_t get_offset_of_condition_1() { return static_cast<int32_t>(offsetof(Filter_t1571657935, ___condition_1)); } inline AstNode_t2514041814 * get_condition_1() const { return ___condition_1; } inline AstNode_t2514041814 ** get_address_of_condition_1() { return &___condition_1; } inline void set_condition_1(AstNode_t2514041814 * value) { ___condition_1 = value; Il2CppCodeGenWriteBarrier((&___condition_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FILTER_T1571657935_H #ifndef NAMEVALUECOLLECTION_T407452768_H #define NAMEVALUECOLLECTION_T407452768_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Specialized.NameValueCollection struct NameValueCollection_t407452768 : public NameObjectCollectionBase_t2091847364 { public: // System.String[] System.Collections.Specialized.NameValueCollection::_all StringU5BU5D_t1281789340* ____all_10; // System.String[] System.Collections.Specialized.NameValueCollection::_allKeys StringU5BU5D_t1281789340* ____allKeys_11; public: inline static int32_t get_offset_of__all_10() { return static_cast<int32_t>(offsetof(NameValueCollection_t407452768, ____all_10)); } inline StringU5BU5D_t1281789340* get__all_10() const { return ____all_10; } inline StringU5BU5D_t1281789340** get_address_of__all_10() { return &____all_10; } inline void set__all_10(StringU5BU5D_t1281789340* value) { ____all_10 = value; Il2CppCodeGenWriteBarrier((&____all_10), value); } inline static int32_t get_offset_of__allKeys_11() { return static_cast<int32_t>(offsetof(NameValueCollection_t407452768, ____allKeys_11)); } inline StringU5BU5D_t1281789340* get__allKeys_11() const { return ____allKeys_11; } inline StringU5BU5D_t1281789340** get_address_of__allKeys_11() { return &____allKeys_11; } inline void set__allKeys_11(StringU5BU5D_t1281789340* value) { ____allKeys_11 = value; Il2CppCodeGenWriteBarrier((&____allKeys_11), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NAMEVALUECOLLECTION_T407452768_H #ifndef DESIGNERSERIALIZERATTRIBUTE_T1570548024_H #define DESIGNERSERIALIZERATTRIBUTE_T1570548024_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.Design.Serialization.DesignerSerializerAttribute struct DesignerSerializerAttribute_t1570548024 : public Attribute_t861562559 { public: // System.String System.ComponentModel.Design.Serialization.DesignerSerializerAttribute::serializerTypeName String_t* ___serializerTypeName_0; // System.String System.ComponentModel.Design.Serialization.DesignerSerializerAttribute::serializerBaseTypeName String_t* ___serializerBaseTypeName_1; // System.String System.ComponentModel.Design.Serialization.DesignerSerializerAttribute::typeId String_t* ___typeId_2; public: inline static int32_t get_offset_of_serializerTypeName_0() { return static_cast<int32_t>(offsetof(DesignerSerializerAttribute_t1570548024, ___serializerTypeName_0)); } inline String_t* get_serializerTypeName_0() const { return ___serializerTypeName_0; } inline String_t** get_address_of_serializerTypeName_0() { return &___serializerTypeName_0; } inline void set_serializerTypeName_0(String_t* value) { ___serializerTypeName_0 = value; Il2CppCodeGenWriteBarrier((&___serializerTypeName_0), value); } inline static int32_t get_offset_of_serializerBaseTypeName_1() { return static_cast<int32_t>(offsetof(DesignerSerializerAttribute_t1570548024, ___serializerBaseTypeName_1)); } inline String_t* get_serializerBaseTypeName_1() const { return ___serializerBaseTypeName_1; } inline String_t** get_address_of_serializerBaseTypeName_1() { return &___serializerBaseTypeName_1; } inline void set_serializerBaseTypeName_1(String_t* value) { ___serializerBaseTypeName_1 = value; Il2CppCodeGenWriteBarrier((&___serializerBaseTypeName_1), value); } inline static int32_t get_offset_of_typeId_2() { return static_cast<int32_t>(offsetof(DesignerSerializerAttribute_t1570548024, ___typeId_2)); } inline String_t* get_typeId_2() const { return ___typeId_2; } inline String_t** get_address_of_typeId_2() { return &___typeId_2; } inline void set_typeId_2(String_t* value) { ___typeId_2 = value; Il2CppCodeGenWriteBarrier((&___typeId_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DESIGNERSERIALIZERATTRIBUTE_T1570548024_H #ifndef FUNCTIONTYPE_T3319434782_H #define FUNCTIONTYPE_T3319434782_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Function/FunctionType struct FunctionType_t3319434782 { public: // System.Int32 MS.Internal.Xml.XPath.Function/FunctionType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(FunctionType_t3319434782, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FUNCTIONTYPE_T3319434782_H #ifndef DELEGATE_T1188392813_H #define DELEGATE_T1188392813_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Delegate struct Delegate_t1188392813 : 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::extra_arg intptr_t ___extra_arg_5; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_6; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_7; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_8; // System.DelegateData System.Delegate::data DelegateData_t1677132599 * ___data_9; // System.Boolean System.Delegate::method_is_virtual bool ___method_is_virtual_10; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___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_t1188392813, ___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_t1188392813, ___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_t1188392813, ___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_t1188392813, ___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_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___extra_arg_5)); } inline intptr_t get_extra_arg_5() const { return ___extra_arg_5; } inline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; } inline void set_extra_arg_5(intptr_t value) { ___extra_arg_5 = value; } inline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_code_6)); } inline intptr_t get_method_code_6() const { return ___method_code_6; } inline intptr_t* get_address_of_method_code_6() { return &___method_code_6; } inline void set_method_code_6(intptr_t value) { ___method_code_6 = value; } inline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_info_7)); } inline MethodInfo_t * get_method_info_7() const { return ___method_info_7; } inline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; } inline void set_method_info_7(MethodInfo_t * value) { ___method_info_7 = value; Il2CppCodeGenWriteBarrier((&___method_info_7), value); } inline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___original_method_info_8)); } inline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; } inline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; } inline void set_original_method_info_8(MethodInfo_t * value) { ___original_method_info_8 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_8), value); } inline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___data_9)); } inline DelegateData_t1677132599 * get_data_9() const { return ___data_9; } inline DelegateData_t1677132599 ** get_address_of_data_9() { return &___data_9; } inline void set_data_9(DelegateData_t1677132599 * value) { ___data_9 = value; Il2CppCodeGenWriteBarrier((&___data_9), value); } inline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_is_virtual_10)); } inline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; } inline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; } inline void set_method_is_virtual_10(bool value) { ___method_is_virtual_10 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Delegate struct Delegate_t1188392813_marshaled_pinvoke { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t1677132599 * ___data_9; int32_t ___method_is_virtual_10; }; // Native definition for COM marshalling of System.Delegate struct Delegate_t1188392813_marshaled_com { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t1677132599 * ___data_9; int32_t ___method_is_virtual_10; }; #endif // DELEGATE_T1188392813_H #ifndef COMPRESSIONMODE_T3714291783_H #define COMPRESSIONMODE_T3714291783_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.Compression.CompressionMode struct CompressionMode_t3714291783 { public: // System.Int32 System.IO.Compression.CompressionMode::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(CompressionMode_t3714291783, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMPRESSIONMODE_T3714291783_H #ifndef DEFLATESTREAMNATIVE_T1405046456_H #define DEFLATESTREAMNATIVE_T1405046456_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.Compression.DeflateStreamNative struct DeflateStreamNative_t1405046456 : public RuntimeObject { public: // System.IO.Compression.DeflateStreamNative/UnmanagedReadOrWrite System.IO.Compression.DeflateStreamNative::feeder UnmanagedReadOrWrite_t1975956110 * ___feeder_0; // System.IO.Stream System.IO.Compression.DeflateStreamNative::base_stream Stream_t1273022909 * ___base_stream_1; // System.IntPtr System.IO.Compression.DeflateStreamNative::z_stream intptr_t ___z_stream_2; // System.Runtime.InteropServices.GCHandle System.IO.Compression.DeflateStreamNative::data GCHandle_t3351438187 ___data_3; // System.Boolean System.IO.Compression.DeflateStreamNative::disposed bool ___disposed_4; // System.Byte[] System.IO.Compression.DeflateStreamNative::io_buffer ByteU5BU5D_t4116647657* ___io_buffer_5; public: inline static int32_t get_offset_of_feeder_0() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t1405046456, ___feeder_0)); } inline UnmanagedReadOrWrite_t1975956110 * get_feeder_0() const { return ___feeder_0; } inline UnmanagedReadOrWrite_t1975956110 ** get_address_of_feeder_0() { return &___feeder_0; } inline void set_feeder_0(UnmanagedReadOrWrite_t1975956110 * value) { ___feeder_0 = value; Il2CppCodeGenWriteBarrier((&___feeder_0), value); } inline static int32_t get_offset_of_base_stream_1() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t1405046456, ___base_stream_1)); } inline Stream_t1273022909 * get_base_stream_1() const { return ___base_stream_1; } inline Stream_t1273022909 ** get_address_of_base_stream_1() { return &___base_stream_1; } inline void set_base_stream_1(Stream_t1273022909 * value) { ___base_stream_1 = value; Il2CppCodeGenWriteBarrier((&___base_stream_1), value); } inline static int32_t get_offset_of_z_stream_2() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t1405046456, ___z_stream_2)); } inline intptr_t get_z_stream_2() const { return ___z_stream_2; } inline intptr_t* get_address_of_z_stream_2() { return &___z_stream_2; } inline void set_z_stream_2(intptr_t value) { ___z_stream_2 = value; } inline static int32_t get_offset_of_data_3() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t1405046456, ___data_3)); } inline GCHandle_t3351438187 get_data_3() const { return ___data_3; } inline GCHandle_t3351438187 * get_address_of_data_3() { return &___data_3; } inline void set_data_3(GCHandle_t3351438187 value) { ___data_3 = value; } inline static int32_t get_offset_of_disposed_4() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t1405046456, ___disposed_4)); } inline bool get_disposed_4() const { return ___disposed_4; } inline bool* get_address_of_disposed_4() { return &___disposed_4; } inline void set_disposed_4(bool value) { ___disposed_4 = value; } inline static int32_t get_offset_of_io_buffer_5() { return static_cast<int32_t>(offsetof(DeflateStreamNative_t1405046456, ___io_buffer_5)); } inline ByteU5BU5D_t4116647657* get_io_buffer_5() const { return ___io_buffer_5; } inline ByteU5BU5D_t4116647657** get_address_of_io_buffer_5() { return &___io_buffer_5; } inline void set_io_buffer_5(ByteU5BU5D_t4116647657* value) { ___io_buffer_5 = value; Il2CppCodeGenWriteBarrier((&___io_buffer_5), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DEFLATESTREAMNATIVE_T1405046456_H #ifndef GZIPSTREAM_T3417139389_H #define GZIPSTREAM_T3417139389_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.Compression.GZipStream struct GZipStream_t3417139389 : public Stream_t1273022909 { public: // System.IO.Compression.DeflateStream System.IO.Compression.GZipStream::_deflateStream DeflateStream_t4175168077 * ____deflateStream_4; public: inline static int32_t get_offset_of__deflateStream_4() { return static_cast<int32_t>(offsetof(GZipStream_t3417139389, ____deflateStream_4)); } inline DeflateStream_t4175168077 * get__deflateStream_4() const { return ____deflateStream_4; } inline DeflateStream_t4175168077 ** get_address_of__deflateStream_4() { return &____deflateStream_4; } inline void set__deflateStream_4(DeflateStream_t4175168077 * value) { ____deflateStream_4 = value; Il2CppCodeGenWriteBarrier((&____deflateStream_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GZIPSTREAM_T3417139389_H #ifndef U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255362_H #define U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255362_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails> struct U3CPrivateImplementationDetailsU3E_t3057255362 : public RuntimeObject { public: public: }; struct U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields { public: // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=14 <PrivateImplementationDetails>::0283A6AF88802AB45989B29549915BEA0F6CD515 __StaticArrayInitTypeSizeU3D14_t3517563372 ___0283A6AF88802AB45989B29549915BEA0F6CD515_0; // System.Int64 <PrivateImplementationDetails>::03F4297FCC30D0FD5E420E5D26E7FA711167C7EF int64_t ___03F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=9 <PrivateImplementationDetails>::1A39764B112685485A5BA7B2880D878B858C1A7A __StaticArrayInitTypeSizeU3D9_t3218278899 ___1A39764B112685485A5BA7B2880D878B858C1A7A_2; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>::1A84029C80CB5518379F199F53FF08A7B764F8FD __StaticArrayInitTypeSizeU3D3_t3217885683 ___1A84029C80CB5518379F199F53FF08A7B764F8FD_3; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>::3BE77BF818331C2D8400FFFFF9FADD3F16AD89AC __StaticArrayInitTypeSizeU3D12_t2710994318 ___3BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>::59F5BD34B6C013DEACC784F69C67E95150033A84 __StaticArrayInitTypeSizeU3D32_t2711125390 ___59F5BD34B6C013DEACC784F69C67E95150033A84_5; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=6 <PrivateImplementationDetails>::5BC3486B05BA8CF4689C7BDB198B3F477BB4E20C __StaticArrayInitTypeSizeU3D6_t3217689075 ___5BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=9 <PrivateImplementationDetails>::6D49C9D487D7AD3491ECE08732D68A593CC2038D __StaticArrayInitTypeSizeU3D9_t3218278899 ___6D49C9D487D7AD3491ECE08732D68A593CC2038D_7; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=128 <PrivateImplementationDetails>::6F3AD3DC3AF8047587C4C9D696EB68A01FEF796E __StaticArrayInitTypeSizeU3D128_t531529102 ___6F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=44 <PrivateImplementationDetails>::8E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3 __StaticArrayInitTypeSizeU3D44_t3517366764 ___8E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9; // System.Int64 <PrivateImplementationDetails>::98A44A6F8606AE6F23FE230286C1D6FBCC407226 int64_t ___98A44A6F8606AE6F23FE230286C1D6FBCC407226_10; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>::C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536 __StaticArrayInitTypeSizeU3D32_t2711125390 ___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=128 <PrivateImplementationDetails>::CCEEADA43268372341F81AE0C9208C6856441C04 __StaticArrayInitTypeSizeU3D128_t531529102 ___CCEEADA43268372341F81AE0C9208C6856441C04_12; // System.Int64 <PrivateImplementationDetails>::E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78 int64_t ___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>::EC5842B3154E1AF94500B57220EB9F684BCCC42A __StaticArrayInitTypeSizeU3D32_t2711125390 ___EC5842B3154E1AF94500B57220EB9F684BCCC42A_14; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=256 <PrivateImplementationDetails>::EEAFE8C6E1AB017237567305EE925C976CDB6458 __StaticArrayInitTypeSizeU3D256_t1757367633 ___EEAFE8C6E1AB017237567305EE925C976CDB6458_15; public: inline static int32_t get_offset_of_U30283A6AF88802AB45989B29549915BEA0F6CD515_0() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___0283A6AF88802AB45989B29549915BEA0F6CD515_0)); } inline __StaticArrayInitTypeSizeU3D14_t3517563372 get_U30283A6AF88802AB45989B29549915BEA0F6CD515_0() const { return ___0283A6AF88802AB45989B29549915BEA0F6CD515_0; } inline __StaticArrayInitTypeSizeU3D14_t3517563372 * get_address_of_U30283A6AF88802AB45989B29549915BEA0F6CD515_0() { return &___0283A6AF88802AB45989B29549915BEA0F6CD515_0; } inline void set_U30283A6AF88802AB45989B29549915BEA0F6CD515_0(__StaticArrayInitTypeSizeU3D14_t3517563372 value) { ___0283A6AF88802AB45989B29549915BEA0F6CD515_0 = value; } inline static int32_t get_offset_of_U303F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___03F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1)); } inline int64_t get_U303F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1() const { return ___03F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1; } inline int64_t* get_address_of_U303F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1() { return &___03F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1; } inline void set_U303F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1(int64_t value) { ___03F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1 = value; } inline static int32_t get_offset_of_U31A39764B112685485A5BA7B2880D878B858C1A7A_2() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___1A39764B112685485A5BA7B2880D878B858C1A7A_2)); } inline __StaticArrayInitTypeSizeU3D9_t3218278899 get_U31A39764B112685485A5BA7B2880D878B858C1A7A_2() const { return ___1A39764B112685485A5BA7B2880D878B858C1A7A_2; } inline __StaticArrayInitTypeSizeU3D9_t3218278899 * get_address_of_U31A39764B112685485A5BA7B2880D878B858C1A7A_2() { return &___1A39764B112685485A5BA7B2880D878B858C1A7A_2; } inline void set_U31A39764B112685485A5BA7B2880D878B858C1A7A_2(__StaticArrayInitTypeSizeU3D9_t3218278899 value) { ___1A39764B112685485A5BA7B2880D878B858C1A7A_2 = value; } inline static int32_t get_offset_of_U31A84029C80CB5518379F199F53FF08A7B764F8FD_3() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___1A84029C80CB5518379F199F53FF08A7B764F8FD_3)); } inline __StaticArrayInitTypeSizeU3D3_t3217885683 get_U31A84029C80CB5518379F199F53FF08A7B764F8FD_3() const { return ___1A84029C80CB5518379F199F53FF08A7B764F8FD_3; } inline __StaticArrayInitTypeSizeU3D3_t3217885683 * get_address_of_U31A84029C80CB5518379F199F53FF08A7B764F8FD_3() { return &___1A84029C80CB5518379F199F53FF08A7B764F8FD_3; } inline void set_U31A84029C80CB5518379F199F53FF08A7B764F8FD_3(__StaticArrayInitTypeSizeU3D3_t3217885683 value) { ___1A84029C80CB5518379F199F53FF08A7B764F8FD_3 = value; } inline static int32_t get_offset_of_U33BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___3BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4)); } inline __StaticArrayInitTypeSizeU3D12_t2710994318 get_U33BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4() const { return ___3BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4; } inline __StaticArrayInitTypeSizeU3D12_t2710994318 * get_address_of_U33BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4() { return &___3BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4; } inline void set_U33BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4(__StaticArrayInitTypeSizeU3D12_t2710994318 value) { ___3BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4 = value; } inline static int32_t get_offset_of_U359F5BD34B6C013DEACC784F69C67E95150033A84_5() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___59F5BD34B6C013DEACC784F69C67E95150033A84_5)); } inline __StaticArrayInitTypeSizeU3D32_t2711125390 get_U359F5BD34B6C013DEACC784F69C67E95150033A84_5() const { return ___59F5BD34B6C013DEACC784F69C67E95150033A84_5; } inline __StaticArrayInitTypeSizeU3D32_t2711125390 * get_address_of_U359F5BD34B6C013DEACC784F69C67E95150033A84_5() { return &___59F5BD34B6C013DEACC784F69C67E95150033A84_5; } inline void set_U359F5BD34B6C013DEACC784F69C67E95150033A84_5(__StaticArrayInitTypeSizeU3D32_t2711125390 value) { ___59F5BD34B6C013DEACC784F69C67E95150033A84_5 = value; } inline static int32_t get_offset_of_U35BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___5BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6)); } inline __StaticArrayInitTypeSizeU3D6_t3217689075 get_U35BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6() const { return ___5BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6; } inline __StaticArrayInitTypeSizeU3D6_t3217689075 * get_address_of_U35BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6() { return &___5BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6; } inline void set_U35BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6(__StaticArrayInitTypeSizeU3D6_t3217689075 value) { ___5BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6 = value; } inline static int32_t get_offset_of_U36D49C9D487D7AD3491ECE08732D68A593CC2038D_7() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___6D49C9D487D7AD3491ECE08732D68A593CC2038D_7)); } inline __StaticArrayInitTypeSizeU3D9_t3218278899 get_U36D49C9D487D7AD3491ECE08732D68A593CC2038D_7() const { return ___6D49C9D487D7AD3491ECE08732D68A593CC2038D_7; } inline __StaticArrayInitTypeSizeU3D9_t3218278899 * get_address_of_U36D49C9D487D7AD3491ECE08732D68A593CC2038D_7() { return &___6D49C9D487D7AD3491ECE08732D68A593CC2038D_7; } inline void set_U36D49C9D487D7AD3491ECE08732D68A593CC2038D_7(__StaticArrayInitTypeSizeU3D9_t3218278899 value) { ___6D49C9D487D7AD3491ECE08732D68A593CC2038D_7 = value; } inline static int32_t get_offset_of_U36F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___6F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8)); } inline __StaticArrayInitTypeSizeU3D128_t531529102 get_U36F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8() const { return ___6F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8; } inline __StaticArrayInitTypeSizeU3D128_t531529102 * get_address_of_U36F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8() { return &___6F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8; } inline void set_U36F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8(__StaticArrayInitTypeSizeU3D128_t531529102 value) { ___6F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8 = value; } inline static int32_t get_offset_of_U38E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___8E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9)); } inline __StaticArrayInitTypeSizeU3D44_t3517366764 get_U38E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9() const { return ___8E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9; } inline __StaticArrayInitTypeSizeU3D44_t3517366764 * get_address_of_U38E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9() { return &___8E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9; } inline void set_U38E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9(__StaticArrayInitTypeSizeU3D44_t3517366764 value) { ___8E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9 = value; } inline static int32_t get_offset_of_U398A44A6F8606AE6F23FE230286C1D6FBCC407226_10() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___98A44A6F8606AE6F23FE230286C1D6FBCC407226_10)); } inline int64_t get_U398A44A6F8606AE6F23FE230286C1D6FBCC407226_10() const { return ___98A44A6F8606AE6F23FE230286C1D6FBCC407226_10; } inline int64_t* get_address_of_U398A44A6F8606AE6F23FE230286C1D6FBCC407226_10() { return &___98A44A6F8606AE6F23FE230286C1D6FBCC407226_10; } inline void set_U398A44A6F8606AE6F23FE230286C1D6FBCC407226_10(int64_t value) { ___98A44A6F8606AE6F23FE230286C1D6FBCC407226_10 = value; } inline static int32_t get_offset_of_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11)); } inline __StaticArrayInitTypeSizeU3D32_t2711125390 get_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11() const { return ___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11; } inline __StaticArrayInitTypeSizeU3D32_t2711125390 * get_address_of_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11() { return &___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11; } inline void set_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11(__StaticArrayInitTypeSizeU3D32_t2711125390 value) { ___C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11 = value; } inline static int32_t get_offset_of_CCEEADA43268372341F81AE0C9208C6856441C04_12() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___CCEEADA43268372341F81AE0C9208C6856441C04_12)); } inline __StaticArrayInitTypeSizeU3D128_t531529102 get_CCEEADA43268372341F81AE0C9208C6856441C04_12() const { return ___CCEEADA43268372341F81AE0C9208C6856441C04_12; } inline __StaticArrayInitTypeSizeU3D128_t531529102 * get_address_of_CCEEADA43268372341F81AE0C9208C6856441C04_12() { return &___CCEEADA43268372341F81AE0C9208C6856441C04_12; } inline void set_CCEEADA43268372341F81AE0C9208C6856441C04_12(__StaticArrayInitTypeSizeU3D128_t531529102 value) { ___CCEEADA43268372341F81AE0C9208C6856441C04_12 = value; } inline static int32_t get_offset_of_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13)); } inline int64_t get_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13() const { return ___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13; } inline int64_t* get_address_of_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13() { return &___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13; } inline void set_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13(int64_t value) { ___E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13 = value; } inline static int32_t get_offset_of_EC5842B3154E1AF94500B57220EB9F684BCCC42A_14() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___EC5842B3154E1AF94500B57220EB9F684BCCC42A_14)); } inline __StaticArrayInitTypeSizeU3D32_t2711125390 get_EC5842B3154E1AF94500B57220EB9F684BCCC42A_14() const { return ___EC5842B3154E1AF94500B57220EB9F684BCCC42A_14; } inline __StaticArrayInitTypeSizeU3D32_t2711125390 * get_address_of_EC5842B3154E1AF94500B57220EB9F684BCCC42A_14() { return &___EC5842B3154E1AF94500B57220EB9F684BCCC42A_14; } inline void set_EC5842B3154E1AF94500B57220EB9F684BCCC42A_14(__StaticArrayInitTypeSizeU3D32_t2711125390 value) { ___EC5842B3154E1AF94500B57220EB9F684BCCC42A_14 = value; } inline static int32_t get_offset_of_EEAFE8C6E1AB017237567305EE925C976CDB6458_15() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields, ___EEAFE8C6E1AB017237567305EE925C976CDB6458_15)); } inline __StaticArrayInitTypeSizeU3D256_t1757367633 get_EEAFE8C6E1AB017237567305EE925C976CDB6458_15() const { return ___EEAFE8C6E1AB017237567305EE925C976CDB6458_15; } inline __StaticArrayInitTypeSizeU3D256_t1757367633 * get_address_of_EEAFE8C6E1AB017237567305EE925C976CDB6458_15() { return &___EEAFE8C6E1AB017237567305EE925C976CDB6458_15; } inline void set_EEAFE8C6E1AB017237567305EE925C976CDB6458_15(__StaticArrayInitTypeSizeU3D256_t1757367633 value) { ___EEAFE8C6E1AB017237567305EE925C976CDB6458_15 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255362_H #ifndef XPATHRESULTTYPE_T2828988488_H #define XPATHRESULTTYPE_T2828988488_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.XPath.XPathResultType struct XPathResultType_t2828988488 { public: // System.Int32 System.Xml.XPath.XPathResultType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(XPathResultType_t2828988488, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHRESULTTYPE_T2828988488_H #ifndef XPATHNODETYPE_T3031007223_H #define XPATHNODETYPE_T3031007223_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.XPath.XPathNodeType struct XPathNodeType_t3031007223 { public: // System.Int32 System.Xml.XPath.XPathNodeType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(XPathNodeType_t3031007223, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHNODETYPE_T3031007223_H #ifndef OP_T2046805169_H #define OP_T2046805169_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Operator/Op struct Op_t2046805169 { public: // System.Int32 MS.Internal.Xml.XPath.Operator/Op::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(Op_t2046805169, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OP_T2046805169_H #ifndef AXISTYPE_T3322599580_H #define AXISTYPE_T3322599580_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Axis/AxisType struct AxisType_t3322599580 { public: // System.Int32 MS.Internal.Xml.XPath.Axis/AxisType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AxisType_t3322599580, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // AXISTYPE_T3322599580_H #ifndef LEXKIND_T864578899_H #define LEXKIND_T864578899_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.XPathScanner/LexKind struct LexKind_t864578899 { public: // System.Int32 MS.Internal.Xml.XPath.XPathScanner/LexKind::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(LexKind_t864578899, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LEXKIND_T864578899_H #ifndef XPATHDOCUMENTNAVIGATOR_T2457178823_H #define XPATHDOCUMENTNAVIGATOR_T2457178823_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.Cache.XPathDocumentNavigator struct XPathDocumentNavigator_t2457178823 : public XPathNavigator_t787956054 { public: // MS.Internal.Xml.Cache.XPathNode[] MS.Internal.Xml.Cache.XPathDocumentNavigator::pageCurrent XPathNodeU5BU5D_t47339301* ___pageCurrent_4; // MS.Internal.Xml.Cache.XPathNode[] MS.Internal.Xml.Cache.XPathDocumentNavigator::pageParent XPathNodeU5BU5D_t47339301* ___pageParent_5; // System.Int32 MS.Internal.Xml.Cache.XPathDocumentNavigator::idxCurrent int32_t ___idxCurrent_6; // System.Int32 MS.Internal.Xml.Cache.XPathDocumentNavigator::idxParent int32_t ___idxParent_7; public: inline static int32_t get_offset_of_pageCurrent_4() { return static_cast<int32_t>(offsetof(XPathDocumentNavigator_t2457178823, ___pageCurrent_4)); } inline XPathNodeU5BU5D_t47339301* get_pageCurrent_4() const { return ___pageCurrent_4; } inline XPathNodeU5BU5D_t47339301** get_address_of_pageCurrent_4() { return &___pageCurrent_4; } inline void set_pageCurrent_4(XPathNodeU5BU5D_t47339301* value) { ___pageCurrent_4 = value; Il2CppCodeGenWriteBarrier((&___pageCurrent_4), value); } inline static int32_t get_offset_of_pageParent_5() { return static_cast<int32_t>(offsetof(XPathDocumentNavigator_t2457178823, ___pageParent_5)); } inline XPathNodeU5BU5D_t47339301* get_pageParent_5() const { return ___pageParent_5; } inline XPathNodeU5BU5D_t47339301** get_address_of_pageParent_5() { return &___pageParent_5; } inline void set_pageParent_5(XPathNodeU5BU5D_t47339301* value) { ___pageParent_5 = value; Il2CppCodeGenWriteBarrier((&___pageParent_5), value); } inline static int32_t get_offset_of_idxCurrent_6() { return static_cast<int32_t>(offsetof(XPathDocumentNavigator_t2457178823, ___idxCurrent_6)); } inline int32_t get_idxCurrent_6() const { return ___idxCurrent_6; } inline int32_t* get_address_of_idxCurrent_6() { return &___idxCurrent_6; } inline void set_idxCurrent_6(int32_t value) { ___idxCurrent_6 = value; } inline static int32_t get_offset_of_idxParent_7() { return static_cast<int32_t>(offsetof(XPathDocumentNavigator_t2457178823, ___idxParent_7)); } inline int32_t get_idxParent_7() const { return ___idxParent_7; } inline int32_t* get_address_of_idxParent_7() { return &___idxParent_7; } inline void set_idxParent_7(int32_t value) { ___idxParent_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHDOCUMENTNAVIGATOR_T2457178823_H #ifndef DTDPROCESSING_T1163997051_H #define DTDPROCESSING_T1163997051_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.DtdProcessing struct DtdProcessing_t1163997051 { public: // System.Int32 System.Xml.DtdProcessing::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(DtdProcessing_t1163997051, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DTDPROCESSING_T1163997051_H #ifndef CONFORMANCELEVEL_T3899847875_H #define CONFORMANCELEVEL_T3899847875_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.ConformanceLevel struct ConformanceLevel_t3899847875 { public: // System.Int32 System.Xml.ConformanceLevel::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ConformanceLevel_t3899847875, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONFORMANCELEVEL_T3899847875_H #ifndef ENTITYHANDLING_T1047276436_H #define ENTITYHANDLING_T1047276436_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Xml.EntityHandling struct EntityHandling_t1047276436 { public: // System.Int32 System.Xml.EntityHandling::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(EntityHandling_t1047276436, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ENTITYHANDLING_T1047276436_H #ifndef ASTTYPE_T3854428833_H #define ASTTYPE_T3854428833_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.AstNode/AstType struct AstType_t3854428833 { public: // System.Int32 MS.Internal.Xml.XPath.AstNode/AstType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(AstType_t3854428833, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASTTYPE_T3854428833_H #ifndef OPERATOR_T966760113_H #define OPERATOR_T966760113_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Operator struct Operator_t966760113 : public AstNode_t2514041814 { public: // MS.Internal.Xml.XPath.Operator/Op MS.Internal.Xml.XPath.Operator::opType int32_t ___opType_1; // MS.Internal.Xml.XPath.AstNode MS.Internal.Xml.XPath.Operator::opnd1 AstNode_t2514041814 * ___opnd1_2; // MS.Internal.Xml.XPath.AstNode MS.Internal.Xml.XPath.Operator::opnd2 AstNode_t2514041814 * ___opnd2_3; public: inline static int32_t get_offset_of_opType_1() { return static_cast<int32_t>(offsetof(Operator_t966760113, ___opType_1)); } inline int32_t get_opType_1() const { return ___opType_1; } inline int32_t* get_address_of_opType_1() { return &___opType_1; } inline void set_opType_1(int32_t value) { ___opType_1 = value; } inline static int32_t get_offset_of_opnd1_2() { return static_cast<int32_t>(offsetof(Operator_t966760113, ___opnd1_2)); } inline AstNode_t2514041814 * get_opnd1_2() const { return ___opnd1_2; } inline AstNode_t2514041814 ** get_address_of_opnd1_2() { return &___opnd1_2; } inline void set_opnd1_2(AstNode_t2514041814 * value) { ___opnd1_2 = value; Il2CppCodeGenWriteBarrier((&___opnd1_2), value); } inline static int32_t get_offset_of_opnd2_3() { return static_cast<int32_t>(offsetof(Operator_t966760113, ___opnd2_3)); } inline AstNode_t2514041814 * get_opnd2_3() const { return ___opnd2_3; } inline AstNode_t2514041814 ** get_address_of_opnd2_3() { return &___opnd2_3; } inline void set_opnd2_3(AstNode_t2514041814 * value) { ___opnd2_3 = value; Il2CppCodeGenWriteBarrier((&___opnd2_3), value); } }; struct Operator_t966760113_StaticFields { public: // MS.Internal.Xml.XPath.Operator/Op[] MS.Internal.Xml.XPath.Operator::invertOp OpU5BU5D_t2837398892* ___invertOp_0; public: inline static int32_t get_offset_of_invertOp_0() { return static_cast<int32_t>(offsetof(Operator_t966760113_StaticFields, ___invertOp_0)); } inline OpU5BU5D_t2837398892* get_invertOp_0() const { return ___invertOp_0; } inline OpU5BU5D_t2837398892** get_address_of_invertOp_0() { return &___invertOp_0; } inline void set_invertOp_0(OpU5BU5D_t2837398892* value) { ___invertOp_0 = value; Il2CppCodeGenWriteBarrier((&___invertOp_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OPERATOR_T966760113_H #ifndef OPERAND_T3355154092_H #define OPERAND_T3355154092_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Operand struct Operand_t3355154092 : public AstNode_t2514041814 { public: // System.Xml.XPath.XPathResultType MS.Internal.Xml.XPath.Operand::type int32_t ___type_0; // System.Object MS.Internal.Xml.XPath.Operand::val RuntimeObject * ___val_1; public: inline static int32_t get_offset_of_type_0() { return static_cast<int32_t>(offsetof(Operand_t3355154092, ___type_0)); } inline int32_t get_type_0() const { return ___type_0; } inline int32_t* get_address_of_type_0() { return &___type_0; } inline void set_type_0(int32_t value) { ___type_0 = value; } inline static int32_t get_offset_of_val_1() { return static_cast<int32_t>(offsetof(Operand_t3355154092, ___val_1)); } inline RuntimeObject * get_val_1() const { return ___val_1; } inline RuntimeObject ** get_address_of_val_1() { return &___val_1; } inline void set_val_1(RuntimeObject * value) { ___val_1 = value; Il2CppCodeGenWriteBarrier((&___val_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // OPERAND_T3355154092_H #ifndef PARAMINFO_T1233379796_H #define PARAMINFO_T1233379796_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.XPathParser/ParamInfo struct ParamInfo_t1233379796 : public RuntimeObject { public: // MS.Internal.Xml.XPath.Function/FunctionType MS.Internal.Xml.XPath.XPathParser/ParamInfo::ftype int32_t ___ftype_0; // System.Int32 MS.Internal.Xml.XPath.XPathParser/ParamInfo::minargs int32_t ___minargs_1; // System.Int32 MS.Internal.Xml.XPath.XPathParser/ParamInfo::maxargs int32_t ___maxargs_2; // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.XPathParser/ParamInfo::argTypes XPathResultTypeU5BU5D_t1515527577* ___argTypes_3; public: inline static int32_t get_offset_of_ftype_0() { return static_cast<int32_t>(offsetof(ParamInfo_t1233379796, ___ftype_0)); } inline int32_t get_ftype_0() const { return ___ftype_0; } inline int32_t* get_address_of_ftype_0() { return &___ftype_0; } inline void set_ftype_0(int32_t value) { ___ftype_0 = value; } inline static int32_t get_offset_of_minargs_1() { return static_cast<int32_t>(offsetof(ParamInfo_t1233379796, ___minargs_1)); } inline int32_t get_minargs_1() const { return ___minargs_1; } inline int32_t* get_address_of_minargs_1() { return &___minargs_1; } inline void set_minargs_1(int32_t value) { ___minargs_1 = value; } inline static int32_t get_offset_of_maxargs_2() { return static_cast<int32_t>(offsetof(ParamInfo_t1233379796, ___maxargs_2)); } inline int32_t get_maxargs_2() const { return ___maxargs_2; } inline int32_t* get_address_of_maxargs_2() { return &___maxargs_2; } inline void set_maxargs_2(int32_t value) { ___maxargs_2 = value; } inline static int32_t get_offset_of_argTypes_3() { return static_cast<int32_t>(offsetof(ParamInfo_t1233379796, ___argTypes_3)); } inline XPathResultTypeU5BU5D_t1515527577* get_argTypes_3() const { return ___argTypes_3; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_argTypes_3() { return &___argTypes_3; } inline void set_argTypes_3(XPathResultTypeU5BU5D_t1515527577* value) { ___argTypes_3 = value; Il2CppCodeGenWriteBarrier((&___argTypes_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PARAMINFO_T1233379796_H #ifndef XPATHSCANNER_T3283201025_H #define XPATHSCANNER_T3283201025_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.XPathScanner struct XPathScanner_t3283201025 : public RuntimeObject { public: // System.String MS.Internal.Xml.XPath.XPathScanner::xpathExpr String_t* ___xpathExpr_0; // System.Int32 MS.Internal.Xml.XPath.XPathScanner::xpathExprIndex int32_t ___xpathExprIndex_1; // MS.Internal.Xml.XPath.XPathScanner/LexKind MS.Internal.Xml.XPath.XPathScanner::kind int32_t ___kind_2; // System.Char MS.Internal.Xml.XPath.XPathScanner::currentChar Il2CppChar ___currentChar_3; // System.String MS.Internal.Xml.XPath.XPathScanner::name String_t* ___name_4; // System.String MS.Internal.Xml.XPath.XPathScanner::prefix String_t* ___prefix_5; // System.String MS.Internal.Xml.XPath.XPathScanner::stringValue String_t* ___stringValue_6; // System.Double MS.Internal.Xml.XPath.XPathScanner::numberValue double ___numberValue_7; // System.Boolean MS.Internal.Xml.XPath.XPathScanner::canBeFunction bool ___canBeFunction_8; // System.Xml.XmlCharType MS.Internal.Xml.XPath.XPathScanner::xmlCharType XmlCharType_t2277243275 ___xmlCharType_9; public: inline static int32_t get_offset_of_xpathExpr_0() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___xpathExpr_0)); } inline String_t* get_xpathExpr_0() const { return ___xpathExpr_0; } inline String_t** get_address_of_xpathExpr_0() { return &___xpathExpr_0; } inline void set_xpathExpr_0(String_t* value) { ___xpathExpr_0 = value; Il2CppCodeGenWriteBarrier((&___xpathExpr_0), value); } inline static int32_t get_offset_of_xpathExprIndex_1() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___xpathExprIndex_1)); } inline int32_t get_xpathExprIndex_1() const { return ___xpathExprIndex_1; } inline int32_t* get_address_of_xpathExprIndex_1() { return &___xpathExprIndex_1; } inline void set_xpathExprIndex_1(int32_t value) { ___xpathExprIndex_1 = value; } inline static int32_t get_offset_of_kind_2() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___kind_2)); } inline int32_t get_kind_2() const { return ___kind_2; } inline int32_t* get_address_of_kind_2() { return &___kind_2; } inline void set_kind_2(int32_t value) { ___kind_2 = value; } inline static int32_t get_offset_of_currentChar_3() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___currentChar_3)); } inline Il2CppChar get_currentChar_3() const { return ___currentChar_3; } inline Il2CppChar* get_address_of_currentChar_3() { return &___currentChar_3; } inline void set_currentChar_3(Il2CppChar value) { ___currentChar_3 = value; } inline static int32_t get_offset_of_name_4() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___name_4)); } inline String_t* get_name_4() const { return ___name_4; } inline String_t** get_address_of_name_4() { return &___name_4; } inline void set_name_4(String_t* value) { ___name_4 = value; Il2CppCodeGenWriteBarrier((&___name_4), value); } inline static int32_t get_offset_of_prefix_5() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___prefix_5)); } inline String_t* get_prefix_5() const { return ___prefix_5; } inline String_t** get_address_of_prefix_5() { return &___prefix_5; } inline void set_prefix_5(String_t* value) { ___prefix_5 = value; Il2CppCodeGenWriteBarrier((&___prefix_5), value); } inline static int32_t get_offset_of_stringValue_6() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___stringValue_6)); } inline String_t* get_stringValue_6() const { return ___stringValue_6; } inline String_t** get_address_of_stringValue_6() { return &___stringValue_6; } inline void set_stringValue_6(String_t* value) { ___stringValue_6 = value; Il2CppCodeGenWriteBarrier((&___stringValue_6), value); } inline static int32_t get_offset_of_numberValue_7() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___numberValue_7)); } inline double get_numberValue_7() const { return ___numberValue_7; } inline double* get_address_of_numberValue_7() { return &___numberValue_7; } inline void set_numberValue_7(double value) { ___numberValue_7 = value; } inline static int32_t get_offset_of_canBeFunction_8() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___canBeFunction_8)); } inline bool get_canBeFunction_8() const { return ___canBeFunction_8; } inline bool* get_address_of_canBeFunction_8() { return &___canBeFunction_8; } inline void set_canBeFunction_8(bool value) { ___canBeFunction_8 = value; } inline static int32_t get_offset_of_xmlCharType_9() { return static_cast<int32_t>(offsetof(XPathScanner_t3283201025, ___xmlCharType_9)); } inline XmlCharType_t2277243275 get_xmlCharType_9() const { return ___xmlCharType_9; } inline XmlCharType_t2277243275 * get_address_of_xmlCharType_9() { return &___xmlCharType_9; } inline void set_xmlCharType_9(XmlCharType_t2277243275 value) { ___xmlCharType_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // XPATHSCANNER_T3283201025_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_t1188392813 { public: // System.Delegate[] System.MulticastDelegate::delegates DelegateU5BU5D_t1703627840* ___delegates_11; public: inline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___delegates_11)); } inline DelegateU5BU5D_t1703627840* get_delegates_11() const { return ___delegates_11; } inline DelegateU5BU5D_t1703627840** get_address_of_delegates_11() { return &___delegates_11; } inline void set_delegates_11(DelegateU5BU5D_t1703627840* value) { ___delegates_11 = value; Il2CppCodeGenWriteBarrier((&___delegates_11), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_pinvoke : public Delegate_t1188392813_marshaled_pinvoke { DelegateU5BU5D_t1703627840* ___delegates_11; }; // Native definition for COM marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_com : public Delegate_t1188392813_marshaled_com { DelegateU5BU5D_t1703627840* ___delegates_11; }; #endif // MULTICASTDELEGATE_T_H #ifndef AXIS_T4207104559_H #define AXIS_T4207104559_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Axis struct Axis_t4207104559 : public AstNode_t2514041814 { public: // MS.Internal.Xml.XPath.Axis/AxisType MS.Internal.Xml.XPath.Axis::axisType int32_t ___axisType_0; // MS.Internal.Xml.XPath.AstNode MS.Internal.Xml.XPath.Axis::input AstNode_t2514041814 * ___input_1; // System.String MS.Internal.Xml.XPath.Axis::prefix String_t* ___prefix_2; // System.String MS.Internal.Xml.XPath.Axis::name String_t* ___name_3; // System.Xml.XPath.XPathNodeType MS.Internal.Xml.XPath.Axis::nodeType int32_t ___nodeType_4; // System.Boolean MS.Internal.Xml.XPath.Axis::abbrAxis bool ___abbrAxis_5; // System.String MS.Internal.Xml.XPath.Axis::urn String_t* ___urn_6; public: inline static int32_t get_offset_of_axisType_0() { return static_cast<int32_t>(offsetof(Axis_t4207104559, ___axisType_0)); } inline int32_t get_axisType_0() const { return ___axisType_0; } inline int32_t* get_address_of_axisType_0() { return &___axisType_0; } inline void set_axisType_0(int32_t value) { ___axisType_0 = value; } inline static int32_t get_offset_of_input_1() { return static_cast<int32_t>(offsetof(Axis_t4207104559, ___input_1)); } inline AstNode_t2514041814 * get_input_1() const { return ___input_1; } inline AstNode_t2514041814 ** get_address_of_input_1() { return &___input_1; } inline void set_input_1(AstNode_t2514041814 * value) { ___input_1 = value; Il2CppCodeGenWriteBarrier((&___input_1), value); } inline static int32_t get_offset_of_prefix_2() { return static_cast<int32_t>(offsetof(Axis_t4207104559, ___prefix_2)); } inline String_t* get_prefix_2() const { return ___prefix_2; } inline String_t** get_address_of_prefix_2() { return &___prefix_2; } inline void set_prefix_2(String_t* value) { ___prefix_2 = value; Il2CppCodeGenWriteBarrier((&___prefix_2), value); } inline static int32_t get_offset_of_name_3() { return static_cast<int32_t>(offsetof(Axis_t4207104559, ___name_3)); } inline String_t* get_name_3() const { return ___name_3; } inline String_t** get_address_of_name_3() { return &___name_3; } inline void set_name_3(String_t* value) { ___name_3 = value; Il2CppCodeGenWriteBarrier((&___name_3), value); } inline static int32_t get_offset_of_nodeType_4() { return static_cast<int32_t>(offsetof(Axis_t4207104559, ___nodeType_4)); } inline int32_t get_nodeType_4() const { return ___nodeType_4; } inline int32_t* get_address_of_nodeType_4() { return &___nodeType_4; } inline void set_nodeType_4(int32_t value) { ___nodeType_4 = value; } inline static int32_t get_offset_of_abbrAxis_5() { return static_cast<int32_t>(offsetof(Axis_t4207104559, ___abbrAxis_5)); } inline bool get_abbrAxis_5() const { return ___abbrAxis_5; } inline bool* get_address_of_abbrAxis_5() { return &___abbrAxis_5; } inline void set_abbrAxis_5(bool value) { ___abbrAxis_5 = value; } inline static int32_t get_offset_of_urn_6() { return static_cast<int32_t>(offsetof(Axis_t4207104559, ___urn_6)); } inline String_t* get_urn_6() const { return ___urn_6; } inline String_t** get_address_of_urn_6() { return &___urn_6; } inline void set_urn_6(String_t* value) { ___urn_6 = value; Il2CppCodeGenWriteBarrier((&___urn_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // AXIS_T4207104559_H #ifndef FUNCTION_T1283990952_H #define FUNCTION_T1283990952_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MS.Internal.Xml.XPath.Function struct Function_t1283990952 : public AstNode_t2514041814 { public: // MS.Internal.Xml.XPath.Function/FunctionType MS.Internal.Xml.XPath.Function::functionType int32_t ___functionType_0; // System.Collections.ArrayList MS.Internal.Xml.XPath.Function::argumentList ArrayList_t2718874744 * ___argumentList_1; // System.String MS.Internal.Xml.XPath.Function::name String_t* ___name_2; // System.String MS.Internal.Xml.XPath.Function::prefix String_t* ___prefix_3; public: inline static int32_t get_offset_of_functionType_0() { return static_cast<int32_t>(offsetof(Function_t1283990952, ___functionType_0)); } inline int32_t get_functionType_0() const { return ___functionType_0; } inline int32_t* get_address_of_functionType_0() { return &___functionType_0; } inline void set_functionType_0(int32_t value) { ___functionType_0 = value; } inline static int32_t get_offset_of_argumentList_1() { return static_cast<int32_t>(offsetof(Function_t1283990952, ___argumentList_1)); } inline ArrayList_t2718874744 * get_argumentList_1() const { return ___argumentList_1; } inline ArrayList_t2718874744 ** get_address_of_argumentList_1() { return &___argumentList_1; } inline void set_argumentList_1(ArrayList_t2718874744 * value) { ___argumentList_1 = value; Il2CppCodeGenWriteBarrier((&___argumentList_1), value); } inline static int32_t get_offset_of_name_2() { return static_cast<int32_t>(offsetof(Function_t1283990952, ___name_2)); } inline String_t* get_name_2() const { return ___name_2; } inline String_t** get_address_of_name_2() { return &___name_2; } inline void set_name_2(String_t* value) { ___name_2 = value; Il2CppCodeGenWriteBarrier((&___name_2), value); } inline static int32_t get_offset_of_prefix_3() { return static_cast<int32_t>(offsetof(Function_t1283990952, ___prefix_3)); } inline String_t* get_prefix_3() const { return ___prefix_3; } inline String_t** get_address_of_prefix_3() { return &___prefix_3; } inline void set_prefix_3(String_t* value) { ___prefix_3 = value; Il2CppCodeGenWriteBarrier((&___prefix_3), value); } }; struct Function_t1283990952_StaticFields { public: // System.Xml.XPath.XPathResultType[] MS.Internal.Xml.XPath.Function::ReturnTypes XPathResultTypeU5BU5D_t1515527577* ___ReturnTypes_4; public: inline static int32_t get_offset_of_ReturnTypes_4() { return static_cast<int32_t>(offsetof(Function_t1283990952_StaticFields, ___ReturnTypes_4)); } inline XPathResultTypeU5BU5D_t1515527577* get_ReturnTypes_4() const { return ___ReturnTypes_4; } inline XPathResultTypeU5BU5D_t1515527577** get_address_of_ReturnTypes_4() { return &___ReturnTypes_4; } inline void set_ReturnTypes_4(XPathResultTypeU5BU5D_t1515527577* value) { ___ReturnTypes_4 = value; Il2CppCodeGenWriteBarrier((&___ReturnTypes_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FUNCTION_T1283990952_H #ifndef DEFLATESTREAM_T4175168077_H #define DEFLATESTREAM_T4175168077_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.Compression.DeflateStream struct DeflateStream_t4175168077 : public Stream_t1273022909 { public: // System.IO.Stream System.IO.Compression.DeflateStream::base_stream Stream_t1273022909 * ___base_stream_4; // System.IO.Compression.CompressionMode System.IO.Compression.DeflateStream::mode int32_t ___mode_5; // System.Boolean System.IO.Compression.DeflateStream::leaveOpen bool ___leaveOpen_6; // System.Boolean System.IO.Compression.DeflateStream::disposed bool ___disposed_7; // System.IO.Compression.DeflateStreamNative System.IO.Compression.DeflateStream::native DeflateStreamNative_t1405046456 * ___native_8; public: inline static int32_t get_offset_of_base_stream_4() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___base_stream_4)); } inline Stream_t1273022909 * get_base_stream_4() const { return ___base_stream_4; } inline Stream_t1273022909 ** get_address_of_base_stream_4() { return &___base_stream_4; } inline void set_base_stream_4(Stream_t1273022909 * value) { ___base_stream_4 = value; Il2CppCodeGenWriteBarrier((&___base_stream_4), value); } inline static int32_t get_offset_of_mode_5() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___mode_5)); } inline int32_t get_mode_5() const { return ___mode_5; } inline int32_t* get_address_of_mode_5() { return &___mode_5; } inline void set_mode_5(int32_t value) { ___mode_5 = value; } inline static int32_t get_offset_of_leaveOpen_6() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___leaveOpen_6)); } inline bool get_leaveOpen_6() const { return ___leaveOpen_6; } inline bool* get_address_of_leaveOpen_6() { return &___leaveOpen_6; } inline void set_leaveOpen_6(bool value) { ___leaveOpen_6 = value; } inline static int32_t get_offset_of_disposed_7() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___disposed_7)); } inline bool get_disposed_7() const { return ___disposed_7; } inline bool* get_address_of_disposed_7() { return &___disposed_7; } inline void set_disposed_7(bool value) { ___disposed_7 = value; } inline static int32_t get_offset_of_native_8() { return static_cast<int32_t>(offsetof(DeflateStream_t4175168077, ___native_8)); } inline DeflateStreamNative_t1405046456 * get_native_8() const { return ___native_8; } inline DeflateStreamNative_t1405046456 ** get_address_of_native_8() { return &___native_8; } inline void set_native_8(DeflateStreamNative_t1405046456 * value) { ___native_8 = value; Il2CppCodeGenWriteBarrier((&___native_8), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DEFLATESTREAM_T4175168077_H #ifndef READMETHOD_T893206259_H #define READMETHOD_T893206259_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.Compression.DeflateStream/ReadMethod struct ReadMethod_t893206259 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // READMETHOD_T893206259_H #ifndef WRITEMETHOD_T2538911768_H #define WRITEMETHOD_T2538911768_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.Compression.DeflateStream/WriteMethod struct WriteMethod_t2538911768 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WRITEMETHOD_T2538911768_H #ifndef UNMANAGEDREADORWRITE_T1975956110_H #define UNMANAGEDREADORWRITE_T1975956110_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IO.Compression.DeflateStreamNative/UnmanagedReadOrWrite struct UnmanagedReadOrWrite_t1975956110 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNMANAGEDREADORWRITE_T1975956110_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2200 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2201 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2202 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2203 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2204 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2205 = { sizeof (DesignerSerializerAttribute_t1570548024), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2205[3] = { DesignerSerializerAttribute_t1570548024::get_offset_of_serializerTypeName_0(), DesignerSerializerAttribute_t1570548024::get_offset_of_serializerBaseTypeName_1(), DesignerSerializerAttribute_t1570548024::get_offset_of_typeId_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2206 = { sizeof (InstanceDescriptor_t657473484), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2206[3] = { InstanceDescriptor_t657473484::get_offset_of_member_0(), InstanceDescriptor_t657473484::get_offset_of_arguments_1(), InstanceDescriptor_t657473484::get_offset_of_isComplete_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2207 = { sizeof (RootDesignerSerializerAttribute_t3074689342), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2207[4] = { RootDesignerSerializerAttribute_t3074689342::get_offset_of_reloadable_0(), RootDesignerSerializerAttribute_t3074689342::get_offset_of_serializerTypeName_1(), RootDesignerSerializerAttribute_t3074689342::get_offset_of_serializerBaseTypeName_2(), RootDesignerSerializerAttribute_t3074689342::get_offset_of_typeId_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2208 = { sizeof (HybridDictionary_t4070033136), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2208[3] = { HybridDictionary_t4070033136::get_offset_of_list_0(), HybridDictionary_t4070033136::get_offset_of_hashtable_1(), HybridDictionary_t4070033136::get_offset_of_caseInsensitive_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2209 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2210 = { sizeof (ListDictionary_t1624492310), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2210[5] = { ListDictionary_t1624492310::get_offset_of_head_0(), ListDictionary_t1624492310::get_offset_of_version_1(), ListDictionary_t1624492310::get_offset_of_count_2(), ListDictionary_t1624492310::get_offset_of_comparer_3(), ListDictionary_t1624492310::get_offset_of__syncRoot_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2211 = { sizeof (NodeEnumerator_t3248827953), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2211[4] = { NodeEnumerator_t3248827953::get_offset_of_list_0(), NodeEnumerator_t3248827953::get_offset_of_current_1(), NodeEnumerator_t3248827953::get_offset_of_version_2(), NodeEnumerator_t3248827953::get_offset_of_start_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2212 = { sizeof (NodeKeyValueCollection_t1279341543), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2212[2] = { NodeKeyValueCollection_t1279341543::get_offset_of_list_0(), NodeKeyValueCollection_t1279341543::get_offset_of_isKeys_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2213 = { sizeof (NodeKeyValueEnumerator_t642906510), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2213[5] = { NodeKeyValueEnumerator_t642906510::get_offset_of_list_0(), NodeKeyValueEnumerator_t642906510::get_offset_of_current_1(), NodeKeyValueEnumerator_t642906510::get_offset_of_version_2(), NodeKeyValueEnumerator_t642906510::get_offset_of_isKeys_3(), NodeKeyValueEnumerator_t642906510::get_offset_of_start_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2214 = { sizeof (DictionaryNode_t417719465), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2214[3] = { DictionaryNode_t417719465::get_offset_of_key_0(), DictionaryNode_t417719465::get_offset_of_value_1(), DictionaryNode_t417719465::get_offset_of_next_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2215 = { sizeof (NameObjectCollectionBase_t2091847364), -1, sizeof(NameObjectCollectionBase_t2091847364_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2215[10] = { NameObjectCollectionBase_t2091847364::get_offset_of__readOnly_0(), NameObjectCollectionBase_t2091847364::get_offset_of__entriesArray_1(), NameObjectCollectionBase_t2091847364::get_offset_of__keyComparer_2(), NameObjectCollectionBase_t2091847364::get_offset_of__entriesTable_3(), NameObjectCollectionBase_t2091847364::get_offset_of__nullKeyEntry_4(), NameObjectCollectionBase_t2091847364::get_offset_of__keys_5(), NameObjectCollectionBase_t2091847364::get_offset_of__serializationInfo_6(), NameObjectCollectionBase_t2091847364::get_offset_of__version_7(), NameObjectCollectionBase_t2091847364::get_offset_of__syncRoot_8(), NameObjectCollectionBase_t2091847364_StaticFields::get_offset_of_defaultComparer_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2216 = { sizeof (NameObjectEntry_t4224248211), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2216[2] = { NameObjectEntry_t4224248211::get_offset_of_Key_0(), NameObjectEntry_t4224248211::get_offset_of_Value_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2217 = { sizeof (NameObjectKeysEnumerator_t3824388371), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2217[3] = { NameObjectKeysEnumerator_t3824388371::get_offset_of__pos_0(), NameObjectKeysEnumerator_t3824388371::get_offset_of__coll_1(), NameObjectKeysEnumerator_t3824388371::get_offset_of__version_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2218 = { sizeof (KeysCollection_t1318642398), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2218[1] = { KeysCollection_t1318642398::get_offset_of__coll_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2219 = { sizeof (CompatibleComparer_t4154576053), -1, sizeof(CompatibleComparer_t4154576053_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2219[4] = { CompatibleComparer_t4154576053::get_offset_of__comparer_0(), CompatibleComparer_t4154576053_StaticFields::get_offset_of_defaultComparer_1(), CompatibleComparer_t4154576053::get_offset_of__hcp_2(), CompatibleComparer_t4154576053_StaticFields::get_offset_of_defaultHashProvider_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2220 = { sizeof (NameValueCollection_t407452768), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2220[2] = { NameValueCollection_t407452768::get_offset_of__all_10(), NameValueCollection_t407452768::get_offset_of__allKeys_11(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2221 = { sizeof (OrderedDictionary_t2617496293), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2221[7] = { OrderedDictionary_t2617496293::get_offset_of__objectsArray_0(), OrderedDictionary_t2617496293::get_offset_of__objectsTable_1(), OrderedDictionary_t2617496293::get_offset_of__initialCapacity_2(), OrderedDictionary_t2617496293::get_offset_of__comparer_3(), OrderedDictionary_t2617496293::get_offset_of__readOnly_4(), OrderedDictionary_t2617496293::get_offset_of__syncRoot_5(), OrderedDictionary_t2617496293::get_offset_of__siInfo_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2222 = { sizeof (OrderedDictionaryEnumerator_t1215437281), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2222[2] = { OrderedDictionaryEnumerator_t1215437281::get_offset_of__objectReturnType_0(), OrderedDictionaryEnumerator_t1215437281::get_offset_of_arrayEnumerator_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2223 = { sizeof (OrderedDictionaryKeyValueCollection_t1788601968), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2223[2] = { OrderedDictionaryKeyValueCollection_t1788601968::get_offset_of__objects_0(), OrderedDictionaryKeyValueCollection_t1788601968::get_offset_of_isKeys_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2224 = { sizeof (StringCollection_t167406615), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2224[1] = { StringCollection_t167406615::get_offset_of_data_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2225 = { sizeof (StringDictionary_t120437468), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2225[1] = { StringDictionary_t120437468::get_offset_of_contents_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2226 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2227 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2228 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2229 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2230 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable2230[5] = { 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2231 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable2231[6] = { 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2232 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable2232[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2233 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable2233[7] = { 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2234 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable2234[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2235 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable2235[5] = { 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2236 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable2236[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2237 = { sizeof (CompressionMode_t3714291783)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2237[3] = { CompressionMode_t3714291783::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2238 = { sizeof (GZipStream_t3417139389), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2238[1] = { GZipStream_t3417139389::get_offset_of__deflateStream_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2239 = { sizeof (DeflateStream_t4175168077), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2239[5] = { DeflateStream_t4175168077::get_offset_of_base_stream_4(), DeflateStream_t4175168077::get_offset_of_mode_5(), DeflateStream_t4175168077::get_offset_of_leaveOpen_6(), DeflateStream_t4175168077::get_offset_of_disposed_7(), DeflateStream_t4175168077::get_offset_of_native_8(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2240 = { sizeof (ReadMethod_t893206259), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2241 = { sizeof (WriteMethod_t2538911768), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2242 = { sizeof (DeflateStreamNative_t1405046456), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2242[6] = { DeflateStreamNative_t1405046456::get_offset_of_feeder_0(), DeflateStreamNative_t1405046456::get_offset_of_base_stream_1(), DeflateStreamNative_t1405046456::get_offset_of_z_stream_2(), DeflateStreamNative_t1405046456::get_offset_of_data_3(), DeflateStreamNative_t1405046456::get_offset_of_disposed_4(), DeflateStreamNative_t1405046456::get_offset_of_io_buffer_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2243 = { sizeof (UnmanagedReadOrWrite_t1975956110), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2244 = { sizeof (U3CPrivateImplementationDetailsU3E_t3057255362), -1, sizeof(U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2244[16] = { U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U30283A6AF88802AB45989B29549915BEA0F6CD515_0(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U303F4297FCC30D0FD5E420E5D26E7FA711167C7EF_1(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U31A39764B112685485A5BA7B2880D878B858C1A7A_2(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U31A84029C80CB5518379F199F53FF08A7B764F8FD_3(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U33BE77BF818331C2D8400FFFFF9FADD3F16AD89AC_4(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U359F5BD34B6C013DEACC784F69C67E95150033A84_5(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U35BC3486B05BA8CF4689C7BDB198B3F477BB4E20C_6(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U36D49C9D487D7AD3491ECE08732D68A593CC2038D_7(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U36F3AD3DC3AF8047587C4C9D696EB68A01FEF796E_8(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U38E0EF3D67A3EB1863224EE3CACB424BC2F8CFBA3_9(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_U398A44A6F8606AE6F23FE230286C1D6FBCC407226_10(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_C02C28AFEBE998F767E4AF43E3BE8F5E9FA11536_11(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_CCEEADA43268372341F81AE0C9208C6856441C04_12(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_E5BC1BAFADE1862DD6E0B9FB632BFAA6C3873A78_13(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_EC5842B3154E1AF94500B57220EB9F684BCCC42A_14(), U3CPrivateImplementationDetailsU3E_t3057255362_StaticFields::get_offset_of_EEAFE8C6E1AB017237567305EE925C976CDB6458_15(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2245 = { sizeof (__StaticArrayInitTypeSizeU3D3_t3217885683)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D3_t3217885683 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2246 = { sizeof (__StaticArrayInitTypeSizeU3D6_t3217689075)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D6_t3217689075 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2247 = { sizeof (__StaticArrayInitTypeSizeU3D9_t3218278899)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D9_t3218278899 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2248 = { sizeof (__StaticArrayInitTypeSizeU3D12_t2710994318)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D12_t2710994318 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2249 = { sizeof (__StaticArrayInitTypeSizeU3D14_t3517563372)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D14_t3517563372 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2250 = { sizeof (__StaticArrayInitTypeSizeU3D32_t2711125390)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D32_t2711125390 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2251 = { sizeof (__StaticArrayInitTypeSizeU3D44_t3517366764)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D44_t3517366764 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2252 = { sizeof (__StaticArrayInitTypeSizeU3D128_t531529102)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D128_t531529102 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2253 = { sizeof (__StaticArrayInitTypeSizeU3D256_t1757367633)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D256_t1757367633 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2254 = { sizeof (U3CModuleU3E_t692745527), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2255 = { sizeof (SR_t167583545), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2256 = { sizeof (AstNode_t2514041814), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2257 = { sizeof (AstType_t3854428833)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2257[10] = { AstType_t3854428833::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2258 = { sizeof (Axis_t4207104559), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2258[7] = { Axis_t4207104559::get_offset_of_axisType_0(), Axis_t4207104559::get_offset_of_input_1(), Axis_t4207104559::get_offset_of_prefix_2(), Axis_t4207104559::get_offset_of_name_3(), Axis_t4207104559::get_offset_of_nodeType_4(), Axis_t4207104559::get_offset_of_abbrAxis_5(), Axis_t4207104559::get_offset_of_urn_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2259 = { sizeof (AxisType_t3322599580)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2259[15] = { AxisType_t3322599580::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2260 = { sizeof (Filter_t1571657935), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2260[2] = { Filter_t1571657935::get_offset_of_input_0(), Filter_t1571657935::get_offset_of_condition_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2261 = { sizeof (Function_t1283990952), -1, sizeof(Function_t1283990952_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2261[5] = { Function_t1283990952::get_offset_of_functionType_0(), Function_t1283990952::get_offset_of_argumentList_1(), Function_t1283990952::get_offset_of_name_2(), Function_t1283990952::get_offset_of_prefix_3(), Function_t1283990952_StaticFields::get_offset_of_ReturnTypes_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2262 = { sizeof (FunctionType_t3319434782)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2262[29] = { FunctionType_t3319434782::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2263 = { sizeof (Group_t100818710), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2263[1] = { Group_t100818710::get_offset_of_groupNode_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2264 = { sizeof (Operand_t3355154092), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2264[2] = { Operand_t3355154092::get_offset_of_type_0(), Operand_t3355154092::get_offset_of_val_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2265 = { sizeof (Operator_t966760113), -1, sizeof(Operator_t966760113_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2265[4] = { Operator_t966760113_StaticFields::get_offset_of_invertOp_0(), Operator_t966760113::get_offset_of_opType_1(), Operator_t966760113::get_offset_of_opnd1_2(), Operator_t966760113::get_offset_of_opnd2_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2266 = { sizeof (Op_t2046805169)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2266[16] = { Op_t2046805169::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2267 = { sizeof (Root_t720671714), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2268 = { sizeof (Variable_t262588068), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2268[2] = { Variable_t262588068::get_offset_of_localname_0(), Variable_t262588068::get_offset_of_prefix_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2269 = { sizeof (XPathParser_t618394529), -1, sizeof(XPathParser_t618394529_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2269[13] = { XPathParser_t618394529::get_offset_of_scanner_0(), XPathParser_t618394529::get_offset_of_parseDepth_1(), XPathParser_t618394529_StaticFields::get_offset_of_temparray1_2(), XPathParser_t618394529_StaticFields::get_offset_of_temparray2_3(), XPathParser_t618394529_StaticFields::get_offset_of_temparray3_4(), XPathParser_t618394529_StaticFields::get_offset_of_temparray4_5(), XPathParser_t618394529_StaticFields::get_offset_of_temparray5_6(), XPathParser_t618394529_StaticFields::get_offset_of_temparray6_7(), XPathParser_t618394529_StaticFields::get_offset_of_temparray7_8(), XPathParser_t618394529_StaticFields::get_offset_of_temparray8_9(), XPathParser_t618394529_StaticFields::get_offset_of_temparray9_10(), XPathParser_t618394529_StaticFields::get_offset_of_functionTable_11(), XPathParser_t618394529_StaticFields::get_offset_of_AxesTable_12(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2270 = { sizeof (ParamInfo_t1233379796), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2270[4] = { ParamInfo_t1233379796::get_offset_of_ftype_0(), ParamInfo_t1233379796::get_offset_of_minargs_1(), ParamInfo_t1233379796::get_offset_of_maxargs_2(), ParamInfo_t1233379796::get_offset_of_argTypes_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2271 = { sizeof (XPathScanner_t3283201025), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2271[10] = { XPathScanner_t3283201025::get_offset_of_xpathExpr_0(), XPathScanner_t3283201025::get_offset_of_xpathExprIndex_1(), XPathScanner_t3283201025::get_offset_of_kind_2(), XPathScanner_t3283201025::get_offset_of_currentChar_3(), XPathScanner_t3283201025::get_offset_of_name_4(), XPathScanner_t3283201025::get_offset_of_prefix_5(), XPathScanner_t3283201025::get_offset_of_stringValue_6(), XPathScanner_t3283201025::get_offset_of_numberValue_7(), XPathScanner_t3283201025::get_offset_of_canBeFunction_8(), XPathScanner_t3283201025::get_offset_of_xmlCharType_9(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2272 = { sizeof (LexKind_t864578899)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2272[32] = { LexKind_t864578899::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2273 = { sizeof (XPathDocumentNavigator_t2457178823), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2273[4] = { XPathDocumentNavigator_t2457178823::get_offset_of_pageCurrent_4(), XPathDocumentNavigator_t2457178823::get_offset_of_pageParent_5(), XPathDocumentNavigator_t2457178823::get_offset_of_idxCurrent_6(), XPathDocumentNavigator_t2457178823::get_offset_of_idxParent_7(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2274 = { sizeof (XPathNode_t2208072876)+ sizeof (RuntimeObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2274[7] = { XPathNode_t2208072876::get_offset_of_info_0() + static_cast<int32_t>(sizeof(RuntimeObject)), XPathNode_t2208072876::get_offset_of_idxSibling_1() + static_cast<int32_t>(sizeof(RuntimeObject)), XPathNode_t2208072876::get_offset_of_idxParent_2() + static_cast<int32_t>(sizeof(RuntimeObject)), XPathNode_t2208072876::get_offset_of_idxSimilar_3() + static_cast<int32_t>(sizeof(RuntimeObject)), XPathNode_t2208072876::get_offset_of_posOffset_4() + static_cast<int32_t>(sizeof(RuntimeObject)), XPathNode_t2208072876::get_offset_of_props_5() + static_cast<int32_t>(sizeof(RuntimeObject)), XPathNode_t2208072876::get_offset_of_value_6() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2275 = { sizeof (XPathNodeRef_t3498189018)+ sizeof (RuntimeObject), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2275[2] = { XPathNodeRef_t3498189018::get_offset_of_page_0() + static_cast<int32_t>(sizeof(RuntimeObject)), XPathNodeRef_t3498189018::get_offset_of_idx_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2276 = { sizeof (XPathNodeHelper_t2230825274), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2277 = { sizeof (XPathNodePageInfo_t2343388010), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2277[3] = { XPathNodePageInfo_t2343388010::get_offset_of_pageNum_0(), XPathNodePageInfo_t2343388010::get_offset_of_nodeCount_1(), XPathNodePageInfo_t2343388010::get_offset_of_pageNext_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2278 = { sizeof (XPathNodeInfoAtom_t1760358141), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2278[13] = { XPathNodeInfoAtom_t1760358141::get_offset_of_localName_0(), XPathNodeInfoAtom_t1760358141::get_offset_of_namespaceUri_1(), XPathNodeInfoAtom_t1760358141::get_offset_of_prefix_2(), XPathNodeInfoAtom_t1760358141::get_offset_of_baseUri_3(), XPathNodeInfoAtom_t1760358141::get_offset_of_pageParent_4(), XPathNodeInfoAtom_t1760358141::get_offset_of_pageSibling_5(), XPathNodeInfoAtom_t1760358141::get_offset_of_pageSimilar_6(), XPathNodeInfoAtom_t1760358141::get_offset_of_doc_7(), XPathNodeInfoAtom_t1760358141::get_offset_of_lineNumBase_8(), XPathNodeInfoAtom_t1760358141::get_offset_of_linePosBase_9(), XPathNodeInfoAtom_t1760358141::get_offset_of_hashCode_10(), XPathNodeInfoAtom_t1760358141::get_offset_of_localNameHash_11(), XPathNodeInfoAtom_t1760358141::get_offset_of_pageInfo_12(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2279 = { sizeof (Res_t3627928856), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2280 = { sizeof (Base64Encoder_t3938083961), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2280[3] = { Base64Encoder_t3938083961::get_offset_of_leftOverBytes_0(), Base64Encoder_t3938083961::get_offset_of_leftOverBytesCount_1(), Base64Encoder_t3938083961::get_offset_of_charsLine_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2281 = { sizeof (XmlTextWriterBase64Encoder_t4259465041), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2281[1] = { XmlTextWriterBase64Encoder_t4259465041::get_offset_of_xmlTextEncoder_3(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2282 = { sizeof (BinHexDecoder_t1474272384), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable2282[5] = { BinHexDecoder_t1474272384::get_offset_of_buffer_0(), BinHexDecoder_t1474272384::get_offset_of_curIndex_1(), BinHexDecoder_t1474272384::get_offset_of_endIndex_2(), BinHexDecoder_t1474272384::get_offset_of_hasHalfByteCached_3(), BinHexDecoder_t1474272384::get_offset_of_cachedHalfByte_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2283 = { sizeof (BinHexEncoder_t1687308627), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2284 = { sizeof (Bits_t3566938933), -1, sizeof(Bits_t3566938933_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2284[5] = { Bits_t3566938933_StaticFields::get_offset_of_MASK_0101010101010101_0(), Bits_t3566938933_StaticFields::get_offset_of_MASK_0011001100110011_1(), Bits_t3566938933_StaticFields::get_offset_of_MASK_0000111100001111_2(), Bits_t3566938933_StaticFields::get_offset_of_MASK_0000000011111111_3(), Bits_t3566938933_StaticFields::get_offset_of_MASK_1111111111111111_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2285 = { sizeof (BinaryCompatibility_t2660327299), -1, sizeof(BinaryCompatibility_t2660327299_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable2285[1] = { BinaryCompatibility_t2660327299_StaticFields::get_offset_of__targetsAtLeast_Desktop_V4_5_2_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2286 = { sizeof (ConformanceLevel_t3899847875)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2286[4] = { ConformanceLevel_t3899847875::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2287 = { sizeof (DtdProcessing_t1163997051)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2287[4] = { DtdProcessing_t1163997051::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2288 = { sizeof (EntityHandling_t1047276436)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable2288[3] = { EntityHandling_t1047276436::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2289 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2290 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2291 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2292 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2293 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2294 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2295 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2296 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2297 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2298 = { sizeof (IncrementalReadDecoder_t3011954239), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize2299 = { sizeof (IncrementalReadDummyDecoder_t2572367147), -1, 0, 0 }; #ifdef __clang__ #pragma clang diagnostic pop #endif
40.171484
236
0.825589
[ "object" ]
e06df24a01cac4b2555d31b8daf810fc3784adde
4,263
hpp
C++
libs/vectormath/common.hpp
bematteo/Cauldron
3e4a021fc0d3e0372347126771a5155016810a11
[ "MIT" ]
590
2019-07-23T13:39:32.000Z
2022-03-31T02:09:29.000Z
libs/vectormath/common.hpp
bematteo/Cauldron
3e4a021fc0d3e0372347126771a5155016810a11
[ "MIT" ]
23
2019-07-24T02:22:52.000Z
2022-02-08T08:48:27.000Z
libs/vectormath/common.hpp
bematteo/Cauldron
3e4a021fc0d3e0372347126771a5155016810a11
[ "MIT" ]
67
2019-07-23T16:26:39.000Z
2022-03-16T08:46:53.000Z
// ================================================================================================ // -*- C++ -*- // File: vectormath/common.hpp // Author: Guilherme R. Lampert // Created on: 30/12/16 // Brief: Extra helper functions added to the Vectormath library. // ================================================================================================ #ifndef VECTORMATH_COMMON_HPP #define VECTORMATH_COMMON_HPP namespace Vectormath { inline float * toFloatPtr(Point2 & p) { return reinterpret_cast<float *>(&p); } // 2 floats - default alignment inline float * toFloatPtr(Point3 & p) { return reinterpret_cast<float *>(&p); } // 4 floats - 16 bytes aligned inline float * toFloatPtr(Vector2 & v) { return reinterpret_cast<float *>(&v); } // 2 floats - default alignment inline float * toFloatPtr(Vector3 & v) { return reinterpret_cast<float *>(&v); } // 4 floats - 16 bytes aligned inline float * toFloatPtr(Vector4 & v) { return reinterpret_cast<float *>(&v); } // 4 floats - 16 bytes aligned inline float * toFloatPtr(Quat & q) { return reinterpret_cast<float *>(&q); } // 4 floats - 16 bytes aligned inline float * toFloatPtr(Matrix3 & m) { return reinterpret_cast<float *>(&m); } // 12 floats - 16 bytes aligned inline float * toFloatPtr(Matrix4 & m) { return reinterpret_cast<float *>(&m); } // 16 floats - 16 bytes aligned inline float * toFloatPtr(Transform3 & t) { return reinterpret_cast<float *>(&t); } // 16 floats - 16 bytes aligned inline const float * toFloatPtr(const Point2 & p) { return reinterpret_cast<const float *>(&p); } inline const float * toFloatPtr(const Point3 & p) { return reinterpret_cast<const float *>(&p); } inline const float * toFloatPtr(const Vector2 & v) { return reinterpret_cast<const float *>(&v); } inline const float * toFloatPtr(const Vector3 & v) { return reinterpret_cast<const float *>(&v); } inline const float * toFloatPtr(const Vector4 & v) { return reinterpret_cast<const float *>(&v); } inline const float * toFloatPtr(const Quat & q) { return reinterpret_cast<const float *>(&q); } inline const float * toFloatPtr(const Matrix3 & m) { return reinterpret_cast<const float *>(&m); } inline const float * toFloatPtr(const Matrix4 & m) { return reinterpret_cast<const float *>(&m); } inline const float * toFloatPtr(const Transform3 & t) { return reinterpret_cast<const float *>(&t); } // Shorthand to discard the last element of a Vector4 and get a Point3. inline Point3 toPoint3(const Vector4 & v4) { return Point3(v4[0], v4[1], v4[2]); } // Convert from world (global) coordinates to local model coordinates. // Input matrix must be the inverse of the model matrix, e.g.: 'inverse(modelMatrix)'. inline Point3 worldPointToModel(const Matrix4 & invModelToWorldMatrix, const Point3 & point) { return toPoint3(invModelToWorldMatrix * point); } // Makes a plane projection matrix that can be used for simple object shadow effects. // The W component of the light position vector should be 1 for a point light and 0 for directional. inline Matrix4 makeShadowMatrix(const Vector4 & plane, const Vector4 & light) { Matrix4 shadowMat; const auto dot = (plane[0] * light[0]) + (plane[1] * light[1]) + (plane[2] * light[2]) + (plane[3] * light[3]); shadowMat[0][0] = dot - (light[0] * plane[0]); shadowMat[1][0] = - (light[0] * plane[1]); shadowMat[2][0] = - (light[0] * plane[2]); shadowMat[3][0] = - (light[0] * plane[3]); shadowMat[0][1] = - (light[1] * plane[0]); shadowMat[1][1] = dot - (light[1] * plane[1]); shadowMat[2][1] = - (light[1] * plane[2]); shadowMat[3][1] = - (light[1] * plane[3]); shadowMat[0][2] = - (light[2] * plane[0]); shadowMat[1][2] = - (light[2] * plane[1]); shadowMat[2][2] = dot - (light[2] * plane[2]); shadowMat[3][2] = - (light[2] * plane[3]); shadowMat[0][3] = - (light[3] * plane[0]); shadowMat[1][3] = - (light[3] * plane[1]); shadowMat[2][3] = - (light[3] * plane[2]); shadowMat[3][3] = dot - (light[3] * plane[3]); return shadowMat; } } // namespace Vectormath #endif // VECTORMATH_COMMON_HPP
50.152941
116
0.612714
[ "object", "vector", "model" ]
e07293fd6abd8a897c9b0b58789f7deb500dd817
6,739
cpp
C++
src/ConfigParser.cpp
ISISComputingGroup/EPICS-forward_epics_to_kafka
c45079d403f5cdfa4e218c9932bcc77b714fd680
[ "BSD-2-Clause" ]
null
null
null
src/ConfigParser.cpp
ISISComputingGroup/EPICS-forward_epics_to_kafka
c45079d403f5cdfa4e218c9932bcc77b714fd680
[ "BSD-2-Clause" ]
2
2018-05-04T22:34:53.000Z
2019-04-15T10:59:02.000Z
src/ConfigParser.cpp
ISISComputingGroup/EPICS-forward_epics_to_kafka
c45079d403f5cdfa4e218c9932bcc77b714fd680
[ "BSD-2-Clause" ]
null
null
null
#include "ConfigParser.h" #include "Forwarder.h" #include "helper.h" #include "json.h" #include "logger.h" #include <iostream> namespace Forwarder { void ConfigParser::setJsonFromString(std::string RawJson) { Json = nlohmann::json::parse(RawJson); if (Json.is_null()) { throw std::runtime_error("Cannot parse configuration file as JSON"); } } ConfigSettings ConfigParser::extractConfiguration() { ConfigSettings Settings; extractBrokerConfig(Settings); extractBrokers(Settings); extractConversionThreads(Settings); extractConversionWorkerQueueSize(Settings); extractMainPollInterval(Settings); extractStatusUri(Settings); extractKafkaBrokerSettings(Settings); extractStreamSettings(Settings); extractGlobalConverters(Settings); return Settings; } void ConfigParser::extractBrokerConfig(ConfigSettings &Settings) { if (auto x = find<std::string>("broker-config", Json)) { Settings.BrokerConfig = x.inner(); } } void ConfigParser::extractBrokers(ConfigSettings &Settings) { if (auto x = find<std::string>("broker", Json)) { setBrokers(x.inner(), Settings); } else { // If not specified then use default setBrokers("localhost:9092", Settings); } } void ConfigParser::extractConversionThreads(ConfigSettings &Settings) { if (auto x = find<size_t>("conversion-threads", Json)) { Settings.ConversionThreads = x.inner(); } } void ConfigParser::extractConversionWorkerQueueSize(ConfigSettings &Settings) { if (auto x = find<size_t>("conversion-worker-queue-size", Json)) { Settings.ConversionWorkerQueueSize = x.inner(); } } void ConfigParser::extractMainPollInterval(ConfigSettings &Settings) { if (auto x = find<int32_t>("main-poll-interval", Json)) { Settings.MainPollInterval = x.inner(); } } void ConfigParser::extractGlobalConverters(ConfigSettings &Settings) { using nlohmann::json; if (auto ConvertersMaybe = find<json>("converters", Json)) { auto const &Converters = ConvertersMaybe.inner(); if (Converters.is_object()) { for (auto It = Converters.begin(); It != Converters.end(); ++It) { KafkaBrokerSettings BrokerSettings{}; for (auto SettingIt = It.value().begin(); SettingIt != It.value().end(); ++SettingIt) { if (SettingIt.value().is_number()) { BrokerSettings.ConfigurationIntegers[SettingIt.key()] = SettingIt.value().get<int64_t>(); } if (SettingIt.value().is_string()) { BrokerSettings.ConfigurationStrings[SettingIt.key()] = SettingIt.value().get<std::string>(); } } Settings.GlobalConverters[It.key()] = BrokerSettings; } } } } void ConfigParser::extractStatusUri(ConfigSettings &Settings) { if (auto x = find<std::string>("status-uri", Json)) { auto URIString = x.inner(); URI URI; URI.port = 9092; URI.parse(URIString); Settings.StatusReportURI = URI; } } void ConfigParser::setBrokers(std::string const &Brokers, ConfigSettings &Settings) { Settings.Brokers.clear(); auto a = split(Brokers, ","); for (auto &x : a) { URI u1; u1.require_host_slashes = false; u1.parse(x); Settings.Brokers.push_back(u1); } } void ConfigParser::extractKafkaBrokerSettings(ConfigSettings &Settings) { using nlohmann::json; if (auto KafkaMaybe = find<json>("kafka", Json)) { auto Kafka = KafkaMaybe.inner(); if (auto BrokerMaybe = find<json>("broker", Kafka)) { auto Broker = BrokerMaybe.inner(); for (auto Property = Broker.begin(); Property != Broker.end(); ++Property) { auto const Key = Property.key(); if (Key.find("___") == 0) { // Skip this property continue; } if (Property.value().is_string()) { auto Value = Property.value().get<std::string>(); LOG(6, "kafka broker config {}: {}", Key, Value); Settings.BrokerSettings.ConfigurationStrings[Key] = Value; } else if (Property.value().is_number()) { auto Value = Property.value().get<int64_t>(); LOG(6, "kafka broker config {}: {}", Key, Value); Settings.BrokerSettings.ConfigurationIntegers[Key] = Value; } else { LOG(3, "can not understand option: {}", Key); } } } } } void ConfigParser::extractStreamSettings(ConfigSettings &Settings) { using nlohmann::json; if (auto StreamsMaybe = find<json>("streams", Json)) { auto Streams = StreamsMaybe.inner(); if (Streams.is_array()) { for (auto const &StreamJson : Streams) { StreamSettings Stream; // Find the basic information extractMappingInfo(StreamJson, Stream.Name, Stream.EpicsProtocol); // Find the converters, if present if (auto x = find<nlohmann::json>("converter", StreamJson)) { if (x.inner().is_object()) { Stream.Converters.push_back(extractConverterSettings(x.inner())); } else if (x.inner().is_array()) { for (auto const &ConverterSettings : x.inner()) { Stream.Converters.push_back( extractConverterSettings(ConverterSettings)); } } } Settings.StreamsInfo.push_back(Stream); } } } } void ConfigParser::extractMappingInfo(nlohmann::json const &Mapping, std::string &Channel, std::string &Protocol) { if (!Mapping.is_object()) { throw MappingAddException("Given Mapping is not a JSON object"); } if (auto ChannelMaybe = find<std::string>("channel", Mapping)) { Channel = ChannelMaybe.inner(); } else { throw MappingAddException("Cannot find channel"); } if (auto ChannelProviderTypeMaybe = find<std::string>("channel_provider_type", Mapping)) { Protocol = ChannelProviderTypeMaybe.inner(); } else { // Default is pva Protocol = "pva"; } } ConverterSettings ConfigParser::extractConverterSettings(nlohmann::json const &Mapping) { ConverterSettings Settings; if (auto SchemaMaybe = find<std::string>("schema", Mapping)) { Settings.Schema = SchemaMaybe.inner(); } else { throw MappingAddException("Cannot find schema"); } if (auto TopicMaybe = find<std::string>("topic", Mapping)) { Settings.Topic = TopicMaybe.inner(); } else { throw MappingAddException("Cannot find topic"); } if (auto x = find<std::string>("name", Mapping)) { Settings.Name = x.inner(); } else { // Assign automatically generated name Settings.Name = fmt::format("converter_{}", ConverterIndex++); } return Settings; } } // namespace Forwarder
30.355856
80
0.639561
[ "object" ]
e076af35d0c9b411cf2e224b2a58d81fbd00a079
9,835
cpp
C++
src/dray/triangle_mesh.cpp
LLNL/devil_ray
6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
14
2019-12-17T17:40:32.000Z
2021-12-13T20:32:32.000Z
src/dray/triangle_mesh.cpp
LLNL/devil_ray
6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
72
2019-12-21T16:55:38.000Z
2022-03-22T20:40:13.000Z
src/dray/triangle_mesh.cpp
LLNL/devil_ray
6ab59dd740a5fb1e04967e982c5c6d4c7507f4cb
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
3
2020-02-21T18:06:57.000Z
2021-12-03T18:39:48.000Z
// Copyright 2019 Lawrence Livermore National Security, LLC and other // Devil Ray Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #include <dray/triangle_mesh.hpp> #include <dray/array_utils.hpp> #include <dray/error_check.hpp> #include <dray/intersection_context.hpp> #include <dray/linear_bvh_builder.hpp> #include <dray/policies.hpp> #include <dray/triangle_intersection.hpp> #include <assert.h> namespace dray { namespace detail { Array<AABB<>> get_tri_aabbs (Array<float32> &coords, Array<int32> indices) { Array<AABB<>> aabbs; assert (indices.size () % 3 == 0); const int32 num_tris = indices.size () / 3; aabbs.resize (num_tris); const int32 *indices_ptr = indices.get_device_ptr_const (); const float32 *coords_ptr = coords.get_device_ptr_const (); AABB<> *aabb_ptr = aabbs.get_device_ptr (); std::cout << "number of triangles " << num_tris << "\n"; std::cout << "coords " << coords.size () << "\n"; RAJA::forall<for_policy> (RAJA::RangeSegment (0, num_tris), [=] DRAY_LAMBDA (int32 tri) { AABB<> aabb; const int32 i_offset = tri * 3; for (int32 i = 0; i < 3; ++i) { const int32 vertex_id = indices_ptr[i_offset + i]; const int32 v_offset = vertex_id * 3; Vec3f vertex; for (int32 v = 0; v < 3; ++v) { vertex[v] = coords_ptr[v_offset + v]; } aabb.include (vertex); } aabb_ptr[tri] = aabb; }); DRAY_ERROR_CHECK(); return aabbs; } } // namespace detail TriangleMesh::TriangleMesh (Array<float32> &coords, Array<int32> &indices) : m_coords (coords), m_indices (indices) { Array<AABB<>> aabbs = detail::get_tri_aabbs (m_coords, indices); LinearBVHBuilder builder; m_bvh = builder.construct (aabbs); } TriangleMesh::TriangleMesh () { } TriangleMesh::~TriangleMesh () { } Array<float32> &TriangleMesh::get_coords () { return m_coords; } Array<int32> &TriangleMesh::get_indices () { return m_indices; } AABB<> TriangleMesh::get_bounds () { return m_bvh.m_bounds; } template <typename T> DRAY_EXEC_ONLY bool intersect_AABB (const Vec<float32, 4> *bvh, const int32 &currentNode, const Vec<T, 3> &orig_dir, const Vec<T, 3> &inv_dir, const T &closest_dist, bool &hit_left, bool &hit_right, const T &min_dist) // Find hit after this distance { Vec<float32, 4> first4 = const_get_vec4f (&bvh[currentNode + 0]); Vec<float32, 4> second4 = const_get_vec4f (&bvh[currentNode + 1]); Vec<float32, 4> third4 = const_get_vec4f (&bvh[currentNode + 2]); T xmin0 = first4[0] * inv_dir[0] - orig_dir[0]; T ymin0 = first4[1] * inv_dir[1] - orig_dir[1]; T zmin0 = first4[2] * inv_dir[2] - orig_dir[2]; T xmax0 = first4[3] * inv_dir[0] - orig_dir[0]; T ymax0 = second4[0] * inv_dir[1] - orig_dir[1]; T zmax0 = second4[1] * inv_dir[2] - orig_dir[2]; T min0 = fmaxf (fmaxf (fmaxf (fminf (ymin0, ymax0), fminf (xmin0, xmax0)), fminf (zmin0, zmax0)), min_dist); T max0 = fminf (fminf (fminf (fmaxf (ymin0, ymax0), fmaxf (xmin0, xmax0)), fmaxf (zmin0, zmax0)), closest_dist); hit_left = (max0 >= min0); T xmin1 = second4[2] * inv_dir[0] - orig_dir[0]; T ymin1 = second4[3] * inv_dir[1] - orig_dir[1]; T zmin1 = third4[0] * inv_dir[2] - orig_dir[2]; T xmax1 = third4[1] * inv_dir[0] - orig_dir[0]; T ymax1 = third4[2] * inv_dir[1] - orig_dir[1]; T zmax1 = third4[3] * inv_dir[2] - orig_dir[2]; T min1 = fmaxf (fmaxf (fmaxf (fminf (ymin1, ymax1), fminf (xmin1, xmax1)), fminf (zmin1, zmax1)), min_dist); T max1 = fminf (fminf (fminf (fmaxf (ymin1, ymax1), fmaxf (xmin1, xmax1)), fmaxf (zmin1, zmax1)), closest_dist); hit_right = (max1 >= min1); return (min0 > min1); } Array<RayHit> TriangleMesh::intersect (const Array<Ray> &rays) { const float32 *coords_ptr = m_coords.get_device_ptr_const (); const int32 *indices_ptr = m_indices.get_device_ptr_const (); const int32 *leaf_ptr = m_bvh.m_leaf_nodes.get_device_ptr_const (); const Vec<float32, 4> *inner_ptr = m_bvh.m_inner_nodes.get_device_ptr_const (); const Ray *ray_ptr = rays.get_device_ptr_const (); const int32 size = rays.size (); Array<RayHit> hits; hits.resize (size); RayHit *hit_ptr = hits.get_device_ptr (); RAJA::forall<for_policy> (RAJA::RangeSegment (0, size), [=] DRAY_LAMBDA (int32 i) { Ray ray = ray_ptr[i]; RayHit hit; Float closest_dist = ray.m_far; Float min_dist = ray.m_near; int32 hit_idx = -1; const Vec<Float, 3> dir = ray.m_dir; Vec<Float, 3> inv_dir; inv_dir[0] = rcp_safe (dir[0]); inv_dir[1] = rcp_safe (dir[1]); inv_dir[2] = rcp_safe (dir[2]); int32 current_node; int32 todo[64]; int32 stackptr = 0; current_node = 0; constexpr int32 barrier = -2000000000; todo[stackptr] = barrier; Vec<Float, 3> orig_dir; orig_dir[0] = ray.m_orig[0] * inv_dir[0]; orig_dir[1] = ray.m_orig[1] * inv_dir[1]; orig_dir[2] = ray.m_orig[2] * inv_dir[2]; while (current_node != barrier) { if (current_node > -1) { bool hit_left, hit_right; bool right_closer = intersect_AABB (inner_ptr, current_node, orig_dir, inv_dir, closest_dist, hit_left, hit_right, min_dist); if (!hit_left && !hit_right) { current_node = todo[stackptr]; stackptr--; } else { Vec<float32, 4> children = const_get_vec4f (&inner_ptr[current_node + 3]); int32 l_child; constexpr int32 isize = sizeof (int32); memcpy (&l_child, &children[0], isize); int32 r_child; memcpy (&r_child, &children[1], isize); current_node = (hit_left) ? l_child : r_child; if (hit_left && hit_right) { if (right_closer) { current_node = r_child; stackptr++; todo[stackptr] = l_child; } else { stackptr++; todo[stackptr] = r_child; } } } } // if inner node if (current_node < 0 && current_node != barrier) // check register usage { current_node = -current_node - 1; // swap the neg address Float minU, minV; // Moller leaf_intersector; TriLeafIntersector<Moller> leaf_intersector; leaf_intersector.intersect_leaf (current_node, ray.m_orig, dir, hit_idx, minU, minV, closest_dist, min_dist, indices_ptr, coords_ptr, leaf_ptr); current_node = todo[stackptr]; stackptr--; } // if leaf node } // while if (hit_idx != -1) { hit.m_dist = closest_dist; } hit.m_hit_idx = hit_idx; hit_ptr[i] = hit; }); DRAY_ERROR_CHECK(); return hits; } Array<IntersectionContext> TriangleMesh::get_intersection_context (const Array<Ray> &rays, const Array<RayHit> &hits) { const int32 size = rays.size (); Array<IntersectionContext> intersection_ctx; intersection_ctx.resize (size); // Device pointers for output IntersectionContext *ctx_ptr = intersection_ctx.get_device_ptr (); // Read-only device pointers for input fields. const Ray *ray_ptr = rays.get_device_ptr_const (); const RayHit *hit_ptr = hits.get_device_ptr_const (); // Read-only device pointers for mesh object member fields. const float32 *m_coords_ptr = m_coords.get_device_ptr_const (); const int32 *m_indices_ptr = m_indices.get_device_ptr_const (); RAJA::View<const float32, RAJA::Layout<2>> coords (m_coords_ptr, m_coords.size () / 3, 3); RAJA::View<const int32, RAJA::Layout<2>> indices (m_indices_ptr, m_indices.size () / 3, 3); // Iterate over all rays. RAJA::forall<for_policy> (RAJA::RangeSegment (0, size), [=] DRAY_LAMBDA (int32 ray_idx) { const Ray &ray = ray_ptr[ray_idx]; const RayHit &hit = hit_ptr[ray_idx]; IntersectionContext ctx; ctx.m_pixel_id = ray.m_pixel_id; ctx.m_ray_dir = ray.m_dir; if (hit.m_hit_idx == -1) { // There is no intersection. ctx.m_is_valid = 0; } else { // There is an intersection. ctx.m_is_valid = 1; // Calculate the hit point by projecting the ray. ctx.m_hit_pt = ray.m_orig + ray.m_dir * hit.m_dist; // Get the triangle vertex coordinates (to later calculate surface normal). Vec<Float, 3> v[3]; // Using raw int32 and saving intermediate indices... /// const int32 i_offset = in_hit_idx_ptr[ray_idx] * 3; /// for(int32 i = 0; i < 3; ++i) /// { /// const int32 vertex_id = m_indices_ptr[i_offset + i]; /// const int32 v_offset = vertex_id * 3; /// for(int32 vi = 0; vi < 3; ++vi) /// { /// v[i][vi] = (T) m_coords_ptr[v_offset + vi]; /// } /// } // Using RAJA "Views"... for (int32 i = 0; i < 3; ++i) for (int32 vi = 0; vi < 3; ++vi) v[i][vi] = (Float)coords (indices (hit.m_hit_idx, i), vi); // Now calculate the surface normal (facing the source of the ray). ctx.m_normal = cross (v[1] - v[0], v[2] - v[0]); ctx.m_normal.normalize (); if (dot (ctx.m_normal, ray.m_dir) > 0.0f) { ctx.m_normal = -ctx.m_normal; } } ctx_ptr[ray_idx] = ctx; }); DRAY_ERROR_CHECK(); return intersection_ctx; } } // namespace dray
29.011799
91
0.592272
[ "mesh", "object" ]
2ff131e58e52efbb9eb21b3ae2235adf2f352871
665
cpp
C++
Trees/postorder.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Trees/postorder.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Trees/postorder.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ vector<int> postorderTraversal(TreeNode* A) { vector<int> ans; stack<TreeNode*> s1; stack<int> s2; s1.push(A); while(!s1.empty()) { TreeNode *top = s1.top(); s1.pop(); s2.push(top->val); if(top->left != nullptr) { s1.push(top->left); } if(top->right != nullptr) { s1.push(top->right); } } while(!s2.empty()) { ans.push_back(s2.top()); s2.pop(); } return ans; } int main(void) { return 0; }
15.113636
59
0.571429
[ "vector" ]
2ff2412a3847c6032681ac4f3ec2d8bcda6162ab
1,122
cpp
C++
infoarena/bellman-ford/main.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
1
2022-01-27T17:13:08.000Z
2022-01-27T17:13:08.000Z
infoarena/bellman-ford/main.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
null
null
null
infoarena/bellman-ford/main.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
null
null
null
#include <vector> #include <tuple> #include <iostream> #include <queue> #include <fstream> std::ifstream fin("bellmanford.in"); std::ofstream fout("bellmanford.out"); static const int mxn = 5e4, INF = 2e9 + 7; std::vector<std::pair<int,int> > adj[mxn + 5]; int n, m; int distance[mxn + 5], pasi[mxn + 5]; std::queue<std::pair<int, int> > q; int main(){ fin >> n >> m; for (int t = 1; t <= m; ++t){ int a, b, d; fin >> a >> b >> d; adj[a].push_back({b, d}); } for (int i = 1; i <= n; ++i){ distance[i] = INF; } distance[1] = 0; pasi[1] = 0; q.push({1, 0}); while (!q.empty()){ int i = q.front().first, j = q.front().second; q.pop(); if (j != distance[i]){ continue; } if (pasi[i] > n){ fout << "Ciclu negativ!\n"; return 0; } for (auto e : adj[i]){ if (distance[e.first] > j + e.second){ distance[e.first] = j + e.second; pasi[e.first] = pasi[i] + 1; q.push({e.first, distance[e.first]}); } } } for (int i = 2; i <= n; ++i){ fout << distance[i] << ' '; } fout << '\n'; return 0; }
19.344828
50
0.493761
[ "vector" ]
2ff9e68aa5fee2293260bf70a7d59c048feffe1e
1,885
hpp
C++
include/codegen/include/GlobalNamespace/OVRProfile.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/OVRProfile.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/OVRProfile.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Object #include "UnityEngine/Object.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: OVRProfile class OVRProfile : public UnityEngine::Object { public: // Nested type: GlobalNamespace::OVRProfile::State struct State; // public System.String get_id() // Offset: 0xF4C134 ::Il2CppString* get_id(); // public System.String get_userName() // Offset: 0xF4C17C ::Il2CppString* get_userName(); // public System.String get_locale() // Offset: 0xF4C1C4 ::Il2CppString* get_locale(); // public System.Single get_ipd() // Offset: 0xF4C20C float get_ipd(); // public System.Single get_eyeHeight() // Offset: 0xF4C340 float get_eyeHeight(); // public System.Single get_eyeDepth() // Offset: 0xF4C3A0 float get_eyeDepth(); // public System.Single get_neckHeight() // Offset: 0xF4C400 float get_neckHeight(); // public OVRProfile/State get_state() // Offset: 0xF4C420 GlobalNamespace::OVRProfile::State get_state(); // public System.Void .ctor() // Offset: 0xF4C428 // Implemented from: UnityEngine.Object // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static OVRProfile* New_ctor(); }; // OVRProfile } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::OVRProfile*, "", "OVRProfile"); #pragma pack(pop)
32.5
76
0.672679
[ "object" ]
6405133d33a63eb1a67b9b34c19879c22e542d80
18,574
cpp
C++
Platform/Win32/Build/Utils/OpenNIFilter/XnVideoSource.cpp
Wessi/OpenNI
613b0a43e66e1e97488624dec285341bc047d6d4
[ "Apache-2.0" ]
null
null
null
Platform/Win32/Build/Utils/OpenNIFilter/XnVideoSource.cpp
Wessi/OpenNI
613b0a43e66e1e97488624dec285341bc047d6d4
[ "Apache-2.0" ]
null
null
null
Platform/Win32/Build/Utils/OpenNIFilter/XnVideoSource.cpp
Wessi/OpenNI
613b0a43e66e1e97488624dec285341bc047d6d4
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * * OpenNI 1.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <streams.h> #include <olectl.h> #include <initguid.h> #include "XnVideoSource.h" #include "Guids.h" #include "XnVideoStream.h" #include <XnLog.h> //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- XnVideoSource::XnVideoSource(LPUNKNOWN lpunk, HRESULT *phr) : CSource(g_videoName, lpunk, CLSID_OpenNIVideo), m_pVideoProcAmp(NULL), m_pCameraControl(NULL), m_Dump(xnDumpFileOpen(XN_MASK_FILTER, "FilterFlow.log")) { ASSERT(phr != NULL); xnLogVerbose(XN_MASK_FILTER, "Creating video source filter"); CAutoLock cAutoLock(&m_cStateLock); // initialize OpenNI XnStatus nRetVal = m_context.Init(); if (nRetVal != XN_STATUS_OK) { xnLogWarning(XN_MASK_FILTER, "Can't init context"); *phr = E_UNEXPECTED; } // try to create an image generator nRetVal = m_image.Create(m_context); if (nRetVal != XN_STATUS_OK) { xnLogWarning(XN_MASK_FILTER, "Can't create image generator"); *phr = VFW_E_NO_CAPTURE_HARDWARE; return; } // create output pins. Every pin registers itself with the source object XnVideoStream* pStream = new XnVideoStream(phr, this, m_image, L"VideoOut"); if (pStream == NULL) { *phr = E_OUTOFMEMORY; } *phr = NOERROR; } XnVideoSource::~XnVideoSource() { xnLogVerbose(XN_MASK_FILTER, "Destroying filter..."); if (m_pVideoProcAmp != NULL) { delete m_pVideoProcAmp; } if (m_pCameraControl != NULL) { delete m_pCameraControl; } for (int i = 0; i < GetPinCount(); ++i) { delete GetPin(i); } m_image.Release(); m_context.Release(); } // // CreateInstance // // The only allowed way to create XnVideoSource! // CUnknown * WINAPI XnVideoSource::CreateInstance(LPUNKNOWN lpunk, HRESULT *phr) { ASSERT(phr); CUnknown *punk = new XnVideoSource(lpunk, phr); if(punk == NULL) { *phr = E_OUTOFMEMORY; } else if (*phr != NOERROR) { delete punk; punk = NULL; } return punk; } STDMETHODIMP XnVideoSource::GetPages(CAUUID *pPages) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pPages); pPages->cElems = 3; pPages->pElems = reinterpret_cast<GUID*>(CoTaskMemAlloc(sizeof(GUID)*pPages->cElems)); if (pPages->pElems == NULL) { XN_METHOD_RETURN(E_OUTOFMEMORY); } pPages->pElems[0] = CLSID_VideoProcAmpPropertyPage; pPages->pElems[1] = CLSID_CameraControlPropertyPage; pPages->pElems[2] = CLSID_AdditionalOpenNIControlsPropertyPage; XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::NonDelegatingQueryInterface(REFIID riid, void **ppv) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(ppv); HRESULT hr = S_OK; if (riid == IID_ISpecifyPropertyPages) { xnDumpFileWriteString(m_Dump, "\tFilter query interface to ISpecifyPropertyPages\n"); hr = GetInterface(static_cast<ISpecifyPropertyPages*>(this), ppv); } else if (riid == IID_IAMVideoControl) { xnDumpFileWriteString(m_Dump, "\tFilter query interface to IAMVideoControl\n"); hr = GetInterface(static_cast<IAMVideoControl*>(this), ppv); } else if (riid == IID_IAMVideoProcAmp) { xnDumpFileWriteString(m_Dump, "\tFilter query interface to IAMVideoProcAmp\n"); if (m_pVideoProcAmp == NULL) { m_pVideoProcAmp = new VideoProcAmp(this); if (m_pVideoProcAmp == NULL) { XN_METHOD_RETURN(E_OUTOFMEMORY); } } hr = GetInterface(static_cast<IAMVideoProcAmp*>(m_pVideoProcAmp), ppv); } else if (riid == IID_IAMCameraControl) { xnDumpFileWriteString(m_Dump, "\tFilter query interface to IAMCameraControl\n"); if (m_pCameraControl == NULL) { m_pCameraControl = new CameraControl(this); if (m_pCameraControl == NULL) { XN_METHOD_RETURN(E_OUTOFMEMORY); } } hr = GetInterface(static_cast<IAMCameraControl*>(m_pCameraControl), ppv); } else if (riid == IID_IAdditionalOpenNIControls) { xnDumpFileWriteString(m_Dump, "\tFilter query interface to IAdditionalControls\n"); hr = GetInterface(static_cast<IAdditionalControls*>(this), ppv); } else { OLECHAR strGuid[40]; StringFromGUID2(riid, strGuid, 40); xnDumpFileWriteString(m_Dump, "\tFilter query interface to %S\n", strGuid); hr = CSource::NonDelegatingQueryInterface(riid, ppv); } XN_METHOD_RETURN(hr); } HRESULT STDMETHODCALLTYPE XnVideoSource::GetCaps(IPin *pPin, long *pCapsFlags) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pPin); XN_METHOD_CHECK_POINTER(pCapsFlags); // we have only 1 pin, make sure this is it if (pPin != static_cast<IPin*>(GetPin(0))) { XN_METHOD_RETURN(E_FAIL); } *pCapsFlags = VideoControlFlag_FlipHorizontal | VideoControlFlag_FlipVertical; XN_METHOD_RETURN(S_OK); } HRESULT STDMETHODCALLTYPE XnVideoSource::SetMode( IPin *pPin, long Mode ) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pPin); HRESULT hr = S_OK; // we have only 1 pin, make sure this is it XnVideoStream* pVideoStream = dynamic_cast<XnVideoStream*>(GetPin(0)); if (pPin != static_cast<IPin*>(pVideoStream)) { XN_METHOD_RETURN(E_FAIL); } xnLogVerbose(XN_MASK_FILTER, "Setting flip mode to %d", Mode); hr = pVideoStream->SetMirror(Mode & VideoControlFlag_FlipHorizontal); if (FAILED(hr)) XN_METHOD_RETURN(hr); hr = pVideoStream->SetVerticalFlip(Mode & VideoControlFlag_FlipVertical); if (FAILED(hr)) XN_METHOD_RETURN(hr); XN_METHOD_RETURN(S_OK); } HRESULT STDMETHODCALLTYPE XnVideoSource::GetMode( IPin *pPin, __out long *Mode ) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pPin); XN_METHOD_CHECK_POINTER(Mode); // we have only 1 pin, make sure this is it XnVideoStream* pVideoStream = dynamic_cast<XnVideoStream*>(GetPin(0)); if (pPin != static_cast<IPin*>(pVideoStream)) { XN_METHOD_RETURN(E_FAIL); } *Mode = 0; if (pVideoStream->GetMirror()) *Mode |= VideoControlFlag_FlipHorizontal; if (pVideoStream->GetVerticalFlip()) *Mode |= VideoControlFlag_FlipVertical; XN_METHOD_RETURN(S_OK); } HRESULT STDMETHODCALLTYPE XnVideoSource::GetCurrentActualFrameRate( IPin *pPin, __out LONGLONG *ActualFrameRate ) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pPin); XN_METHOD_CHECK_POINTER(ActualFrameRate); // we have only 1 pin, make sure this is it XnVideoStream* pVideoStream = dynamic_cast<XnVideoStream*>(GetPin(0)); if (pPin != static_cast<IPin*>(pVideoStream)) { XN_METHOD_RETURN(E_FAIL); } *ActualFrameRate = (LONGLONG)(10000000.0 / pVideoStream->GetCurrentFPS() + 0.5); XN_METHOD_RETURN(S_OK); } HRESULT STDMETHODCALLTYPE XnVideoSource::GetMaxAvailableFrameRate( IPin *pPin, long iIndex, SIZE Dimensions, __out LONGLONG *MaxAvailableFrameRate ) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pPin); XN_METHOD_CHECK_POINTER(MaxAvailableFrameRate); HRESULT hr = S_OK; // we have only 1 pin, make sure this is it XnVideoStream* pVideoStream = dynamic_cast<XnVideoStream*>(GetPin(0)); if (pPin != static_cast<IPin*>(pVideoStream)) { XN_METHOD_RETURN(E_FAIL); } AM_MEDIA_TYPE* pMediaType; VIDEO_STREAM_CONFIG_CAPS vscc; hr = pVideoStream->GetStreamCaps(iIndex, &pMediaType, (BYTE*)&vscc); if (FAILED(hr)) XN_METHOD_RETURN(hr); CoTaskMemFree(pMediaType); if (Dimensions.cx != vscc.MaxOutputSize.cx || Dimensions.cy != vscc.MaxOutputSize.cy) XN_METHOD_RETURN(E_FAIL); *MaxAvailableFrameRate = vscc.MaxFrameInterval; XN_METHOD_RETURN(S_OK); } HRESULT STDMETHODCALLTYPE XnVideoSource::GetFrameRateList( IPin *pPin, long iIndex, SIZE Dimensions, __out long *ListSize, __out LONGLONG **FrameRates ) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pPin); XN_METHOD_CHECK_POINTER(ListSize); HRESULT hr = S_OK; // we have only 1 pin, make sure this is it XnVideoStream* pVideoStream = dynamic_cast<XnVideoStream*>(GetPin(0)); if (pPin != static_cast<IPin*>(pVideoStream)) { XN_METHOD_RETURN(E_FAIL); } AM_MEDIA_TYPE* pMediaType; VIDEO_STREAM_CONFIG_CAPS vscc; hr = pVideoStream->GetStreamCaps(iIndex, &pMediaType, (BYTE*)&vscc); if (FAILED(hr)) XN_METHOD_RETURN(hr); CoTaskMemFree(pMediaType); if (Dimensions.cx != vscc.MaxOutputSize.cx || Dimensions.cy != vscc.MaxOutputSize.cy) XN_METHOD_RETURN(E_FAIL); // we return 1 frame rate for each mode (this is the OpenNI way...) *ListSize = 1; if (FrameRates != NULL) { *FrameRates = (LONGLONG*)CoTaskMemAlloc(sizeof(LONGLONG)* (*ListSize)); (*FrameRates)[0] = vscc.MaxFrameInterval; } XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::GetPowerLineFrequencyDefault(XnPowerLineFrequency* pnValue) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pnValue); if (!m_image.IsCapabilitySupported(XN_CAPABILITY_ANTI_FLICKER)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } *pnValue = m_image.GetAntiFlickerCap().GetPowerLineFrequency(); XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::GetPowerLineFrequency(XnPowerLineFrequency *pnValue) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pnValue); if (!m_image.IsCapabilitySupported(XN_CAPABILITY_ANTI_FLICKER)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } *pnValue = m_image.GetAntiFlickerCap().GetPowerLineFrequency(); XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::SetPowerLineFrequency(XnPowerLineFrequency nValue) { XN_METHOD_START; if (!m_image.IsCapabilitySupported(XN_CAPABILITY_ANTI_FLICKER)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } XnStatus nRetVal = m_image.GetAntiFlickerCap().SetPowerLineFrequency(nValue); if (nRetVal != XN_STATUS_OK) { XN_METHOD_RETURN(E_FAIL); } XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::GetGainRange(XnInt32 *pnMin, XnInt32* pnMax, XnInt32* pnStep, XnInt32* pnDefault, XnBool* pbAutoSupported) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pnMin); XN_METHOD_CHECK_POINTER(pnMax); XN_METHOD_CHECK_POINTER(pnStep); XN_METHOD_CHECK_POINTER(pnDefault); XN_METHOD_CHECK_POINTER(pbAutoSupported); if (!m_image.IsCapabilitySupported(XN_CAPABILITY_GAIN)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } xn::GeneralIntCapability cap = m_image.GetGainCap(); cap.GetRange(*pnMin, *pnMax, *pnStep, *pnDefault, *pbAutoSupported); XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::GetGain(XnInt32 *pnValue) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pnValue); if (!m_image.IsCapabilitySupported(XN_CAPABILITY_GAIN)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } xn::GeneralIntCapability cap = m_image.GetGainCap(); *pnValue = cap.Get(); XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::SetGain(XnInt32 nValue) { XN_METHOD_START; if (!m_image.IsCapabilitySupported(XN_CAPABILITY_GAIN)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } xn::GeneralIntCapability cap = m_image.GetGainCap(); XnStatus nRetVal = cap.Set(nValue); if (nRetVal != XN_STATUS_OK) { XN_METHOD_RETURN(E_FAIL); } XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::GetLowLightCompensationDefault(XnBool* pbValue) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pbValue); if (!m_image.IsCapabilitySupported(XN_CAPABILITY_LOW_LIGHT_COMPENSATION)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } XnInt32 nMin, nMax, nStep, nDefault; XnBool bAutoSupported; m_image.GetLowLightCompensationCap().GetRange(nMin, nMax, nStep, nDefault, bAutoSupported); *pbValue = nDefault; XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::GetLowLightCompensation(XnBool *pbValue) { XN_METHOD_START; XN_METHOD_CHECK_POINTER(pbValue); if (!m_image.IsCapabilitySupported(XN_CAPABILITY_LOW_LIGHT_COMPENSATION)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } xn::GeneralIntCapability cap = m_image.GetLowLightCompensationCap(); *pbValue = (XnBool)cap.Get(); XN_METHOD_RETURN(S_OK); } STDMETHODIMP XnVideoSource::SetLowLightCompensation(XnBool bValue) { XN_METHOD_START; if (!m_image.IsCapabilitySupported(XN_CAPABILITY_LOW_LIGHT_COMPENSATION)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } xn::GeneralIntCapability cap = m_image.GetLowLightCompensationCap(); XnStatus nRetVal = cap.Set(bValue); if (nRetVal != XN_STATUS_OK) { XN_METHOD_RETURN(E_FAIL); } XN_METHOD_RETURN(S_OK); } HRESULT XnVideoSource::GetCapRange(const XnChar* strCap, long *pMin, long *pMax, long *pSteppingDelta, long *pDefault, long *pCapsFlags) { XN_METHOD_START; if (strCap == NULL || !m_image.IsCapabilitySupported(strCap)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } XN_METHOD_CHECK_POINTER(pMin); XN_METHOD_CHECK_POINTER(pMax); XN_METHOD_CHECK_POINTER(pSteppingDelta); XN_METHOD_CHECK_POINTER(pDefault); XN_METHOD_CHECK_POINTER(pCapsFlags); xn::GeneralIntCapability cap = m_image.GetGeneralIntCap(strCap); XnInt32 nMin, nMax, nStep, nDefault; XnBool bIsAutoSupported; cap.GetRange(nMin, nMax, nStep, nDefault, bIsAutoSupported); *pMin = nMin; *pMax = nMax; *pSteppingDelta = nStep; *pDefault = nDefault; *pCapsFlags = bIsAutoSupported ? 0x01 : 0x02; XN_METHOD_RETURN(S_OK); } HRESULT XnVideoSource::GetCap(const XnChar* strCap, long *lValue, long *Flags) { XN_METHOD_START; if (strCap == NULL || !m_image.IsCapabilitySupported(strCap)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } XN_METHOD_CHECK_POINTER(lValue); XN_METHOD_CHECK_POINTER(Flags); xn::GeneralIntCapability cap = m_image.GetGeneralIntCap(strCap); XnInt32 nVal = cap.Get(); if (nVal == XN_AUTO_CONTROL) { XnInt32 nMin, nMax, nStep, nDefault; XnBool bIsAutoSupported; cap.GetRange(nMin, nMax, nStep, nDefault, bIsAutoSupported); *Flags = 0x01; *lValue = nDefault; } else { *Flags = 0x02; *lValue = nVal; } XN_METHOD_RETURN(S_OK); } HRESULT XnVideoSource::SetCap(const XnChar* strCap, long lValue, long Flags) { XN_METHOD_START; if (strCap == NULL || !m_image.IsCapabilitySupported(strCap)) { XN_METHOD_RETURN(E_PROP_ID_UNSUPPORTED); } xn::GeneralIntCapability cap = m_image.GetGeneralIntCap(strCap); if (Flags == 0x01) { lValue = XN_AUTO_CONTROL; } XnStatus nRetVal = cap.Set(lValue); if (nRetVal != XN_STATUS_OK) { XN_METHOD_RETURN(E_FAIL); } XN_METHOD_RETURN(S_OK); } XnVideoSource::VideoProcAmp::VideoProcAmp(XnVideoSource* pSource) : CUnknown(NAME("XnVideoSource::VideoProcAmp"), pSource->GetOwner()), m_pSource(pSource), m_Dump(pSource->m_Dump) {} const XnChar* XnVideoSource::VideoProcAmp::GetPropertyCap(long Property) { switch (Property) { case VideoProcAmp_Brightness: return XN_CAPABILITY_BRIGHTNESS; case VideoProcAmp_Contrast: return XN_CAPABILITY_CONTRAST; case VideoProcAmp_Hue: return XN_CAPABILITY_HUE; case VideoProcAmp_Saturation: return XN_CAPABILITY_SATURATION; case VideoProcAmp_Sharpness: return XN_CAPABILITY_SHARPNESS; case VideoProcAmp_Gamma: return XN_CAPABILITY_GAMMA; case VideoProcAmp_ColorEnable: return NULL; case VideoProcAmp_WhiteBalance: return XN_CAPABILITY_COLOR_TEMPERATURE; case VideoProcAmp_BacklightCompensation: return XN_CAPABILITY_BACKLIGHT_COMPENSATION; case VideoProcAmp_Gain: return XN_CAPABILITY_GAIN; default: xnLogWarning(XN_MASK_FILTER, "IAMVideoProcAmp: an unknown property (%d was requested)", Property); return NULL; } } STDMETHODIMP XnVideoSource::VideoProcAmp::GetRange(long Property, long *pMin, long *pMax, long *pSteppingDelta, long *pDefault, long *pCapsFlags) { return m_pSource->GetCapRange(GetPropertyCap(Property), pMin, pMax, pSteppingDelta, pDefault, pCapsFlags); } STDMETHODIMP XnVideoSource::VideoProcAmp::Set(long Property, long lValue, long Flags) { return m_pSource->SetCap(GetPropertyCap(Property), lValue, Flags); } STDMETHODIMP XnVideoSource::VideoProcAmp::Get(long Property, long *lValue, long *Flags) { return m_pSource->GetCap(GetPropertyCap(Property), lValue, Flags); } XnVideoSource::CameraControl::CameraControl(XnVideoSource* pSource) : CUnknown(NAME("XnVideoSource::CameraControl"), pSource->GetOwner()), m_pSource(pSource), m_Dump(pSource->m_Dump) {} const XnChar* XnVideoSource::CameraControl::GetPropertyCap(long Property) { switch (Property) { case CameraControl_Pan: return XN_CAPABILITY_PAN; case CameraControl_Tilt: return XN_CAPABILITY_TILT; case CameraControl_Roll: return XN_CAPABILITY_ROLL; case CameraControl_Zoom: return XN_CAPABILITY_ZOOM; case CameraControl_Exposure: return XN_CAPABILITY_EXPOSURE; case CameraControl_Iris: return XN_CAPABILITY_IRIS; case CameraControl_Focus: return XN_CAPABILITY_FOCUS; default: xnLogWarning(XN_MASK_FILTER, "IAMCameraControl: an unknown property (%d was requested)", Property); return NULL; } } STDMETHODIMP XnVideoSource::CameraControl::GetRange(long Property, long *pMin, long *pMax, long *pSteppingDelta, long *pDefault, long *pCapsFlags) { return m_pSource->GetCapRange(GetPropertyCap(Property), pMin, pMax, pSteppingDelta, pDefault, pCapsFlags); } STDMETHODIMP XnVideoSource::CameraControl::Set(long Property, long lValue, long Flags) { return m_pSource->SetCap(GetPropertyCap(Property), lValue, Flags); } STDMETHODIMP XnVideoSource::CameraControl::Get(long Property, long *lValue, long *Flags) { return m_pSource->GetCap(GetPropertyCap(Property), lValue, Flags); }
26.572246
152
0.712071
[ "object" ]
640f26314da5f2357476bc4d6b7eee0522de4e2f
8,322
cc
C++
renderdoc/3rdparty/interceptor-lib/lib/AArch64/target_aarch64.cc
PLohrmannAMD/renderdoc
ea16d31aa340581f5e505e0c734a8468e5d3d47f
[ "MIT" ]
6,181
2015-01-07T11:49:11.000Z
2022-03-31T21:46:55.000Z
renderdoc/3rdparty/interceptor-lib/lib/AArch64/target_aarch64.cc
PLohrmannAMD/renderdoc
ea16d31aa340581f5e505e0c734a8468e5d3d47f
[ "MIT" ]
2,015
2015-01-16T01:45:25.000Z
2022-03-25T12:01:06.000Z
renderdoc/3rdparty/interceptor-lib/lib/AArch64/target_aarch64.cc
PLohrmannAMD/renderdoc
ea16d31aa340581f5e505e0c734a8468e5d3d47f
[ "MIT" ]
1,088
2015-01-06T08:36:25.000Z
2022-03-30T03:31:21.000Z
/* * Copyright (C) 2017 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 "target_aarch64.h" #include <cassert> #include <memory> #include "MCTargetDesc/AArch64MCTargetDesc.h" #include "llvm/ADT/Triple.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstBuilder.h" #include "code_generator.h" #include "disassembler.h" using namespace interceptor; static llvm::Triple GetTriple() { llvm::Triple triple(llvm::sys::getProcessTriple()); assert(triple.getArch() == llvm::Triple::aarch64 && "Invalid default host triple for target"); return triple; } CodeGenerator *TargetAARCH64::GetCodeGenerator(void *address, size_t start_alignment) { return CodeGenerator::Create(GetTriple(), start_alignment); } Disassembler *TargetAARCH64::CreateDisassembler(void *address) { return Disassembler::Create(GetTriple()); } std::vector<TrampolineConfig> TargetAARCH64::GetTrampolineConfigs( uintptr_t start_address) const { std::vector<TrampolineConfig> configs; configs.push_back({FIRST_4G_TRAMPOLINE, false, 0x10000, 0xffffffff}); configs.push_back({FULL_TRAMPOLINE, false, 0, 0xffffffffffffffff}); return configs; } Error TargetAARCH64::EmitTrampoline(const TrampolineConfig &config, CodeGenerator &codegen, void *source, void *target) { switch (config.type) { case FIRST_4G_TRAMPOLINE: { uint64_t target_addr = reinterpret_cast<uintptr_t>(target); if (target_addr > 0xffffffff) return Error("Target address is out of range for the trampoline"); uint32_t target_addr32 = target_addr; codegen.AddInstruction( llvm::MCInstBuilder(llvm::AArch64::LDRWl) .addReg(llvm::AArch64::X17) .addExpr(codegen.CreateDataExpr(target_addr32))); codegen.AddInstruction( llvm::MCInstBuilder(llvm::AArch64::BR).addReg(llvm::AArch64::X17)); return Error(); } case FULL_TRAMPOLINE: { uint64_t target_addr = reinterpret_cast<uintptr_t>(target); codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl) .addReg(llvm::AArch64::X17) .addExpr(codegen.CreateDataExpr(target_addr))); codegen.AddInstruction( llvm::MCInstBuilder(llvm::AArch64::BR).addReg(llvm::AArch64::X17)); return Error(); } } return Error("Unsupported trampoline type"); } static void *calculatePcRelativeAddress(void *data, size_t pc_offset, size_t offset, bool page_align) { uintptr_t data_addr = reinterpret_cast<uintptr_t>(data); assert((data_addr & 3) == 0 && "Unaligned data address"); assert((pc_offset & 3) == 0 && "Unaligned PC offset"); data_addr += pc_offset; // Add the PC if (page_align) { data_addr &= ~0x0fff; // Align to 4KB offset <<= 12; } data_addr += offset; // Add the offset return reinterpret_cast<void *>(data_addr); } // IP1 (second intra-procedure-call scratch register) is X17 and it is used in // the trampoline so we need special handling for it. static bool hasIP1Operand(const llvm::MCInst &inst) { for (size_t i = 0; i < inst.getNumOperands(); ++i) { const llvm::MCOperand &op = inst.getOperand(i); if (op.isReg() && op.getReg() == llvm::AArch64::X17) return true; } return false; } Error TargetAARCH64::RewriteInstruction(const llvm::MCInst &inst, CodeGenerator &codegen, void *data, size_t offset, bool &possible_end_of_function) { switch (inst.getOpcode()) { case llvm::AArch64::ADDXri: case llvm::AArch64::ANDXri: case llvm::AArch64::LDRXui: case llvm::AArch64::MOVNWi: case llvm::AArch64::MOVNXi: case llvm::AArch64::MOVZWi: case llvm::AArch64::MOVZXi: case llvm::AArch64::MRS: case llvm::AArch64::ORRWrs: case llvm::AArch64::ORRXrs: case llvm::AArch64::STPDi: case llvm::AArch64::STPXi: case llvm::AArch64::STPXpre: case llvm::AArch64::STRBBui: case llvm::AArch64::STRSui: case llvm::AArch64::STRWui: case llvm::AArch64::STRXpre: case llvm::AArch64::STRXui: case llvm::AArch64::SUBSWri: case llvm::AArch64::SUBSXri: case llvm::AArch64::SUBXri: { if (hasIP1Operand(inst)) return Error( "Instruction not handled yet when one of the operand is IP1 (%s " "(OpcodeId: %d))", codegen.PrintInstruction(inst).c_str(), inst.getOpcode()); possible_end_of_function = false; codegen.AddInstruction(inst); break; } case llvm::AArch64::ADRP: { uint32_t Rd = inst.getOperand(0).getReg(); uint64_t imm = inst.getOperand(1).getImm(); possible_end_of_function = false; if (hasIP1Operand(inst)) return Error( "Instruction not handled yet when one of the operand is IP1 (%s " "(OpcodeId: %d))", codegen.PrintInstruction(inst).c_str(), inst.getOpcode()); uint64_t addr = reinterpret_cast<uintptr_t>( calculatePcRelativeAddress(data, offset, imm, true)); codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl) .addReg(Rd) .addExpr(codegen.CreateDataExpr(addr))); break; } case llvm::AArch64::B: { uint64_t imm = inst.getOperand(0).getImm() << 2; possible_end_of_function = true; uint64_t addr = reinterpret_cast<uintptr_t>( calculatePcRelativeAddress(data, offset, imm, false)); codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl) .addReg(llvm::AArch64::X17) .addExpr(codegen.CreateDataExpr(addr))); codegen.AddInstruction( llvm::MCInstBuilder(llvm::AArch64::BR).addReg(llvm::AArch64::X17)); break; } case llvm::AArch64::BL: { uint64_t imm = inst.getOperand(0).getImm() << 2; possible_end_of_function = true; uint64_t addr = reinterpret_cast<uintptr_t>( calculatePcRelativeAddress(data, offset, imm, false)); codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl) .addReg(llvm::AArch64::X17) .addExpr(codegen.CreateDataExpr(addr))); codegen.AddInstruction( llvm::MCInstBuilder(llvm::AArch64::BLR).addReg(llvm::AArch64::X17)); break; } case llvm::AArch64::CBZX: { uint32_t Rt = inst.getOperand(0).getReg(); uint64_t imm = inst.getOperand(1).getImm() << 2; possible_end_of_function = false; if (hasIP1Operand(inst)) return Error( "Instruction not handled yet when one of the operand is IP0 (%s " "(OpcodeId: %d))", codegen.PrintInstruction(inst).c_str(), inst.getOpcode()); uint64_t addr = reinterpret_cast<uintptr_t>( calculatePcRelativeAddress(data, offset, imm, false)); codegen.AddInstruction( llvm::MCInstBuilder(llvm::AArch64::CBNZX).addReg(Rt).addImm(12 >> 2)); codegen.AddInstruction(llvm::MCInstBuilder(llvm::AArch64::LDRXl) .addReg(llvm::AArch64::X17) .addExpr(codegen.CreateDataExpr(addr))); codegen.AddInstruction( llvm::MCInstBuilder(llvm::AArch64::BR).addReg(llvm::AArch64::X17)); break; } default: { possible_end_of_function = true; return Error("Unhandled instruction: %s (OpcodeId: %d)", codegen.PrintInstruction(inst).c_str(), inst.getOpcode()); } } return Error(); }
37.827273
80
0.629536
[ "vector" ]
641200a584bf524733513c464824c46a6f250a50
2,709
cpp
C++
c++/sql_load_location.cpp
jrrpanix/reference
2d6774ca5aefee8d215279ee552a684a1d6a3906
[ "MIT" ]
1
2022-01-27T16:21:49.000Z
2022-01-27T16:21:49.000Z
c++/sql_load_location.cpp
jrrpanix/reference
2d6774ca5aefee8d215279ee552a684a1d6a3906
[ "MIT" ]
null
null
null
c++/sql_load_location.cpp
jrrpanix/reference
2d6774ca5aefee8d215279ee552a684a1d6a3906
[ "MIT" ]
null
null
null
#include <mysql/mysql.h> #include <string> #include <iostream> #include <sstream> #include <vector> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> struct Location { Location() : person_id(0),tracker_id(0),date(0),time(0),latitude(0), longitude(0) {} int persion_id; int tracker_id; int date; int time; double latitude; double longitude; }; typedef boost::shared_ptr<Location> LocationPtr; typedef std::vector<LocationPtr> LocationVec; std::ostream &operator<<( std::ostream &stream , const LocationPtr &loc ) { stream << loc->person_id << "," << loc->tracker_id << "," << loc->date << "," << loc->time << "," << loc->latitude << "," << loc->longitude; return stream; } MYSQL *get_connection( const std::string &Uid , const std::string &Pwd , const std::string &Db) { MYSQL *conn = mysql_init(NULL); const char *host = "localhost"; const char *user = Uid.c_str(); const char *pwd = Pwd.c_str(); const char *db = Db.c_str(); if ( mysql_real_connect( conn , host , user, pwd , db , 0 , NULL , 0 ) == NULL ) { std::cout << mysql_error(conn) << std::endl; return 0; } return conn; } int get_locations( MYSQL *conn , int person_id , LocationVec &locV ) { std::stringstream strm; strm << "select tracker_id,date,time,latitude,longitude " << "from tracking_table where " << "person_id=" << person_id; int rv = mysql_query( conn , strm.str().c_str()); if ( rv ) { std::cerr << mysql_error(conn) << std::endl; return rv; } MYSQL_RES *result = mysql_store_result(conn ); MYSQL_ROW row; while ( ( row = mysql_fetch_row( result ) ) ) { size_t i = 0; LocationPtr loc( new Location() ); loc->person_id = person_id; loc->tracker_id = boost::lexical_cast<int>(row[i++]); loc->date = boost::lexical_cast<int>(row[i++]); loc->time = boost::lexical_cast<int>(row[i++]); loc->latitude = boost::lexical_cast<double>(row[i++]); loc->longitude = boost::lexical_cast<double>(row[i++]); locV.push_back(loc); } return rv; } int main ( int argc , char **argv ) { if ( argc != 5 ) { std::cerr << "usage " << argv[0] << " <person_id> <uid> <pwd> <db>" << std::endl; return -1; } int person_id = boost::lexical_cast<int>(argv[1]); std::string uid = argv[2]; std::string pwd = argv[3]; std::string db = argv[4]; MYSQL *conn = get_connection(uid,pwd,db); if ( !conn ) { return -1; } LocationVec locV; get_locations( conn , person_id , locV ); for( size_t i = 0; i < locV.size() ; i++ ) std::cout << locV[i] << std::endl; mysql_close(conn); return 0; }
24.853211
95
0.598376
[ "vector" ]
641bed6bb00f1c3baf47eb646c12eae7c168bae3
4,658
cpp
C++
src/TextRenderer.cpp
adinh254/Pong-GL
1f1526f68ffdb75251600355a72bbe8cda50fb79
[ "MIT" ]
null
null
null
src/TextRenderer.cpp
adinh254/Pong-GL
1f1526f68ffdb75251600355a72bbe8cda50fb79
[ "MIT" ]
null
null
null
src/TextRenderer.cpp
adinh254/Pong-GL
1f1526f68ffdb75251600355a72bbe8cda50fb79
[ "MIT" ]
null
null
null
#include "TextRenderer.h" bool TextRenderer::init( const glm::mat4& projection ) { projection_ = projection; // Position of text layout_.push<GLfloat>( 2 ); // Texture coordinates layout_.push<GLfloat>( 2 ); if( FT_Init_FreeType( &ft_ ) ) { SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize Freetype Library!\n" ); return false; } if( !shader_.init( "./shaders/text.vertex", "./shaders/text.fragment" ) ) { SDL_LogWarn( SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize Text Shaders!\n" ); return false; } return true; } bool TextRenderer::loadTTF( const std::string& font, GLuint size ) { // Clear old font set characters_.clear(); FT_Face face; if( FT_New_Face( ft_, font.c_str(), 0, &face ) ) { SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "Unable to load font!\n" ); return false; } // Set size of glyphs FT_Set_Pixel_Sizes( face, 0, size ); // Disable byte-alignment to one byte per pixel since FT loads characters in one channel grayscale glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); for( GLubyte ch = 0; ch < 128; ch++ ) { if( FT_Load_Char( face, ch, FT_LOAD_RENDER ) ) continue; // If char doesn't exist // Generate texture GLuint texture; glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); glTexImage2D( GL_TEXTURE_2D, 0, GL_R8, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer ); // Set Texture options glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // Store character Character chara = { texture, glm::vec2( face->glyph->bitmap.width, face->glyph->bitmap.rows ), glm::vec2( face->glyph->bitmap_left, face->glyph->bitmap_top ), face->glyph->advance.x, }; GLfloat width = chara.size.x; GLfloat height = chara.size.y; height_ = height; GLfloat x_pos = chara.bearing.x; GLfloat y_pos = height - chara.bearing.y; // For characters rendered below baseline https://learnopengl.com/In-Practice/Text-Rendering chara.vertices = { { glm::vec2( x_pos, y_pos ), glm::vec2( 0.0f, 0.0f ) }, // Top Left { glm::vec2( x_pos + width, y_pos ), glm::vec2( 1.0f, 0.0f ) }, // Top right { glm::vec2( x_pos + width, y_pos + height ), glm::vec2( 1.0f, 1.0f) }, // Bottom right { glm::vec2( x_pos, y_pos + height ), glm::vec2( 0.0f, 1.0f) } // Bottom left }; characters_.insert( std::pair<GLubyte, Character>(ch, chara) ); } std::vector<GLuint> indices = { 0, 1, 2, 2, 3, 0 }; // Initialize first number as a mesh mesh_.init( characters_[ '0' ].vertices, indices, layout_, GL_DYNAMIC_DRAW ); mesh_.addModel( glm::mat4( 1.0f ) ); // Unbind Texture glBindTexture( GL_TEXTURE_2D, 0 ); // Destroy Freetype FT_Done_Face( face ); return true; } GLfloat TextRenderer::getTextWidth( const std::string& text ) const { GLfloat size = 0; Character chara; for( size_t i = 0; i < text.size() - 1; i++ ) { chara = characters_.at( text[i] ); size += ( chara.offset >> 6 ); } size += ( chara.offset >> 6 ) / 2.0f; // Last offset is divided by 2 return size; } GLfloat TextRenderer::getFontHeight() const { return height_; } void TextRenderer::renderText( const std::string& text, GLfloat x, GLfloat y, GLfloat scale, const glm::vec4& color, bool advance_left ) { GLfloat x_offset = x; glm::mat4 font_scale = glm::scale( glm::mat4( 1.0f ), glm::vec3( scale, scale, 0.0f ) ); shader_.bind(); // Set text color shader_.setUniform4f( "text_color", color ); glActiveTexture( GL_TEXTURE0 ); auto lambda = [&]( const Character& chara ) { glm::mat4 translation = glm::translate( glm::mat4( 1.0f ), glm::vec3( x_offset, y, 0.0f ) ); glm::mat4 model = translation * font_scale; glm::mat4 mvp = projection_ * model; shader_.setUniformMat4f( "mvp", mvp ); glBindTexture( GL_TEXTURE_2D, chara.id ); mesh_.setVertices( chara.vertices, 0 ); mesh_.render(); if( advance_left ) x_offset -= ( chara.offset >> 6 ) * scale; else x_offset += ( chara.offset >> 6 ) * scale; }; if( advance_left ) for( auto it = text.rbegin(); it != text.rend(); it++ ) lambda( characters_[ *it ] ); else for( const auto& ch : text ) lambda( characters_[ ch ] ); glBindTexture( GL_TEXTURE_2D, 0 ); } void TextRenderer::shutDown() { FT_Done_FreeType( ft_ ); mesh_.shutDown(); shader_.shutDown(); } TextRenderer::TextRenderer() {} TextRenderer::~TextRenderer() {}
26.770115
136
0.672606
[ "mesh", "render", "vector", "model" ]
641c1381a6e15979852c0c7371f88e4a648496b9
1,449
cpp
C++
android-28/javax/net/ssl/SNIHostName.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/javax/net/ssl/SNIHostName.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/javax/net/ssl/SNIHostName.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JByteArray.hpp" #include "../../../JObject.hpp" #include "../../../JString.hpp" #include "./SNIMatcher.hpp" #include "./SNIHostName.hpp" namespace javax::net::ssl { // Fields // QJniObject forward SNIHostName::SNIHostName(QJniObject obj) : javax::net::ssl::SNIServerName(obj) {} // Constructors SNIHostName::SNIHostName(JByteArray arg0) : javax::net::ssl::SNIServerName( "javax.net.ssl.SNIHostName", "([B)V", arg0.object<jbyteArray>() ) {} SNIHostName::SNIHostName(JString arg0) : javax::net::ssl::SNIServerName( "javax.net.ssl.SNIHostName", "(Ljava/lang/String;)V", arg0.object<jstring>() ) {} // Methods javax::net::ssl::SNIMatcher SNIHostName::createSNIMatcher(JString arg0) { return callStaticObjectMethod( "javax.net.ssl.SNIHostName", "createSNIMatcher", "(Ljava/lang/String;)Ljavax/net/ssl/SNIMatcher;", arg0.object<jstring>() ); } jboolean SNIHostName::equals(JObject arg0) const { return callMethod<jboolean>( "equals", "(Ljava/lang/Object;)Z", arg0.object<jobject>() ); } JString SNIHostName::getAsciiName() const { return callObjectMethod( "getAsciiName", "()Ljava/lang/String;" ); } jint SNIHostName::hashCode() const { return callMethod<jint>( "hashCode", "()I" ); } JString SNIHostName::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } } // namespace javax::net::ssl
21
82
0.659075
[ "object" ]
641d940d948a32e14698630d61cf26a6e2cd36c7
4,603
cpp
C++
simplefvm/src/MeshLoader/SolverDataPackers/CellNumsPacker/NumsPackerV.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
4
2022-01-03T08:45:55.000Z
2022-01-06T19:57:11.000Z
simplefvm/src/MeshLoader/SolverDataPackers/CellNumsPacker/NumsPackerV.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
simplefvm/src/MeshLoader/SolverDataPackers/CellNumsPacker/NumsPackerV.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
#include "NumsPackerV.h" namespace meshloader { NumsPackerV::NumsPackerV(DataStoreMasks& dataStoreMasks, Mesh& mesh, NumsSets& numsSets) : AbstractNumsPacker(dataStoreMasks, mesh, numsSets) { } void NumsPackerV::createStores(std::string partName, size_t partSize) { dataStoreMasks_.getCellInterNumsVMask(partName).createStore(partSize); dataStoreMasks_.getCellNumsGlobalVMask(partName).createStore(partSize); dataStoreMasks_.getAdjCellGlobalNumsVMask(partName).createStore(partSize); dataStoreMasks_.getAdjCellInterNumsVMask(partName).createStore(partSize); } void NumsPackerV::packPart(std::string partName, size_t partSize) { packCellInteriorNum( partName, partSize, dataStoreMasks_.getCellInterNumsVMask(partName) ); packAdjCellInteriorNum( partName, partSize, dataStoreMasks_.getAdjCellInterNumsVMask(partName) ); packCellGlobalNum( partName, partSize, dataStoreMasks_.getCellNumsGlobalVMask(partName) ); packAdjCellGlobalNum( partName, partSize, dataStoreMasks_.getAdjCellGlobalNumsVMask(partName) ); } void NumsPackerV::packCellInteriorNum(std::string partName, size_t partSize, CellNumsInteriorMask& dataMask) { for (size_t idx = 0; idx < partSize; idx++) { size_t num = numsSets_.getNumsSet(partName[0]).at(idx); dataMask.setCellNumP(idx, mesh_.getCell(num)->getCellV().getInteriorNum()); dataMask.setCellNumW(idx, mesh_.getAdjCellW(num)->getCellV().getInteriorNum()); dataMask.setCellNumE(idx, mesh_.getAdjCellE(num)->getCellV().getInteriorNum()); dataMask.setCellNumN(idx, mesh_.getAdjCellN(num)->getCellV().getInteriorNum()); dataMask.setCellNumS(idx, mesh_.getAdjCellS(num)->getCellV().getInteriorNum()); } } void NumsPackerV::packCellGlobalNum(std::string partName, size_t partSize, CellNumsGlobalMask& dataMask) { for (size_t idx = 0; idx < partSize; idx++) { size_t num = numsSets_.getNumsSet(partName[0]).at(idx); dataMask.set_pCellNum(idx, mesh_.getCell(num)->getCellV().getGlobalNum()); dataMask.set_wCellNum(idx, mesh_.getAdjCellW(num)->getCellV().getGlobalNum()); dataMask.set_eCellNum(idx, mesh_.getAdjCellE(num)->getCellV().getGlobalNum()); dataMask.set_nCellNum(idx, mesh_.getAdjCellN(num)->getCellV().getGlobalNum()); dataMask.set_sCellNum(idx, mesh_.getAdjCellS(num)->getCellV().getGlobalNum()); } } void NumsPackerV::packAdjCellGlobalNum(std::string partName, size_t partSize, AdjCellGlobalNumsVMask& dataMask) { for (size_t idx = 0; idx < partSize; idx++) { size_t num = numsSets_.getNumsSet(partName[0]).at(idx); dataMask.setNumPp(idx, mesh_.getCell(num)->getCellP().getGlobalNum()); dataMask.setNumPs(idx, mesh_.getAdjCellS(num)->getCellP().getGlobalNum()); dataMask.setNumVn(idx, mesh_.getAdjCellN(num)->getCellV().getGlobalNum()); dataMask.setNumVs(idx, mesh_.getAdjCellS(num)->getCellV().getGlobalNum()); dataMask.setNumUen(idx, mesh_.getAdjCellE(num)->getCellU().getGlobalNum()); dataMask.setNumUes(idx, mesh_.getAdjCellE(mesh_.getAdjCellS(num)-> getCellGlobalNum())->getCellU().getGlobalNum()); dataMask.setNumUwn(idx, mesh_.getCell(num)->getCellU().getGlobalNum()); dataMask.setNumUws(idx, mesh_.getAdjCellS(num)->getCellU().getGlobalNum()); } } void NumsPackerV::packAdjCellInteriorNum(std::string partName, size_t partSize, AdjCellInteriorNumsVMask& dataMask) { for (size_t idx = 0; idx < partSize; idx++) { size_t num = numsSets_.getNumsSet(partName[0]).at(idx); dataMask.set_numPp(idx, mesh_.getCell(num)->getCellP().getInteriorNum()); dataMask.set_numPs(idx, mesh_.getAdjCellS(num)->getCellP().getInteriorNum()); } } }
32.415493
78
0.594178
[ "mesh" ]
6423e8a9b83ffe80f33111482b40f640462dda4c
12,838
cpp
C++
NFServer/NFDataAgent_NosqlPlugin/NFCPlayerRedisModule.cpp
schwantz/NoahGameFrame
67764fa16f3bed646e6c14caa34b3e3bb7b09abd
[ "Apache-2.0" ]
null
null
null
NFServer/NFDataAgent_NosqlPlugin/NFCPlayerRedisModule.cpp
schwantz/NoahGameFrame
67764fa16f3bed646e6c14caa34b3e3bb7b09abd
[ "Apache-2.0" ]
null
null
null
NFServer/NFDataAgent_NosqlPlugin/NFCPlayerRedisModule.cpp
schwantz/NoahGameFrame
67764fa16f3bed646e6c14caa34b3e3bb7b09abd
[ "Apache-2.0" ]
null
null
null
// ------------------------------------------------------------------------- // @FileName : NFCPlayerRedisModule.cpp // @Author : LvSheng.Huang // @Date : 2013-10-03 // @Module : NFCPlayerRedisModule // @Desc : // ------------------------------------------------------------------------- #include "NFCPlayerRedisModule.h" NFCPlayerRedisModule::NFCPlayerRedisModule(NFIPluginManager * p) { pPluginManager = p; } bool NFCPlayerRedisModule::Init() { m_pLogicClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pNoSqlModule = pPluginManager->FindModule<NFINoSqlModule>(); m_pCommonRedisModule = pPluginManager->FindModule<NFICommonRedisModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pKernelModule->RegisterCommonPropertyEvent(this, &NFCPlayerRedisModule::OnPropertyCommonEvent); m_pKernelModule->RegisterCommonRecordEvent(this, &NFCPlayerRedisModule::OnRecordCommonEvent); return true; } int NFCPlayerRedisModule::OnPropertyCommonEvent(const NFGUID & self, const std::string & strPropertyName, const NFData & oldVar, const NFData & newVar) { const std::string& strClassName = m_pKernelModule->GetPropertyString(self, NFrame::IObject::ClassName()); if (strClassName == NFrame::Player::ThisName()) { NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self); if (pObject) { NF_SHARE_PTR<NFIPropertyManager> pPropertyManager = pObject->GetPropertyManager(); if (pPropertyManager) { NF_SHARE_PTR<NFIProperty> pPropertyInfo = pPropertyManager->GetElement(strPropertyName); if (pPropertyInfo) { if (pPropertyInfo->GetForce()) { //save data with real-time } } } } } return 0; } int NFCPlayerRedisModule::OnRecordCommonEvent(const NFGUID & self, const RECORD_EVENT_DATA & xEventData, const NFData & oldVar, const NFData & newVar) { const std::string& strClassName = m_pKernelModule->GetPropertyString(self, NFrame::IObject::ClassName()); if (strClassName == NFrame::Player::ThisName()) { NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self); if (pObject) { NF_SHARE_PTR<NFIRecordManager> pRecordManager = pObject->GetRecordManager(); if (pRecordManager) { NF_SHARE_PTR<NFIRecord> pRecordInfo = pRecordManager->GetElement(xEventData.strRecordName); if (pRecordInfo) { if (pRecordInfo->GetForce()) { //save data with real-time } } } } } return 0; } bool NFCPlayerRedisModule::Shut() { return true; } bool NFCPlayerRedisModule::Execute() { return true; } bool NFCPlayerRedisModule::AfterInit() { m_pKernelModule->AddClassCallBack(NFrame::Player::ThisName(), this, &NFCPlayerRedisModule::OnObjectPlayerEvent); m_pKernelModule->AddClassCallBack(NFrame::Guild::ThisName(), this, &NFCPlayerRedisModule::OnObjectGuildEvent); return true; } bool NFCPlayerRedisModule::LoadPlayerData(const NFGUID & self) { mxObjectDataCache.RemoveElement(self); m_pLogModule->LogNormal(NFILogModule::NF_LOG_LEVEL::NLL_DEBUG_NORMAL, self, "Start to load data ", NFGetTimeMS()); NF_SHARE_PTR<PlayerDataCache> xPlayerDataCache(NF_NEW PlayerDataCache()); mxObjectDataCache.AddElement(self, xPlayerDataCache); m_pCommonRedisModule->GetCachePropertyInfo(self, NFrame::Player::ThisName(), xPlayerDataCache->mvPropertyKeyList, xPlayerDataCache->mvPropertyValueList); m_pCommonRedisModule->GetCacheRecordInfo(self, NFrame::Player::ThisName(), xPlayerDataCache->mvRecordKeyList, xPlayerDataCache->mvRecordValueList); //xPlayerDataCache->nHomeSceneID = xPlayerDataCache->xPropertyManager->GetPropertyInt(NFrame::Player::HomeSceneID()); for (int i = 0; i < xPlayerDataCache->mvPropertyKeyList.size(); ++i) { if (xPlayerDataCache->mvPropertyKeyList[i] == NFrame::Player::HomeSceneID()) { const std::string& strValue = xPlayerDataCache->mvPropertyValueList[i]; xPlayerDataCache->nHomeSceneID = lexical_cast<int>(strValue); break; } } m_pLogModule->LogNormal(NFILogModule::NF_LOG_LEVEL::NLL_DEBUG_NORMAL, self, "loaded data ", NFGetTimeMS()); return true; } int NFCPlayerRedisModule::GetPlayerHomeSceneID(const NFGUID & self) { NF_SHARE_PTR<PlayerDataCache> xPlayerDataCache = mxObjectDataCache.GetElement(self); if (xPlayerDataCache) { return xPlayerDataCache->nHomeSceneID; } return 0; } bool NFCPlayerRedisModule::SavePlayerTile(const int nSceneID, const NFGUID & self, const std::string & strTileData) { std::string strTileKey = m_pCommonRedisModule->GetTileCacheKey(nSceneID); NF_SHARE_PTR<NFINoSqlDriver> xNoSqlDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (xNoSqlDriver) { return xNoSqlDriver->HSet(strTileKey, self.ToString(), strTileData); } return false; } bool NFCPlayerRedisModule::LoadPlayerTile(const int nSceneID, const NFGUID & self, std::string & strTileData) { std::string strTileKey = m_pCommonRedisModule->GetTileCacheKey(nSceneID); NF_SHARE_PTR<NFINoSqlDriver> xNoSqlDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (xNoSqlDriver && xNoSqlDriver->Exists(strTileKey)) { return xNoSqlDriver->HGet(strTileKey, self.ToString(), strTileData); } return false; } bool NFCPlayerRedisModule::LoadPlayerTileRandom(const int nSceneID, NFGUID& xPlayer, std::string & strTileData) { std::string strTileKey = m_pCommonRedisModule->GetTileCacheKey(nSceneID); NF_SHARE_PTR<NFINoSqlDriver> xNoSqlDriver = m_pNoSqlModule->GetDriverBySuit(xPlayer.ToString()); if (xNoSqlDriver && xNoSqlDriver->Exists(strTileKey)) { //need to cache this keys std::vector<std::string> vKeys; if (xNoSqlDriver->HKeys(strTileKey, vKeys)) { int nKeyIndex = m_pKernelModule->Random(0, (int)vKeys.size()); std::string strKey = vKeys[nKeyIndex]; if (xPlayer.FromString(strKey) && xNoSqlDriver->HGet(strTileKey, strKey, strTileData)) { if (mxObjectTileCache.ExistElement(xPlayer)) { mxObjectTileCache.RemoveElement(xPlayer); } mxObjectTileCache.AddElement(xPlayer, NF_SHARE_PTR<std::string>(NF_NEW std::string(strTileData))); return true; } } } return false; } bool NFCPlayerRedisModule::LoadPlayerTileRandomCache(const NFGUID & xPlayer, std::string & strTileData) { if (mxObjectTileCache.ExistElement(xPlayer)) { NF_SHARE_PTR<std::string> xData = mxObjectTileCache.GetElement(xPlayer); if (xData) { strTileData = *xData; } return true; } return false; } NFINT64 NFCPlayerRedisModule::GetPropertyInt(const NFGUID & self, const std::string & strPropertyName) { NF_SHARE_PTR<NFINoSqlDriver> pDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (!pDriver) { return 0; } std::string strValue; std::string strCacheKey = m_pCommonRedisModule->GetPropertyCacheKey(self); if (!pDriver->HGet(strCacheKey, strPropertyName, strValue)) { return 0; } return lexical_cast<NFINT64>(strValue); } int NFCPlayerRedisModule::GetPropertyInt32(const NFGUID & self, const std::string & strPropertyName) { NF_SHARE_PTR<NFINoSqlDriver> pDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (!pDriver) { return 0; } std::string strValue; std::string strCacheKey = m_pCommonRedisModule->GetPropertyCacheKey(self); if (!pDriver->HGet(strCacheKey, strPropertyName, strValue)) { return 0; } return lexical_cast<NFINT64>(strValue); } double NFCPlayerRedisModule::GetPropertyFloat(const NFGUID & self, const std::string & strPropertyName) { NF_SHARE_PTR<NFINoSqlDriver> pDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (!pDriver) { return 0; } std::string strValue; std::string strCacheKey = m_pCommonRedisModule->GetPropertyCacheKey(self); if (!pDriver->HGet(strCacheKey, strPropertyName, strValue)) { return 0; } return lexical_cast<double>(strValue); } std::string NFCPlayerRedisModule::GetPropertyString(const NFGUID & self, const std::string & strPropertyName) { NF_SHARE_PTR<NFINoSqlDriver> pDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (!pDriver) { return ""; } std::string strValue; std::string strCacheKey = m_pCommonRedisModule->GetPropertyCacheKey(self); if (!pDriver->HGet(strCacheKey, strPropertyName, strValue)) { return ""; } return strValue; } NFGUID NFCPlayerRedisModule::GetPropertyObject(const NFGUID & self, const std::string & strPropertyName) { NF_SHARE_PTR<NFINoSqlDriver> pDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (!pDriver) { return NFGUID(); } std::string strValue; std::string strCacheKey = m_pCommonRedisModule->GetPropertyCacheKey(self); if (!pDriver->HGet(strCacheKey, strPropertyName, strValue)) { return NFGUID(); } NFGUID xID; xID.FromString(strValue); return xID; } NFVector2 NFCPlayerRedisModule::GetPropertyVector2(const NFGUID & self, const std::string & strPropertyName) { NF_SHARE_PTR<NFINoSqlDriver> pDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (!pDriver) { return NFVector2(); } std::string strValue; std::string strCacheKey = m_pCommonRedisModule->GetPropertyCacheKey(self); if (!pDriver->HGet(strCacheKey, strPropertyName, strValue)) { return NFVector2(); } NFVector2 xValue; xValue.FromString(strValue); return xValue; } NFVector3 NFCPlayerRedisModule::GetPropertyVector3(const NFGUID & self, const std::string & strPropertyName) { NF_SHARE_PTR<NFINoSqlDriver> pDriver = m_pNoSqlModule->GetDriverBySuit(self.ToString()); if (!pDriver) { return NFVector3(); } std::string strValue; std::string strCacheKey = m_pCommonRedisModule->GetPropertyCacheKey(self); if (!pDriver->HGet(strCacheKey, strPropertyName, strValue)) { return NFVector3(); } NFVector3 xValue; xValue.FromString(strValue); return xValue; } bool NFCPlayerRedisModule::SavePlayerData(const NFGUID & self) { m_pCommonRedisModule->SaveCachePropertyInfo(self, m_pKernelModule->GetObject(self)->GetPropertyManager()); m_pCommonRedisModule->SaveCacheRecordInfo(self, m_pKernelModule->GetObject(self)->GetRecordManager()); return true; } std::string NFCPlayerRedisModule::GetOnlineGameServerKey() { //if (strValue == "**nonexistent-key**") return "OnlineGameKey"; } std::string NFCPlayerRedisModule::GetOnlineProxyServerKey() { return "OnlineProxyKey"; } const bool NFCPlayerRedisModule::AttachData(const NFGUID & self) { NF_SHARE_PTR<PlayerDataCache> xPlayerDataCache = mxObjectDataCache.GetElement(self); if (xPlayerDataCache) { //way 1:load first then create object, especially we have loaded nosql plugin NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self); if (pObject) { m_pCommonRedisModule->ConvertPBToPropertyManager(xPlayerDataCache->mvPropertyKeyList, xPlayerDataCache->mvPropertyValueList, pObject->GetPropertyManager()); m_pCommonRedisModule->ConvertPBToRecordManager(xPlayerDataCache->mvRecordKeyList, xPlayerDataCache->mvRecordValueList, pObject->GetRecordManager()); return true; } } else { //way 2:load data when creating a object, especially we donot loaded any sql or nosql plugin } return false; } int NFCPlayerRedisModule::OnObjectPlayerEvent(const NFGUID & self, const std::string & strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFDataList & var) { if (CLASS_OBJECT_EVENT::COE_DESTROY == eClassEvent) { OnOffline(self); m_pLogModule->LogNormal(NFILogModule::NF_LOG_LEVEL::NLL_INFO_NORMAL, self, "start to save data", NFGetTimeMS()); SavePlayerData(self); m_pLogModule->LogNormal(NFILogModule::NF_LOG_LEVEL::NLL_INFO_NORMAL, self, "saved data", NFGetTimeMS()); } else if (CLASS_OBJECT_EVENT::COE_CREATE_LOADDATA == eClassEvent) { OnOnline(self); m_pLogModule->LogNormal(NFILogModule::NF_LOG_LEVEL::NLL_INFO_NORMAL, self, "start to attach data", NFGetTimeMS()); AttachData(self); m_pLogModule->LogNormal(NFILogModule::NF_LOG_LEVEL::NLL_INFO_NORMAL, self, "attached data", NFGetTimeMS()); } else if (CLASS_OBJECT_EVENT::COE_CREATE_FINISH == eClassEvent) { mxObjectDataCache.RemoveElement(self); } return 0; } int NFCPlayerRedisModule::OnObjectGuildEvent(const NFGUID & self, const std::string & strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFDataList & var) { if (CLASS_OBJECT_EVENT::COE_DESTROY == eClassEvent) { SavePlayerData(self); } else if (CLASS_OBJECT_EVENT::COE_CREATE_LOADDATA == eClassEvent) { AttachData(self); } else if (CLASS_OBJECT_EVENT::COE_CREATE_FINISH == eClassEvent) { mxObjectDataCache.RemoveElement(self); } return 0; } void NFCPlayerRedisModule::OnOnline(const NFGUID & self) { //const int nGateID = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::GateID()); //const int nServerID = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::GameID()); } void NFCPlayerRedisModule::OnOffline(const NFGUID & self) { }
29.177273
162
0.747546
[ "object", "vector" ]
64278f84eca6ad1dc5b46686d0a8adfd22507cfb
8,626
cpp
C++
usbdev/usbif_cdc_uart.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
13
2018-02-26T14:56:02.000Z
2022-03-31T06:01:56.000Z
usbdev/usbif_cdc_uart.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
null
null
null
usbdev/usbif_cdc_uart.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
3
2020-11-04T09:15:01.000Z
2021-07-06T09:42:00.000Z
/* ----------------------------------------------------------------------------- * This file is a part of the NVCM Tests project: https://github.com/nvitya/nvcmtests * Copyright (c) 2018 Viktor Nagy, nvitya * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. Permission is granted to anyone to use this * software for any purpose, including commercial applications, and to alter * it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * --------------------------------------------------------------------------- */ /* * file: usbif_cdc_uart.cpp * brief: USB to Serial USB Interface definition * version: 1.00 * date: 2020-08-01 * authors: nvitya */ #include <usbif_cdc_uart.h> #include "platform.h" #include "string.h" #include "traces.h" //---------------------------------------------------- bool TUifCdcUartControl::InitCdcUart(TUifCdcUartData * adataif, THwUart * auart, THwDmaChannel * adma_tx, THwDmaChannel * adma_rx) { dataif = adataif; adataif->control = this; uart = auart; dma_tx = adma_tx; dma_rx = adma_rx; if (!uart || !dma_tx || !dma_rx) { return false; } uart->DmaAssign(true, dma_tx); uart->DmaAssign(false, dma_rx); linecoding.baudrate = uart->baudrate; linecoding.databits = uart->databits; linecoding.paritytype = (uart->parity ? (uart->oddparity ? 1 : 2) : 0); linecoding.charformat = 0; StopUart(); return true; } bool TUifCdcUartControl::InitInterface() { intfdesc.interface_class = 2; // CDC intfdesc.interface_subclass = 2; // Abstract Control Model intfdesc.interface_protocol = 0; // 0 = no class specitic control interface_name = "VCP Control"; // some other descriptors are required AddConfigDesc((void *)&cdc_desc_header_func[0], true); AddConfigDesc((void *)&cdc_desc_call_management[0], true); AddConfigDesc((void *)&cdc_desc_call_acm_func[0], true); AddConfigDesc((void *)&cdc_desc_call_union_func[0], true); // endpoints ep_manage.Init(HWUSB_EP_TYPE_INTERRUPT, false, 64); ep_manage.interval = 10; // polling interval AddEndpoint(&ep_manage); return true; } void TUifCdcUartControl::OnConfigured() { //TRACE("SPEC Device Configured.\r\n"); StartUart(); //ep_manage.EnableRecv(); } bool TUifCdcUartControl::HandleTransferEvent(TUsbEndpoint * aep, bool htod) { return false; } bool TUifCdcUartControl::HandleSetupRequest(TUsbSetupRequest * psrq) { if (0x20 == psrq->request) // set line coding, data stage follows ! { TRACE("VCP Set line coding (SETUP)\r\n"); device->StartSetupData(); // start receiving the data part, which will be handled at the HandleSetupData() return true; } else if (0x21 == psrq->request) // Get line coding { TRACE("VCP Get line coding\r\n"); device->StartSendControlData(&linecoding, sizeof(linecoding)); return true; } else if (0x22 == psrq->request) // Set Control Line State { TRACE("VCP Set Control Line State: %04X\r\n", psrq->value); device->SendControlStatus(true); return true; } return false; } // the setup request's data part comes in a separate phase and so it has a separate callback: bool TUifCdcUartControl::HandleSetupData(TUsbSetupRequest * psrq, void * adata, unsigned adatalen) { if (0x20 == psrq->request) // set line coding { memcpy(&linecoding, adata, sizeof(linecoding)); TRACE("VCP Line Coding data:\r\n baud=%i, format=%i, parity=%i, bits=%i\r\n", linecoding.baudrate, linecoding.charformat, linecoding.paritytype, linecoding.databits ); StopUart(); uart->baudrate = linecoding.baudrate; uart->databits = linecoding.databits; if (linecoding.paritytype) { if (1 == linecoding.paritytype) { uart->oddparity = true; } else { uart->oddparity = false; } uart->parity = true; } else { uart->parity = false; } if (linecoding.charformat) { // stop bits other than 1 is not supported } StartUart(); device->SendControlStatus(true); return true; } return false; } void TUifCdcUartControl::StopUart() { uart_running = false; if (dma_tx) dma_tx->Disable(); if (dma_rx) dma_rx->Disable(); } void TUifCdcUartControl::StartUart() { // re-init the uart with the new parameters uart->Init(uart->devnum); if (!dma_tx || !dma_rx) // DMA required { return; } if (dma_rx) { serial_rxidx = 0; dmaxfer_rx.bytewidth = 1; dmaxfer_rx.count = sizeof(serial_rxbuf); dmaxfer_rx.dstaddr = &serial_rxbuf[0]; dmaxfer_rx.flags = DMATR_CIRCULAR; uart->DmaStartRecv(&dmaxfer_rx); } dataif->Reset(); uart_running = true; } bool TUifCdcUartControl::SerialAddBytes(uint8_t * adata, unsigned adatalen) { if (adatalen > sizeof(serial_txbuf[0]) - serial_txlen) { return false; } else { if (adatalen) { memcpy(&serial_txbuf[serial_txbufidx][serial_txlen], adata, adatalen); serial_txlen += adatalen; } return true; } } void TUifCdcUartControl::SerialSendBytes() { if (serial_txlen && !dma_tx->Active()) { // setup the TX DMA and flip the buffer dmaxfer_tx.flags = 0; dmaxfer_tx.bytewidth = 1; dmaxfer_tx.count = serial_txlen; dmaxfer_tx.srcaddr = &serial_txbuf[serial_txbufidx][0]; uart->DmaStartSend(&dmaxfer_tx); // change the buffer serial_txbufidx ^= 1; serial_txlen = 0; } } void TUifCdcUartControl::Run() { if (!uart_running) { return; } // Put the UART RX data to the inactive USB tx buffer uint8_t c; unsigned dma_write_idx = sizeof(serial_rxbuf) - dma_rx->Remaining(); if (dma_write_idx >= sizeof(serial_rxbuf)) // should not happen { dma_write_idx = 0; } while (dma_write_idx != serial_rxidx) { c = serial_rxbuf[serial_rxidx]; if (!dataif->AddTxByte(c)) { break; } ++serial_rxidx; if (serial_rxidx >= sizeof(serial_rxbuf)) serial_rxidx = 0; } dataif->SendTxBytes(); // send if there are any and it is possible // The USB -> Serial transfers are controlled by the USB Events, // but when the serial buffer is full then it is stalled dataif->TrySendUsbDataToSerial(); // re-enables the USB receive when the USB Rx data transferred to the serial buffer } //------------------------------------------------ bool TUifCdcUartData::InitInterface() { intfdesc.interface_class = 0x0A; // CDC Data intfdesc.interface_subclass = 0; intfdesc.interface_protocol = 0; // no specific protocol interface_name = "VCP Data"; // endpoints ep_input.Init(HWUSB_EP_TYPE_BULK, true, 64); AddEndpoint(&ep_input); ep_output.Init(HWUSB_EP_TYPE_BULK, false, 64); AddEndpoint(&ep_output); Reset(); return true; } void TUifCdcUartData::Reset() { usb_txbufidx = 0; usb_txlen = 0; ready_to_send = true; } void TUifCdcUartData::OnConfigured() { TRACE("VCP Data Configured.\r\n"); Reset(); ep_input.EnableRecv(); } bool TUifCdcUartData::HandleTransferEvent(TUsbEndpoint * aep, bool htod) { if (htod) { usb_rxlen = ep_input.ReadRecvData(&usb_rxbuf[0], sizeof(usb_rxbuf)); //TRACE("%i byte VCP data arrived\r\n", usb_rxlen); #if 0 usb_rxbuf[usb_rxlen] = 0; // terminate the string (array length + 4 required!) TRACE("%s\r\n", &usb_rxbuf[0]); #endif TrySendUsbDataToSerial(); // re-enables USB receive only when the rx bytes are transferred to the serial buffer } else { // the data chunk is successfully sent ready_to_send = true; } return true; } bool TUifCdcUartData::AddTxByte(uint8_t abyte) { if (usb_txlen < sizeof(usb_txbuf[0])) { usb_txbuf[usb_txbufidx][usb_txlen] = abyte; ++usb_txlen; return true; } else { return false; } } bool TUifCdcUartData::SendTxBytes() { if (usb_txlen > 0) { // there is something to send, try to send it if (ready_to_send) { ep_output.StartSendData(&usb_txbuf[usb_txbufidx], usb_txlen); ready_to_send = false; // change the buffer usb_txbufidx ^= 1; usb_txlen = 0; return true; } } return false; } void TUifCdcUartData::TrySendUsbDataToSerial() { if (usb_rxlen && control->SerialAddBytes(&usb_rxbuf[0], usb_rxlen)) { usb_rxlen = 0; ep_input.EnableRecv(); } control->SerialSendBytes(); }
22.581152
130
0.680501
[ "model" ]