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
35948260eacf69345ad5291410fa778288f5d296
1,492
cpp
C++
audio.cpp
nbonaker/ticker
4a9bab2916344914cbc96910c7eff4d9f0e10570
[ "MIT" ]
null
null
null
audio.cpp
nbonaker/ticker
4a9bab2916344914cbc96910c7eff4d9f0e10570
[ "MIT" ]
1
2018-11-06T09:30:23.000Z
2018-11-06T09:30:23.000Z
audio.cpp
nbonaker/ticker
4a9bab2916344914cbc96910c7eff4d9f0e10570
[ "MIT" ]
1
2019-01-23T14:46:11.000Z
2019-01-23T14:46:11.000Z
#include "audio.h" #include "fmod_alphabet_player.h" #include <iostream> static AlphabetPlayer alphabet_player = AlphabetPlayer(); void playNext(void) { alphabet_player.playNext(); } int isReady(void) { return alphabet_player.isReady(); } void setChannels(int i_nchannels) { alphabet_player.setChannels(i_nchannels); } void restart(void) { alphabet_player.restart(); } void stop(void) { alphabet_player.stop(); } void playInstruction(char *i_instruction_name, char *i_file_type) { std::string instruction_name(i_instruction_name); std::string file_type(i_file_type); alphabet_player.playInstruction(instruction_name, i_file_type); } void setRootDir(char *i_dir_name) { std::string dir_name(i_dir_name); alphabet_player.setRootDir(dir_name); } void setAlphabetDir(char *i_dir_name) { std::string dir_name(i_dir_name); alphabet_player.setAlphabetDir(dir_name); } void setConfigDir(char *i_dir_name) { std::string dir_name(i_dir_name); alphabet_player.setConfigDir(dir_name); } void setVolume(float i_val, int i_channel) { alphabet_player.setVolume(i_val, i_channel); } int isPlayingInstruction(void) { return (int)alphabet_player.getIsPlayingInstruction(); } const int *getCurLetterTimes(int *o_size) { const std::vector< int > &letter_times = alphabet_player.getCurLetterTimes(); *o_size = letter_times.size(); return &letter_times[0]; } void setTicks(unsigned int i_nticks) { alphabet_player.setTicks(i_nticks); }
24.459016
79
0.754692
[ "vector" ]
359a6496986c544f1dfa819a8331c787eb864b02
3,373
cpp
C++
src/core/context/Manager.cpp
lsgw/longd
31caabd42a47c05857ae98716ef877052092aabe
[ "MIT" ]
null
null
null
src/core/context/Manager.cpp
lsgw/longd
31caabd42a47c05857ae98716ef877052092aabe
[ "MIT" ]
null
null
null
src/core/context/Manager.cpp
lsgw/longd
31caabd42a47c05857ae98716ef877052092aabe
[ "MIT" ]
null
null
null
#include "Manager.h" #include "Module.h" #include "EventLoop.h" #include "Singleton.h" #define DEFAULT_SLOT_SIZE 8 #define HANDLE_MASK 0xffffffff Manager::Manager() : loop(true), lock_(), index_(1), size_(DEFAULT_SLOT_SIZE), slot_(DEFAULT_SLOT_SIZE, ContextPtr()) { } uint32_t Manager::newContext(const std::string& module, uint32_t handle, uint32_t type, void* data, uint32_t size) { ModulePtr m = Singleton<ModuleList>::instance().query(module); if (!m) { fprintf(stderr, "new %s fail\n", module.c_str()); return 0; } void* actor = m->create(); if (!actor) { fprintf(stderr, "create %s fail\n", module.c_str()); return 0; } ContextPtr ctx(new Context(actor)); ctx->setHandle(registerContext(ctx)); ctx->setModule(m); auto msg = ctx->makeMessage(); msg->source = handle; msg->type = type; msg->data = data; msg->size = size; ctx->recv(msg, 0); return ctx->handle(); } bool Manager::unregisterContext(uint32_t handle) { bool ret = false; lock_.wrlock(); uint32_t hash = handle & (size_ - 1); ContextPtr ctx = slot_[hash]; if (ctx && ctx->handle() == handle) { slot_[hash] = std::shared_ptr<Context>(); ret = true; } lock_.unlock(); return ret; } uint32_t Manager::registerContext(ContextPtr ctx) { lock_.wrlock(); while (true) { for(uint32_t i=0; i<size_; i++) { uint32_t handle = (i + index_) & HANDLE_MASK; uint32_t hash = handle & (size_ - 1); if (!slot_[hash] && handle>0) { slot_[hash] = ctx; index_ = handle + 1; lock_.unlock(); return handle; } } assert((size_*2 - 1) < HANDLE_MASK); std::vector<ContextPtr> new_slot(size_*2, ContextPtr()); for (uint32_t i=0; i<size_; i++) { uint32_t hash = slot_[i]->handle() & (size_*2-1); assert(slot_[i].get() != NULL); new_slot[hash] = slot_[i]; } slot_.swap(new_slot); size_ *= 2; } return 0; } ContextPtr Manager::grab(uint32_t handle) { ContextPtr result; lock_.rdlock(); uint32_t hash = handle & (size_ - 1); //printf("hash = %d, size-1=%d,", hash, size_-1); if (slot_[hash] && slot_[hash]->handle() == handle) { result = slot_[hash]; } lock_.unlock(); return result; } void Manager::push(ContextPtr ctx) { SpinLockGuard lockPending(spinPending_); contextsPending_.push_front(ctx); } ContextPtr Manager::pop() { ContextPtr ctx; { SpinLockGuard lock(spin_); if (contexts_.empty()) { { SpinLockGuard lockPending(spinPending_); if (!contextsPending_.empty()) { contexts_.swap(contextsPending_); } } if (!contexts_.empty()) { ctx = contexts_.back(); contexts_.pop_back(); } } else { ctx = contexts_.back(); contexts_.pop_back(); } } return ctx; } bool Manager::dispatchContext(Monitor::WatcherPtr watcher) { auto ctx = pop(); if (ctx) { ctx->dispatch(watcher); return false; } else { return true; } } bool Manager::postMessage(uint32_t handle, MessagePtr message, int priority) { ContextPtr ctx = grab(handle); // printf("postMessage handle:%u, source:%u, session:%d", handle, message->source, message->session); if (ctx) { // printf(" find\n"); ctx->recv(message, priority); return true; } else { // printf(" not find\n"); return false; } } void Manager::abort() { loop = false; Singleton<Monitor>::instance().notsleep.notifyAll(); Singleton<EventLoop>::instance().wakeup(); }
18.635359
114
0.641862
[ "vector" ]
35b4a2d3965581ad468e951cc9c90dba8c8e4500
4,626
cpp
C++
src/fade2d/Fade2D.cpp
Gigi1237/Bounce
6e674dd7babda0192b930cc532f692c75219d1fd
[ "MIT" ]
null
null
null
src/fade2d/Fade2D.cpp
Gigi1237/Bounce
6e674dd7babda0192b930cc532f692c75219d1fd
[ "MIT" ]
2
2015-02-11T02:46:15.000Z
2015-02-26T14:41:30.000Z
src/fade2d/Fade2D.cpp
Gigi1237/Bounce
6e674dd7babda0192b930cc532f692c75219d1fd
[ "MIT" ]
null
null
null
#include "internal.h" /// /// Constructor for Fade2D /// /// @param resX Diagonal resolution of the desired window /// @param resY Vertical resolution of the desired window /// @param name Name of the desired window /// Fade2D::Fade2D(int resX, int resY, const char* name){ //Start GL context and open windows if (!glfwInit()) { fprintf(stderr, "ERROR: could not start GLFW3\n"); exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 16); window = glfwCreateWindow(resX, resY, name, NULL, NULL); if(window == NULL) { std::cerr << "Failed to open GLFW window. Are your drivers up-to-date ?" << std::endl; glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); if(!glfwGetCurrentContext()) { std::cerr << "Couldn't create OpenGL context" << std::endl; exit(EXIT_FAILURE); } addClassKeyHandler(this); glewExperimental = GL_TRUE; //glewInit(); GLenum err = glewInit(); if (err != GLEW_OK) std::cout << "ERROR 1: " << glewGetErrorString(err); //exit(1); // or handle the error in a nicer way if (!GLEW_VERSION_2_1) // check that the machine supports the 2.1 API. std::cout << "ERROR 2: " << glewGetErrorString(err); //exit(1); // or handle the error in a nicer way glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_MULTISAMPLE); //std::cout << std::endl << "GLError: " << gluErrorString(glGetError()) << std::endl; ShaderHandler::addProgram(); ShaderHandler::bindProgram(ShaderHandler::addShader(ShaderHandler::vertex, SHADERPATH"vertexShader.txt"), ShaderHandler::addShader(ShaderHandler::fragment, SHADERPATH"fragmentShader.txt")); ShaderHandler::useProgram(); glUniformMatrix4fv( glGetUniformLocation(ShaderHandler::getProgram(), "proj"), 1, GL_FALSE, glm::value_ptr(glm::ortho(0.f, (float)resX, (float)resY, 0.f, 1.f, -1.f))); this->genBaseObject(); this->resX = resX; this->resY = resY; } /// /// Checks if the window should close /// bool Fade2D::windowShouldClose() { glfwPollEvents(); return !glfwWindowShouldClose(window); } /// /// Swaps back and front buffers, must be done every scene after rendering /// void Fade2D::swapBuffer(){ glfwSwapBuffers(window); } /// /// Prepares the scene for rendering using default color /// void Fade2D::prepareScene(){ glClearColor(0.5, 0.5, 0.5, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } /// /// Prepares scene for rendering using a custom color /// void Fade2D::prepareScene(float R, float G, float B){ glClearColor(R, G, B, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } /// Interface for creating an object of IEntity /// /// @param xLen Lenght of the Entity /// @param yLen Height of the Entity /// @param xPos Horizontal position of the Entity /// @param yPos Vertical position of the Entiy /// IEntity* Fade2D::newEntity(float xLen, float yLen, float xPos, float yPos, std::string texturePath, float angle){ return new Entity(xLen, yLen, xPos, yPos, texturePath, this, angle); } void Fade2D::draw(){ glBindVertexArray(base_vao); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } void Fade2D::genBaseObject(){ glGenBuffers(1, &base_vbo); glGenVertexArrays(1, &base_vao); glBindVertexArray(base_vao); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, base_vbo); //GLfloat verteces[] = { // 0.f, 1.f, 0.f, // 0.f, 0.f, 0.f, // 1.f, 1.f, 0.f, // 1.f, 0.f, 0.f //}; GLfloat verteces[] = { -0.5f, 0.5f, 0.f, -0.5f, -0.5f, 0.f, 0.5f, 0.5f, 0.f, 0.5f, -0.5f, 0.f }; glBufferData(GL_ARRAY_BUFFER, sizeof(verteces), verteces, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(0); } int* Fade2D::getWindowSize() { static int res[] = { resX, resY }; return res; } void Fade2D::setKeyPressHandler(letters letter, keyHandler handler) { keyHandlers.push_back(keyHandlerFunc(letter, handler)); } void Fade2D::classKeyHandler(int keyPressed, int action) { for (auto& funcsAndKeus : keyHandlers) { if (keyPressed == funcsAndKeus.key) funcsAndKeus.func(action); } } /// Interface for creating a Fade2D object /// /// @param resX Horizontal resolution /// @param resY Vertical resolution /// @param name Name of the window /// IFade2D* new_IFade2d(int resX, int resY, const char* name){ return new Fade2D(resX, resY, name); }
25.988764
190
0.693039
[ "object" ]
35b5c7c448032b4a8211512e671ad059dd6226c6
1,139
cpp
C++
Contests/Codeforces/div2/573/a.cpp
rodrigoAMF7/Notebook---Maratonas
06b38197a042bfbd27b20f707493e0a19fda7234
[ "MIT" ]
4
2019-01-25T21:22:55.000Z
2019-03-20T18:04:01.000Z
Contests/Codeforces/div2/573/a.cpp
rodrigoAMF/competitive-programming-notebook
06b38197a042bfbd27b20f707493e0a19fda7234
[ "MIT" ]
null
null
null
Contests/Codeforces/div2/573/a.cpp
rodrigoAMF/competitive-programming-notebook
06b38197a042bfbd27b20f707493e0a19fda7234
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define MOD 1000000007 #define INF 0x3f3f3f3f #define INFLL 0x3f3f3f3f3f3f3f3f #define EPS 1e-9 #define PI 3.141592653589793238462643383279502884 #define pb push_back #define pf push_front #define fi first #define se second #define mp make_pair #define sz (x) int(x.size()) #define all (x) x.begin(), x.end() #define mset (x, y) memset(&x, (y), sizeof(x)) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef unsigned int uint; typedef vector<int> vi; typedef pair<int , int> ii; char verificaCategoria(int n){ if(n%4 == 1){ return 'A'; }else if(n%4 == 3){ return 'B'; }else if(n%4 == 2){ return 'C'; }else{ return 'D'; } } int main(){ ios::sync_with_stdio(false);cin.tie(NULL); //\n int x; vector<pair<char, int> > categorias; cin >> x; categorias.pb(mp(verificaCategoria(x), 0)); categorias.pb(mp(verificaCategoria(x+1), 1)); categorias.pb(mp(verificaCategoria(x+2), 2)); sort(categorias.rbegin(), categorias.rend()); cout << categorias[2].se << " " << categorias[2].fi << "\n"; return 0; }
20.339286
64
0.658472
[ "vector" ]
35bdee494197e4724d5f8ca415a5cd548bae3bac
8,314
cpp
C++
main.cpp
leewz/xmlparse
16d7bf9cbd14f5093668795cd144c9e684cce651
[ "MIT" ]
null
null
null
main.cpp
leewz/xmlparse
16d7bf9cbd14f5093668795cd144c9e684cce651
[ "MIT" ]
null
null
null
main.cpp
leewz/xmlparse
16d7bf9cbd14f5093668795cd144c9e684cce651
[ "MIT" ]
null
null
null
//third attempt //just read EVERYTHING into a buffer and then deal with it later. //ugh, there are attrvals with leading whitespace. whyyy #include<map> #include<set> #include<vector> #include<functional> #include<iostream> #include<fstream> #include<cassert> #include<cstdlib> #define private public using namespace std; typedef char const* cstr; //pointer string struct pstr{ cstr b,e; //beginning, end of string operator string() const{ return string(b,e); } //why am i writing iterators for this cstr const begin() const{ return b; } cstr const end() const{ return e; } }; class node{ private: static size_t ncount; static size_t const PSIZE; static vector<std::vector<char>> pool_list; public: static void * operator new(size_t sz); static void operator delete(void*p); //don't allow arrays static void * operator new[](size_t sz)=delete; static void operator delete[](void*p)=delete; virtual ~node()=0; }; node::~node(){} //manual memory management saves about a second /* 536367 tag 358189 internal 318020 content 536367*sizeof(tnode)+358189*(sizeof(inode - sizeof(tnode)))+318020*sizeof(pnode) */ size_t node::ncount = 0; //number of nodes created size_t const node::PSIZE = 0x20000000; std::vector<std::vector<char>> node::pool_list(1,vector<char>(PSIZE)); void * node::operator new(size_t sz){ static auto free = pool_list.back().begin(); //index of free pool static auto end = pool_list.back().end(); ncount++; free+=sz; //expand pool if necessary assert(free<=end); // if(free > end){ // std::cerr<<"Expanding mempool\n"; // pool_list.emplace_back(PSIZE); //add another pool // free = pool_list.back().begin(); // end = pool_list.back().end(); // free+=sz; // } return (void*)&*(free-sz); } void node::operator delete(void*p){ static size_t ndel = 0;//number of deleted nodes if(++ndel==ncount){ //delete everything pool_list.clear(); } } //static char const SPACES[]=" \r\n\t"; static char const SPACES = ' '; //tag node class tnode: public node{ private: pstr tag;//the name of the tag static const int MAX_ATTR = 15; pstr keys[MAX_ATTR], vals[MAX_ATTR]; int attrc;//attribute count public: tnode(pstr const); }; //assume only one space //assumes no trailing space tnode::tnode(pstr const str) :attrc(0) { register cstr p, q = str.b, r, s, e=str.e; while(++q<e&&*q!=' '); //right now q is at a space tag = {str.b,q}; while(++q<e){ //advance p=q; while(++q<e&&*q != '='); if(q>=e) //did not find a next attr return; if(attrc>=MAX_ATTR) throw "out of bounds"; r=q+1; s=r; switch(*r){ case '\'': case '"': while(*++s!=*r); keys[attrc] = {p, q}; vals[attrc] = {r+1, s}; attrc++; q=s+1; break; default: cerr<<"they DO exist!\n"; while(++s<e && *s!=' '); keys[attrc] = {p, q}; vals[attrc] = {r, s}; attrc++; q=s; break; } } } //internal node //like <p>content</p> //can have children struct inode:public tnode{ //private: vector<node*>children; public: inode(pstr const); virtual ~inode(); void add(node* n); //delete these operators for now inode(tnode const&) = delete; inode& operator=(tnode const&) = delete; //move should be fine... inode& operator=(tnode &&) = delete; friend class parser; }; inline inode::inode(pstr const str):tnode(str){} inode::~inode(){ //needs to be virtual for(auto child:children) delete child; } inline void inode::add(node* n){ children.push_back(n); } class pnode:public node{//plaintext node, also known as "not tagged" private: pstr content; //start and end of string content public: pnode(pstr const str){content = str;} //not translated yet from xml //should also collapse whitespace }; class document{ private: vector<char>buffer; inode head; //dummy head node inode* stack[20];//stack of node depth inode** stackptr; //pointer into the stack inode* root; public: document(document const&) = delete; document& operator=(document const&) = delete; document(string const& fname) :buffer(0x08000000)//128MB should be enough for anything ,head({&buffer[0],&buffer[0]})//at least it's a valid memory location ,stackptr(stack) { ifstream file(fname); if(!file){ throw "Failure to open "+fname; } file.read(&buffer[0], buffer.size()); //if the buffer filled up, quit if(file.gcount()>=buffer.size()){ cerr<<"buffer full\n"; exit(1); } buffer.resize(file.gcount()); //to keep size *stackptr++ = &head; //put the dummy on the stack cstr left=&buffer[0]-1; cstr right=left; cstr const bufend = left+buffer.size(); //slightly smaller while(true){ //find < while(*++left != '<' && left < bufend); if(left>=bufend) break; //add content contentwise(right+1, left); //find > right = left; while(*++right != '>');// && right<bufend); //add tag tagwise(left+1, right); } //find the root for(auto p : head.children){ root = dynamic_cast<inode*>(p); if(root) break; } file.close(); //just in case } void tagwise(cstr b, cstr e){ if(*b=='/')//end tag --stackptr; else if(e[-1]=='/'){ //empty tag stackptr[-1]->add(new tnode({b,e-1})); //add without the / }else{//it's the start of an internal node inode* temp = new inode({b,e}); stackptr[-1]->add(temp); *stackptr++ = temp; } } void contentwise(cstr b, cstr e){ if(b>=e)return; char * i = const_cast<char*>(b); //true if the last character was a whitespace bool whitespaced = false; //assume empty first bool empty = true; //don't print space if empty //cleanup for(auto p=b;p<e;p++){ switch(*p){ case ' ': case '\t': case '\n': case '\r': whitespaced=true;break; default: if(whitespaced && !empty){ *i++ = ' '; whitespaced=false; } *i++ = *p; empty = false; } } *i=0; if(b<i) stackptr[-1]->add(new pnode({b,i})); } }; void traverse(inode* cur, function<void(inode*, node*)> f){ for(node*p:cur->children){ f(cur,p); auto n = dynamic_cast<inode*>(p); if(n)//if it's an internal node traverse(n,f); } } void nodetypes(inode*root){ int internal=0, tag=0, content=0; traverse(root, [&](inode*parent, node*p){ if(dynamic_cast<tnode*>(p))tag++; if(dynamic_cast<inode*>(p))internal++; if(dynamic_cast<pnode*>(p))content++; }); cout <<tag<<"\ttag\n" <<internal<<"\tinternal\n" <<content<<"\tcontent\n" ; } void instances(inode*root){ map<string, int> m; traverse(root, [&](inode*parent, node*p){ inode* p2 = dynamic_cast<inode*>(p); if(p2){ m[p2->tag]++; } }); int sum=0; for(auto kv:m){ cout<<kv.second<<" "<<kv.first<<endl; sum+=kv.second; } cout<<sum<<endl; } //want to see the attributes void attrtypes(inode* root){ //tag, attribute, values map<string, map<string, map<string,int>>> m; traverse(root, [&](inode *parent, node *n){ tnode* n2 = dynamic_cast<tnode*>(n); if(n2){ auto& blargh = m[n2->tag]; //list of key/val pairs for that attribute for(int i = 0; i < n2->attrc; i++){ blargh[n2->keys[i]][n2->vals[i]]++; } } }); for(auto const & tag:m){ cout<<tag.first<<endl; for(auto const& key: tag.second){ cout<<'\t'<<key.first<<endl; for(auto const& val : key.second){ cout<<"\t\t"<<val.first<<"\t\t\t"<<val.second<<endl; } } } } //what kind of children can each type of child have? void followers(inode* root){ map<string,map<string,int>> blargh; map<inode*, int> ptrset; traverse(root, [&](inode* parent, node*p){ if(ptrset[parent]++) return; auto & bleh = blargh[parent->tag]; for(auto child:parent->children){ tnode *const p = dynamic_cast<tnode * const>(child); if(p) bleh[p->tag]++; else bleh["<text>"]++; } }); //print map for(auto const& pair:blargh){ cout<<pair.first<<endl; for(auto child : pair.second) cout<<'\t'<<child.first<<"\t\t\t"<<child.second<<endl; } } int main(){ string fname = string(std::getenv("APPDATA"))+"/CBLoader/combined.dnd40"; cerr<<"Loading (this may take up to a minute)..."<<endl; document doc(fname); cerr<<"Loaded"<<endl; // nodetypes(doc.root); // instances(doc.root); // attrtypes(doc.root); // followers(doc.root); return 0; }
20.033735
80
0.619918
[ "vector" ]
35c57d8249f0478f41a5b9aae34eb82693376789
4,115
cpp
C++
TEngine/src/core/Transform.cpp
Twixuss/TEngine
024f4208673410bfe9de9aeee4ea5c87facad319
[ "Apache-2.0" ]
null
null
null
TEngine/src/core/Transform.cpp
Twixuss/TEngine
024f4208673410bfe9de9aeee4ea5c87facad319
[ "Apache-2.0" ]
null
null
null
TEngine/src/core/Transform.cpp
Twixuss/TEngine
024f4208673410bfe9de9aeee4ea5c87facad319
[ "Apache-2.0" ]
null
null
null
#include "Transform.h" namespace TEngine { Transform::Transform(float3 pos, float3 rot, float3 scl, Transform *parent) : m_Position(pos.x, pos.y, pos.z, 0), m_Rotation(rot.x, rot.y, rot.z, 0), m_Scaling(scl.x, scl.y, scl.z, 0), m_Dirty(true), m_Parent(parent) { } void Transform::SetPosition(float x, float y, float z) { SetPosition(XMVectorSet(x, y, z, 0)); } void Transform::SetRotation(float x, float y, float z) { SetRotation(XMVectorSet(x, y, z, 0)); } void Transform::SetScaling(float x, float y, float z) { SetScaling(XMVectorSet(x, y, z, 0)); } void Transform::Translate(float x, float y, float z) { Translate(XMVectorSet(x, y, z, 0)); } void Transform::TranslateRelative(float x, float y, float z) { TranslateRelative(XMVectorSet(x, y, z, 0)); } void Transform::Rotate(float x, float y, float z) { Rotate(XMVectorSet(x, y, z, 0)); } void Transform::SetPosition(float3 v) { SetPosition(v.x, v.y, v.z); } void Transform::SetRotation(float3 v) { SetRotation(v.x, v.y, v.z); } void Transform::SetScaling(float3 v) { SetScaling(v.x, v.y, v.z); } void Transform::Translate(float3 v) { Translate(v.x, v.y, v.z); } void Transform::TranslateRelative(float3 v) { TranslateRelative(v.x, v.y, v.z); } void Transform::Rotate(float3 v) { Rotate(v.x, v.y, v.z); } void Transform::SetParent(Transform* p) { m_Parent = p; p->m_Children.AddInPlace(this); } Transform* Transform::GetParent() const { return m_Parent; } float4 Transform::GetPosition() const { if (m_Parent) { return XMVectorAdd(m_Parent->GetPosition().xmv, XMVector4Transform(m_Position.xmv, XMMatrixRotationRollPitchYawFromVector(m_Parent->GetRotation().xmv))); } return m_Position; } float4 Transform::GetRotation() const { if (m_Parent) { return m_Rotation + m_Parent->GetRotation(); } return m_Rotation; } float4 Transform::GetScaling() const { if (m_Parent) { return m_Scaling * m_Parent->GetScaling(); } return m_Scaling; } float4 Transform::GetLocalPosition() const { return m_Position; } float4 Transform::GetLocalRotation() const { return m_Rotation; } float4 Transform::GetLocalScaling() const { return m_Scaling; } float4 Transform::GetRightDir() const { return XMVector4Transform(XMVectorSet(1, 0, 0, 0), XMMatrixRotationRollPitchYawFromVector(GetRotation().xmv)); } float4 Transform::GetUpDir() const { return XMVector4Transform(XMVectorSet(0, 1, 0, 0), XMMatrixRotationRollPitchYawFromVector(GetRotation().xmv)); } float4 Transform::GetForwardDir() const { return XMVector4Transform(XMVectorSet(0, 0, 1, 0), XMMatrixRotationRollPitchYawFromVector(GetRotation().xmv)); } void Transform::SetPosition(const float4 &v) { if (v == m_Position) return; m_Position = v; BecomeDirty(); } void Transform::SetRotation(const float4 &v) { if (v == m_Rotation) return; m_Rotation = v; BecomeDirty(); } void Transform::SetScaling(const float4 &v) { if (v == m_Scaling) return; m_Scaling = v; BecomeDirty(); } void Transform::Translate(const float4 &v) { if (v == float4::Zero()) return; m_Position += v; BecomeDirty(); } void Transform::TranslateRelative(const float4 &v) { if (v == float4::Zero()) return; m_Position += XMVector4Transform(v.xmv, XMMatrixRotationRollPitchYawFromVector(m_Rotation.xmv)); BecomeDirty(); } void Transform::Rotate(const float4 &v) { if (v == float4::Zero()) return; m_Rotation += v; BecomeDirty(); } void Transform::BecomeDirty() { m_Dirty = true; for (auto& c : m_Children) { c->BecomeDirty(); } } }
24.640719
162
0.599514
[ "transform" ]
35c67060efad004a527f5e8a2f07d84ffb5f7747
1,095
cpp
C++
Online Judges/LeetCode/30-day-leetcoding-challenge/Week-5/Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
4
2017-02-20T17:41:14.000Z
2019-07-15T14:15:34.000Z
Online Judges/LeetCode/30-day-leetcoding-challenge/Week-5/Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
Online Judges/LeetCode/30-day-leetcoding-challenge/Week-5/Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool check(TreeNode *root, vector<int> &arr, int sz) { if (sz == arr.size()) return 0; int ret = 0; if (root->val == arr[sz]) { if (root->left) { ret |= check(root->left, arr, sz + 1); } if (root->right) { ret |= check(root->right, arr, sz + 1); } if (root->left == nullptr && root->right == nullptr) { if (sz == arr.size() - 1) ret = 1; } } return ret; } bool isValidSequence(TreeNode *root, vector<int> &arr) { return check(root, arr, 0); } };
26.071429
93
0.445662
[ "vector" ]
35cff66cfd92d1bde5398e08c9dfc40b864259c5
6,217
cpp
C++
HDU/4266.cpp
CodingYue/acm-icpc
667596efae998f5480819870714c37e9af0740eb
[ "Unlicense" ]
1
2015-11-03T09:31:07.000Z
2015-11-03T09:31:07.000Z
HDU/4266.cpp
CodingYue/acm-icpc
667596efae998f5480819870714c37e9af0740eb
[ "Unlicense" ]
null
null
null
HDU/4266.cpp
CodingYue/acm-icpc
667596efae998f5480819870714c37e9af0740eb
[ "Unlicense" ]
null
null
null
// File Name: 3DHull.cpp // Author: YangYue // Created Time: Fri May 17 10:00:59 2013 //headers #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cstring> #include <cmath> #include <ctime> #include <string> #include <queue> #include <set> #include <map> #include <iostream> #include <vector> using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> PII; typedef pair<double,double> PDD; typedef pair<LL, LL>PLL; typedef pair<LL,int>PLI; #define lch(n) ((n<<1)) #define rch(n) ((n<<1)+1) #define lowbit(i) (i&-i) #define sqr(x) ((x)*(x)) #define fi first #define se second #define MP make_pair #define PB push_back const int MaxN = 1005; const double eps = 1e-7; const double DINF = 1e100; const int INF = 1000000006; const LL LINF = 1000000000000000005ll; int n; struct Point3D { double x, y, z; Point3D(){} Point3D(double x, double y, double z) : x(x), y(y), z(z) {} Point3D operator -(const Point3D &b) { return Point3D(x - b.x, y - b.y, z - b.z); } Point3D operator /(const double &t) { return Point3D(x / t, y / t, z / t); } Point3D operator +(const double &t) { return Point3D(x + t, y + t, z + t); } Point3D operator +(const Point3D &b) { return Point3D(x + b.x, y + b.y, z + b.z); } Point3D operator *(const double &t) { return Point3D(x * t, y * t, z * t); } double operator %(const Point3D &b) { return x * b.x + y * b.y + z * b.z; } Point3D operator *(const Point3D &b) { double i = y * b.z - b.y * z; double j = z * b.x - x * b.z; double k = x * b.y - b.x * y; return Point3D(i, j, k); } double len() { return sqrt( sqr(x) + sqr(y) + sqr(z) ); } void init() { scanf("%lf%lf%lf",&x,&y,&z); } }; struct Plane { int a, b, c; bool ok; }; Point3D xcross(Point3D a, Point3D b, Point3D c) { return (b - a) * (c - a); } struct Hull3D { int n, tricnt; int vis[MaxN][MaxN]; Plane tri[MaxN]; Point3D Ply[MaxN]; void rebuild(int n_) { n = n_; tricnt = 0; memset(vis, 0, sizeof vis); } double area(Point3D a, Point3D b, Point3D c) { return ((b - a) * (c - a)).len(); } double volume(Point3D a, Point3D b, Point3D c, Point3D d) { return (b - a) * (c - a) % (d - a); } double PtoPlane(Point3D &P, Plane f) { Point3D m = Ply[f.b] - Ply[f.a]; Point3D n = Ply[f.c] - Ply[f.a]; Point3D t = P - Ply[f.a]; return m * n % t; } void deal(int p, int a, int b) { int f = vis[a][b]; Plane add; if (tri[f].ok) { if ((PtoPlane(Ply[p], tri[f])) > eps) dfs(p, f); else { add.a = b; add.b = a; add.c = p; add.ok = 1; vis[p][b] = vis[a][p] = vis[b][a] = tricnt; tri[tricnt++] = add; } } } void dfs(int p, int cnt) { tri[cnt].ok = 0; deal(p, tri[cnt].b, tri[cnt].a); deal(p, tri[cnt].c, tri[cnt].b); deal(p, tri[cnt].a, tri[cnt].c); } bool same(int s, int e) { Point3D a = Ply[tri[s].a]; Point3D b = Ply[tri[s].b]; Point3D c = Ply[tri[s].c]; return fabs(volume(a, b, c, Ply[tri[e].a])) < eps && fabs(volume(a, b, c, Ply[tri[e].b])) < eps && fabs(volume(a, b, c, Ply[tri[e].c])) < eps; } void construct() { tricnt = 0; if (n < 4) return; bool tmp = 1; for (int i = 1; i < n; ++i) { if ((Ply[0] - Ply[i]).len() > eps) { swap(Ply[1], Ply[i]); tmp = 0; break; } } if (tmp) return; tmp = 1; for (int i = 2; i < n; ++i) { if (((Ply[0] - Ply[1]) * (Ply[1] - Ply[i])).len() > eps) { swap(Ply[2], Ply[i]); tmp = 0; break; } } if (tmp) return; tmp = 1; for (int i = 3; i < n; ++i) { if (fabs((Ply[0] - Ply[1]) * (Ply[1] - Ply[2]) % (Ply[0] - Ply[i])) > eps) { swap(Ply[3], Ply[i]); tmp = 0; break; } } if (tmp) return; Plane add; for (int i = 0; i < 4; ++i) { add.a = (i + 1) % 4; add.b = (i + 2) % 4; add.c = (i + 3) % 4; add.ok = 1; if (PtoPlane(Ply[i], add) > 0) swap(add.b, add.c); vis[add.a][add.b] = vis[add.b][add.c] = vis[add.c][add.a] = tricnt; tri[tricnt++] = add; } for (int i = 4; i < n; ++i) { for (int j = 0; j < tricnt; ++j) { if (tri[j].ok && (PtoPlane(Ply[i], tri[j])) > eps) { dfs(i, j); break; } } } int cnt = tricnt; tricnt = 0; for (int i = 0; i < cnt; ++i) { if (tri[i].ok) { tri[tricnt++] = tri[i]; } } } double Mindis(Point3D ask) { double res = 1e100; for (int i = 0; i < tricnt; ++i) { Point3D fvect = xcross(Ply[tri[i].a], Ply[tri[i].b], Ply[tri[i].c]); fvect = fvect / fvect.len(); double cur = fvect % (ask - Ply[tri[i].a]); res = min(res, fabs(cur)); } return res; } } Hull; int main() { //freopen("3DHull.in","r",stdin); while (1) { cin >> n; if (n == 0) break; Hull.rebuild(n); for (int i = 0; i < n; ++i) { Hull.Ply[i].init(); } Hull.construct(); int Q; cin >> Q; while (Q--) { Point3D ask; ask.init(); printf("%.4lf\n", Hull.Mindis(ask)); } } return 0; } // hehe ~
27.267544
89
0.421103
[ "vector" ]
35d18868b903b5aba6d6054046153c785028d223
2,058
cpp
C++
UESTC/2526.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
UESTC/2526.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
UESTC/2526.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <bits/stdc++.h> #define MAXN 200005 using namespace std; const int C=50; const long long msk=(1LL<<(C+1))-1; int n,m,T=1,rt,in[MAXN],out[MAXN],lazy[1<<19]; long long x[1<<19]; vector <int> g[MAXN],v; int cache[C+1]; unordered_map <int,int> mp; inline void add(int x,int y) { if (!x) v.push_back(y); else g[x].push_back(y); return ; } void dfs(int x) { in[x]=T++; for (int v:g[x]) dfs(v); out[x]=T; return ; } inline void color(int u,int v) { x[u]=1LL<<v;lazy[u]=v; return ; } inline void PushDown(int u) { if (!~lazy[u]) return; color(u<<1,lazy[u]);color(u<<1|1,lazy[u]);lazy[u]=-1; return ; } inline void BuildTree(int u,int l,int r) { lazy[u]=-1;x[u]=1; if (l+1==r) return; int m=l+r>>1;BuildTree(u<<1,l,m);BuildTree(u<<1|1,m,r); return ; } inline void modify(int u,int l,int r,int v,int pl,int pr) { if (pl==l&&pr==r){color(u,v);return ;} int m=pl+pr>>1;PushDown(u); if (r<=m) modify(u<<1,l,r,v,pl,m); else if (m<=l) modify(u<<1|1,l,r,v,m,pr); else { modify(u<<1,l,m,v,pl,m); modify(u<<1|1,m,r,v,m,pr); } x[u]=x[u<<1]|x[u<<1|1]; return ; } inline long long query(int u,int l,int r,int pl,int pr) { if (pl==l&&pr==r) return x[u]; int m=pl+pr>>1;PushDown(u); if (r<=m) return query(u<<1,l,r,pl,m); else if (m<=l) return query(u<<1|1,l,r,m,pr); else return query(u<<1,l,m,pl,m)|query(u<<1|1,m,r,m,pr); } inline int getLowestZero(long long x) { long long s=x^msk; if (!s) return 0; return __builtin_ctzll(s); } inline int assignColor(int c) { int col=mp[c]; if (cache[col]!=c) { col=getLowestZero(x[1]); cache[col]=c;mp[c]=col; } return col; } int main() { memset(cache,-1,sizeof cache); cache[0]=0; scanf("%d %d",&n,&m); for (int i=1,f;i<=n;i++) scanf("%d",&f),add(f,i); for (int rt:v) dfs(rt); BuildTree(1,1,n+1); for (int i=1;i<=m;i++) { int o,p,c; scanf("%d",&o); if (o==1) { scanf("%d %d",&p,&c); modify(1,in[p],out[p],assignColor(c),1,n+1); } else { scanf("%d",&p); printf("%d\n",__builtin_popcountll(query(1,in[p],out[p],1,n+1))); } } return 0; }
17.589744
68
0.575802
[ "vector" ]
35e28cba6fb6228bab50f9613de07b0df6cccda4
18,385
cpp
C++
src/motioncore/protocols/data_management/unsimdify_gate.cpp
tompetersen/MOTION
7a985f88075c10ecfa3071572d7fd23871740143
[ "MIT" ]
45
2020-09-21T12:42:04.000Z
2022-03-26T13:19:31.000Z
src/motioncore/protocols/data_management/unsimdify_gate.cpp
tompetersen/MOTION
7a985f88075c10ecfa3071572d7fd23871740143
[ "MIT" ]
17
2021-04-17T04:54:55.000Z
2022-03-31T15:05:51.000Z
src/motioncore/protocols/data_management/unsimdify_gate.cpp
tompetersen/MOTION
7a985f88075c10ecfa3071572d7fd23871740143
[ "MIT" ]
23
2020-12-14T14:17:48.000Z
2022-03-29T18:50:12.000Z
// MIT License // // Copyright (c) 2021 Oleksandr Tkachenko // Cryptography and Privacy Engineering Group (ENCRYPTO) // TU Darmstadt, Germany // // 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 "unsimdify_gate.h" #include "base/configuration.h" #include "base/register.h" #include "protocols/arithmetic_gmw/arithmetic_gmw_share.h" #include "protocols/arithmetic_gmw/arithmetic_gmw_wire.h" #include "protocols/bmr/bmr_share.h" #include "protocols/bmr/bmr_wire.h" #include "protocols/boolean_gmw/boolean_gmw_share.h" #include "protocols/boolean_gmw/boolean_gmw_wire.h" #include "protocols/constant/constant_share.h" #include "protocols/constant/constant_wire.h" #include "protocols/share.h" #include "utility/constants.h" #include "utility/logger.h" namespace encrypto::motion { UnsimdifyGate::UnsimdifyGate(const SharePointer& parent) : OneGate(parent->GetBackend()) { parent_ = parent->GetWires(); // Initialize this gate. requires_online_interaction_ = false; gate_type_ = GateType::kNonInteractive; gate_id_ = GetRegister().NextGateId(); if constexpr (kDebug) { if (parent_.empty()) { throw std::invalid_argument( fmt::format("Input share in UnsimdifyGate#{} has no wires", gate_id_)); } } const std::size_t number_of_simd{parent_[0]->GetNumberOfSimdValues()}; const MpcProtocol protocol{parent_[0]->GetProtocol()}; if constexpr (kDebug) { for (std::size_t i = 1; i < parent_.size(); ++i) { if (parent_[i]->GetNumberOfSimdValues() != number_of_simd) { throw std::invalid_argument(fmt::format( "Input wires have different numbers of SIMD values in UnsimdifyGate#{}", GetId())); } if (parent_[i]->GetProtocol() != protocol) { throw std::invalid_argument( fmt::format("Input wires have different protocols in UnsimdifyGate#{}", GetId())); } } if ((parent_[0]->GetCircuitType() == CircuitType::kArithmetic) && (parent_.size() != 1)) { throw std::invalid_argument( fmt::format("Got {} arithmetic input wires in UnsimdifyGate#{}, only one is allowed", parent_.size(), GetId())); } } // Register this gate as waiting for the wires. for (auto& wire : parent_) { RegisterWaitingFor(wire->GetWireId()); wire->RegisterWaitingGate(gate_id_); } // Register output wires. const std::size_t input_number_of_simd_values{parent_[0]->GetNumberOfSimdValues()}; const std::size_t number_of_output_wires{parent_.size() * input_number_of_simd_values}; output_wires_.reserve(number_of_output_wires); for (size_t i = 0; i < number_of_output_wires; ++i) { switch (protocol) { case encrypto::motion::MpcProtocol::kArithmeticConstant: { switch (parent_[0]->GetBitLength()) { case 8: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::ConstantArithmeticWire<std::uint8_t>>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } case 16: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::ConstantArithmeticWire<std::uint16_t>>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } case 32: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::ConstantArithmeticWire<std::uint32_t>>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } case 64: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::ConstantArithmeticWire<std::uint64_t>>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } default: throw std::invalid_argument( fmt::format("Trying to create a ConstantArithmeticShare with invalid bitlength: {}", parent_[i]->GetBitLength())); } break; } case encrypto::motion::MpcProtocol::kArithmeticGmw: { switch (parent_[0]->GetBitLength()) { case 8: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::arithmetic_gmw::Wire<std::uint8_t>>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } case 16: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::arithmetic_gmw::Wire<std::uint16_t>>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } case 32: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::arithmetic_gmw::Wire<std::uint32_t>>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } case 64: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::arithmetic_gmw::Wire<std::uint64_t>>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } default: throw std::invalid_argument(fmt::format( "Trying to create a proto::arithmetic_gmw::Share with invalid bitlength: {}", parent_[i]->GetBitLength())); } break; } case encrypto::motion::MpcProtocol::kBmr: { auto& w = output_wires_.emplace_back( std::static_pointer_cast<Wire>(std::make_shared<proto::bmr::Wire>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } case encrypto::motion::MpcProtocol::kBooleanConstant: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::ConstantBooleanWire>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } case encrypto::motion::MpcProtocol::kBooleanGmw: { auto& w = output_wires_.emplace_back(std::static_pointer_cast<Wire>( std::make_shared<proto::boolean_gmw::Wire>(backend_, 1))); assert(w); GetRegister().RegisterNextWire(w); break; } default: throw std::invalid_argument(fmt::format("Unrecognized MpcProtocol in UnsimdifyGate")); } } } void UnsimdifyGate::EvaluateSetup() { if constexpr (kDebug) { GetLogger().LogDebug( fmt::format("Nothing to do in the setup phase of UnsimdifyGate with id#{}", gate_id_)); } const std::size_t input_number_of_simd{parent_[0]->GetNumberOfSimdValues()}; if (parent_[0]->GetProtocol() == MpcProtocol::kBmr) { for (std::size_t i = 0; i < parent_.size(); ++i) { auto in = std::dynamic_pointer_cast<proto::bmr::Wire>(parent_[i]); assert(in); in->GetSetupReadyCondition()->Wait(); for (std::size_t j = 0; j < input_number_of_simd; ++j) { auto out = std::dynamic_pointer_cast<proto::bmr::Wire>(output_wires_[j * parent_.size() + i]); assert(out); out->GetMutablePermutationBits() = in->GetPermutationBits().Subset(j, j + 1); out->GetMutableSecretKeys().resize(1); out->GetMutableSecretKeys()[0] = in->GetSecretKeys()[j]; out->SetSetupIsReady(); } } } SetSetupIsReady(); GetRegister().IncrementEvaluatedGatesSetupCounter(); } template <typename WireType> void ArithmeticUnsimdifyOnlineImplementation(WirePointer parent_wire, std::span<WirePointer> output_wires) { auto in = std::dynamic_pointer_cast<WireType>(parent_wire); assert(in); for (std::size_t i = 0; i < output_wires.size(); ++i) { auto out = std::dynamic_pointer_cast<WireType>(output_wires[i]); assert(out); out->GetMutableValues().push_back(in->GetValues()[i]); } } template <typename T> void ArithmeticGmwUnsimdifyOnline(WirePointer parent_wire, std::span<WirePointer> output_wires) { ArithmeticUnsimdifyOnlineImplementation<proto::arithmetic_gmw::Wire<T>>(parent_wire, output_wires); } template <typename T> void ArithmeticConstantUnsimdifyOnline(WirePointer parent_wire, std::span<WirePointer> output_wires) { ArithmeticUnsimdifyOnlineImplementation<proto::ConstantArithmeticWire<T>>(parent_wire, output_wires); } void UnsimdifyGate::EvaluateOnline() { WaitSetup(); if constexpr (kDebug) { GetLogger().LogDebug( fmt::format("Start evaluating online phase of UnsimdifyGate with id#{}", gate_id_)); } for (auto& wire : parent_) { wire->GetIsReadyCondition().Wait(); } const encrypto::motion::MpcProtocol protocol{parent_[0]->GetProtocol()}; const std::size_t input_numer_of_simd{parent_[0]->GetNumberOfSimdValues()}; switch (protocol) { case encrypto::motion::MpcProtocol::kArithmeticConstant: { switch (parent_[0]->GetBitLength()) { case 8: { ArithmeticConstantUnsimdifyOnline<std::uint8_t>(parent_[0], output_wires_); break; } case 16: { ArithmeticConstantUnsimdifyOnline<std::uint16_t>(parent_[0], output_wires_); break; } case 32: { ArithmeticConstantUnsimdifyOnline<std::uint32_t>(parent_[0], output_wires_); break; } case 64: { ArithmeticConstantUnsimdifyOnline<std::uint64_t>(parent_[0], output_wires_); break; } default: throw std::invalid_argument( fmt::format("Trying to create a ConstantArithmeticShare with invalid bitlength: {}", output_wires_[0]->GetBitLength())); } break; } case encrypto::motion::MpcProtocol::kArithmeticGmw: { switch (parent_[0]->GetBitLength()) { case 8: { ArithmeticGmwUnsimdifyOnline<std::uint8_t>(parent_[0], output_wires_); break; } case 16: { ArithmeticGmwUnsimdifyOnline<std::uint16_t>(parent_[0], output_wires_); break; } case 32: { ArithmeticGmwUnsimdifyOnline<std::uint32_t>(parent_[0], output_wires_); break; } case 64: { ArithmeticGmwUnsimdifyOnline<std::uint64_t>(parent_[0], output_wires_); break; } default: throw std::invalid_argument(fmt::format( "Trying to create a proto::arithmetic_gmw::Share with invalid bitlength: {}", output_wires_[0]->GetBitLength())); } break; } case encrypto::motion::MpcProtocol::kBmr: { const std::size_t number_of_parties{GetConfiguration().GetNumOfParties()}; for (std::size_t i = 0; i < parent_.size(); ++i) { auto in = std::dynamic_pointer_cast<proto::bmr::Wire>(parent_[i]); assert(in); for (std::size_t j = 0; j < input_numer_of_simd; ++j) { auto out = std::dynamic_pointer_cast<proto::bmr::Wire>(output_wires_[j * parent_.size() + i]); assert(out); out->GetMutablePublicValues() = in->GetPublicValues().Subset(j, j + 1); out->GetMutablePublicKeys().resize(number_of_parties); std::copy_n(in->GetPublicKeys().begin() + j * number_of_parties, number_of_parties, out->GetMutablePublicKeys().begin()); } } break; } case encrypto::motion::MpcProtocol::kBooleanConstant: { for (std::size_t i = 0; i < parent_.size(); ++i) { auto in = std::dynamic_pointer_cast<proto::ConstantBooleanWire>(parent_[i]); assert(in); for (std::size_t j = 0; j < input_numer_of_simd; ++j) { auto out = std::dynamic_pointer_cast<proto::ConstantBooleanWire>( output_wires_[j * parent_.size() + i]); assert(out); out->GetMutableValues() = in->GetValues().Subset(j, j + 1); } } break; } case encrypto::motion::MpcProtocol::kBooleanGmw: { for (std::size_t i = 0; i < parent_.size(); ++i) { auto in = std::dynamic_pointer_cast<proto::boolean_gmw::Wire>(parent_[i]); assert(in); for (std::size_t j = 0; j < input_numer_of_simd; ++j) { auto out = std::dynamic_pointer_cast<proto::boolean_gmw::Wire>( output_wires_[j * parent_.size() + i]); assert(out); out->GetMutableValues() = in->GetValues().Subset(j, j + 1); } } break; } default: throw std::invalid_argument(fmt::format("Unrecognized MpcProtocol in UnsimdifyGate")); } SetOnlineIsReady(); GetRegister().IncrementEvaluatedGatesOnlineCounter(); } std::vector<SharePointer> UnsimdifyGate::GetOutputAsVectorOfShares() { const std::size_t input_number_of_simd = parent_[0]->GetNumberOfSimdValues(); std::vector<encrypto::motion::SharePointer> result(input_number_of_simd); for (std::size_t i = 0; i < input_number_of_simd; ++i) { encrypto::motion::SharePointer share{nullptr}; std::vector<encrypto::motion::WirePointer> output_wires( output_wires_.begin() + parent_.size() * i, output_wires_.begin() + parent_.size() * (i + 1)); const encrypto::motion::MpcProtocol protocol{parent_[0]->GetProtocol()}; switch (protocol) { case encrypto::motion::MpcProtocol::kArithmeticConstant: { switch (parent_[0]->GetBitLength()) { case 8: { auto tmp = std::make_shared<proto::ConstantArithmeticShare<std::uint8_t>>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } case 16: { auto tmp = std::make_shared<proto::ConstantArithmeticShare<std::uint16_t>>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } case 32: { auto tmp = std::make_shared<proto::ConstantArithmeticShare<std::uint32_t>>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } case 64: { auto tmp = std::make_shared<proto::ConstantArithmeticShare<std::uint64_t>>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } default: throw std::invalid_argument( fmt::format("Trying to create a ConstantArithmeticShare with invalid bitlength: {}", output_wires_[0]->GetBitLength())); } break; } case encrypto::motion::MpcProtocol::kArithmeticGmw: { switch (parent_[0]->GetBitLength()) { case 8: { auto tmp = std::make_shared<proto::arithmetic_gmw::Share<std::uint8_t>>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } case 16: { auto tmp = std::make_shared<proto::arithmetic_gmw::Share<std::uint16_t>>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } case 32: { auto tmp = std::make_shared<proto::arithmetic_gmw::Share<std::uint32_t>>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } case 64: { auto tmp = std::make_shared<proto::arithmetic_gmw::Share<std::uint64_t>>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } default: throw std::invalid_argument(fmt::format( "Trying to create a proto::arithmetic_gmw::Share with invalid bitlength: {}", output_wires_[0]->GetBitLength())); } break; } case encrypto::motion::MpcProtocol::kBmr: { auto tmp = std::make_shared<proto::bmr::Share>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } case encrypto::motion::MpcProtocol::kBooleanConstant: { auto tmp = std::make_shared<proto::ConstantBooleanShare>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } case encrypto::motion::MpcProtocol::kBooleanGmw: { auto tmp = std::make_shared<proto::boolean_gmw::Share>(output_wires); assert(tmp); share = std::static_pointer_cast<Share>(tmp); break; } default: throw std::invalid_argument(fmt::format("Unrecognized MpcProtocol in UnsimdifyGate")); } result[i] = std::static_pointer_cast<Share>(share); } return result; } } // namespace encrypto::motion
39.794372
100
0.610661
[ "vector" ]
e301721955ed0e3b2ccbc35c6d652f5281cd3714
3,689
cpp
C++
Project/Engine/Source/Graphics/RenderPipeline.cpp
lcomstive/Graphics-Assessment
bc52f41b31646ca5d2bb20669704db83c4f77361
[ "MIT-0" ]
null
null
null
Project/Engine/Source/Graphics/RenderPipeline.cpp
lcomstive/Graphics-Assessment
bc52f41b31646ca5d2bb20669704db83c4f77361
[ "MIT-0" ]
null
null
null
Project/Engine/Source/Graphics/RenderPipeline.cpp
lcomstive/Graphics-Assessment
bc52f41b31646ca5d2bb20669704db83c4f77361
[ "MIT-0" ]
1
2022-03-23T00:28:52.000Z
2022-03-23T00:28:52.000Z
#include <algorithm> #include <Engine/Application.hpp> #include <Engine/Graphics/Mesh.hpp> #include <Engine/ResourceManager.hpp> #include <Engine/Components/Light.hpp> #include <Engine/Graphics/Renderer.hpp> #include <Engine/Components/Camera.hpp> #include <Engine/Graphics/Framebuffer.hpp> #include <Engine/Services/SceneService.hpp> #include <Engine/Graphics/Passes/Skybox.hpp> #include <Engine/Graphics/RenderPipeline.hpp> #include <Engine/Graphics/Passes/ShadowMap.hpp> using namespace glm; using namespace std; using namespace Engine; using namespace Engine::Services; using namespace Engine::Graphics; using namespace Engine::Components; const ivec2 ShadowMapResolution = { 1024, 1024 }; RenderPipeline::RenderPipeline() { m_Skybox = new Skybox(); m_ShadowPass = new ShadowMapPass(ShadowMapResolution); AddPass(m_ShadowPass->GetPipelinePass()); } RenderPipeline::~RenderPipeline() { delete m_ShadowPass; } void RenderPipeline::Draw(Camera& camera) { Scene* scene = Application::GetService<SceneService>()->CurrentScene(); m_PreviousPass = nullptr; for(unsigned int i = 0; i < (unsigned int)m_RenderPasses.size(); i++) { RenderPipelinePass& info = m_RenderPasses[i]; // Setup info.Pass->Bind(); m_CurrentShader = ResourceManager::Get<Shader>(info.Shader); if (m_CurrentShader) { m_CurrentShader->Bind(); m_CurrentShader->Set("time", Renderer::GetTime()); m_CurrentShader->Set("deltaTime", Renderer::GetDeltaTime()); m_CurrentShader->Set("samples", (int)info.Pass->GetSamples()); m_CurrentShader->Set("resolution", vec2{ Renderer::GetResolution().x, Renderer::GetResolution().y }); camera.FillShader(m_CurrentShader); } // Draw calls if (info.DrawCallback) info.DrawCallback(m_PreviousPass); // Finalise if (m_CurrentShader) m_CurrentShader->Unbind(); m_CurrentShader = nullptr; info.Pass->Unbind(); m_PreviousPass = info.Pass; } if (camera.RenderTarget && !m_RenderPasses.empty()) m_RenderPasses[m_RenderPasses.size() - 1].Pass->CopyAttachmentTo(camera.RenderTarget); else if(m_PreviousPass) m_PreviousPass->BlitTo(nullptr, GL_COLOR_BUFFER_BIT); m_PreviousPass = nullptr; } void RenderPipeline::RemovePass(Framebuffer* pass) { for (int i = (int)m_RenderPasses.size() - 1; i >= 0; i--) { if (m_RenderPasses[i].Pass == pass) { m_RenderPasses.erase(m_RenderPasses.begin() + i); break; } } } void RenderPipeline::AddPass(RenderPipelinePass& passInfo) { if (!passInfo.Pass) return; m_RenderPasses.emplace_back(passInfo); } Framebuffer* RenderPipeline::GetPassAt(unsigned int index) { return index < m_RenderPasses.size() ? m_RenderPasses[index].Pass : nullptr; } RenderPipelinePass& RenderPipeline::GetRenderPassAt(unsigned int index) { Log::Assert(index < m_RenderPasses.size(), "Index out of range!"); return m_RenderPasses[index]; } std::vector<RenderPipelinePass>& RenderPipeline::GetAllRenderPasses() { return m_RenderPasses; } RenderTexture* RenderPipeline::GetOutputAttachment(unsigned int index) { if (m_RenderPasses.empty()) return nullptr; Framebuffer* pass = m_RenderPasses[m_RenderPasses.size() - 1].Pass; index = std::clamp(index, 0u, pass->ColourAttachmentCount()); return pass->GetColourAttachment(index); } void RenderPipeline::OnResized(ivec2 resolution) { for (RenderPipelinePass& pass : m_RenderPasses) if (pass.ResizeWithScreen) pass.Pass->SetResolution(resolution); } Shader* RenderPipeline::CurrentShader() { return m_CurrentShader; } Framebuffer* RenderPipeline::GetPreviousPass() { return m_PreviousPass; } ShadowMapPass* RenderPipeline::GetShadowMapPass() { return m_ShadowPass; } Skybox* RenderPipeline::GetSkybox() { return m_Skybox; }
27.529851
104
0.751423
[ "mesh", "vector" ]
e31367d500573d451fbd0e3a90c2e02594938967
9,383
cpp
C++
OptionPanel.cpp
Pachira762/ScreenHistogram
98300c6447e179e21c3a4bdd77812d1386623528
[ "MIT" ]
null
null
null
OptionPanel.cpp
Pachira762/ScreenHistogram
98300c6447e179e21c3a4bdd77812d1386623528
[ "MIT" ]
null
null
null
OptionPanel.cpp
Pachira762/ScreenHistogram
98300c6447e179e21c3a4bdd77812d1386623528
[ "MIT" ]
null
null
null
#include "pch.h" #include "OptionPanel.h" #include "GuiLayout.h" #include "WinUtil.h" #include "Theme.h" using namespace std; static OptionPanel* pThis = nullptr; OptionPanel::OptionPanel(): layout_(make_unique<GuiLayout>(MarginX, MarginY)) { pThis = this; } void OptionPanel::Show() { ShowWindow(hwnd_, SW_SHOW); } void OptionPanel::Hide() { ShowWindow(hwnd_, SW_HIDE); } void OptionPanel::Move() { auto [x, y] = CalcFramePos(); WinUtil::SetWindowPos(hwnd_, x, y); } void OptionPanel::Size() { auto [x, y] = CalcFramePos(); auto [w, h] = CalcFrameSize(); WinUtil::SetWindowPosSize(hwnd_, x, y, w, h, SWP_NOZORDER | SWP_NOACTIVATE); } std::shared_ptr<IGuiBuilder> OptionPanel::Create(HWND parent) { parent_ = parent; WNDCLASSEX wcex = {}; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = 0; wcex.lpfnWndProc = OptionPanel::FrameWndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = GetModuleHandle(NULL); wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = Theme::Dark::BgBrush; wcex.lpszClassName = L"ScreenHistogramOptionPanelFrameWnd"; WINRT_VERIFY(RegisterClassEx(&wcex)); auto [x, y] = CalcFramePos(); auto [w, h] = CalcFrameSize(); hwnd_ = WinUtil::Create(L"ScreenHistogramOptionPanelFrameWnd", NULL, WS_VISIBLE | WS_POPUP | WS_VSCROLL, WS_EX_LAYERED, x, y, w, h, parent); auto [cx, cy] = WinUtil::GetClientSize(hwnd_); auto builder = make_shared<GuiBuilderImpl>((HWND)hwnd_, MarginX, MarginY, cx - MarginX - VScrollWidth, layout_); builder->OnRadioGroupAdded = [this](const std::vector<HWND>& handles, const RadioButtonCallback& callback) { radioGroups_.push_back(RadioButtonGroup{ handles, callback }); customDrawTargets_.insert(handles.begin(), handles.end()); }; builder->OnCheckboxGroupAddes = [this](const std::vector<HWND>& handles, const CheckboxCallback& callback) { checkboxGroups_.push_back(CheckboxGroup{ handles, callback }); customDrawTargets_.insert(handles.begin(), handles.end()); }; builder->OnSliderAdded = [this](HWND handle, const SliderCallback& callback) { sliders_.insert({ handle, callback }); }; builder->OnBuild = [this](GuiBuilderImpl* builder, int contentWidth, int contentHeight) { auto hdc = GetDC(hwnd_); auto [cx, cy] = WinUtil::GetClientSize(hwnd_); layout_->Layout(hdc, cx - MarginX - VScrollWidth); ReleaseDC(hwnd_, hdc); UpdateScrollRange(layout_->Height()); UpdateScrollPage(WinUtil::GetClientSize(this->hwnd_).cy); }; return builder; } void OptionPanel::UpdateScrollRange(int range) { SCROLLINFO si{}; si.cbSize = sizeof(si); si.fMask = SIF_POS; GetScrollInfo(hwnd_, SB_VERT, &si); const int pos = si.nPos; si.fMask = SIF_RANGE; si.nMax = WinUtil::Pix(range); SetScrollInfo(hwnd_, SB_VERT, &si, TRUE); si.fMask = SIF_POS; GetScrollInfo(hwnd_, SB_VERT, &si); ScrollContent(pos - si.nPos); } void OptionPanel::UpdateScrollPage(int page) { SCROLLINFO si{}; si.cbSize = sizeof(si); si.fMask = SIF_POS; GetScrollInfo(hwnd_, SB_VERT, &si); const int pos = si.nPos; si.fMask = SIF_PAGE; si.nPage = WinUtil::Pix(page); SetScrollInfo(hwnd_, SB_VERT, &si, TRUE); si.fMask = SIF_POS; GetScrollInfo(hwnd_, SB_VERT, &si); ScrollContent(pos - si.nPos); } void OptionPanel::ScrollContent(int dy) { scroll_ += dy; ScrollWindowEx(hwnd_, 0, dy, nullptr, nullptr, nullptr, nullptr, SW_ERASE | SW_INVALIDATE | SW_SCROLLCHILDREN); UpdateWindow(hwnd_); } void OptionPanel::OnCreate(LPCREATESTRUCT cs) { Theme::SetWindowTheme_DarkMode_Explorer(hwnd_); Theme::EnableRoundCorner(hwnd_); if (Theme::IsEnabledAcrylic) { Theme::EnableAcrylicWindow(hwnd_); } SetLayeredWindowAttributes(hwnd_, 0, 255, LWA_ALPHA); SetWindowDisplayAffinity(hwnd_, WDA_EXCLUDEFROMCAPTURE); } void OptionPanel::OnSize(int cx, int cy) { auto page = WinUtil::GetClientSize(this->hwnd_).cy; UpdateScrollPage(page); } void OptionPanel::OnPaint() { int y = WinUtil::Dpi(-scroll_); PAINTSTRUCT ps{}; HDC hdc = BeginPaint(hwnd_, &ps); if (Theme::IsEnabledAcrylic) { FillRect(hdc, &ps.rcPaint, (HBRUSH)GetStockObject(BLACK_BRUSH)); } SetBkMode(hdc, TRANSPARENT); layout_->Draw(hdc, y); EndPaint(hwnd_, &ps); } void OptionPanel::OnHScroll(HWND scroll) { if (auto itr = sliders_.find(scroll); itr != sliders_.end()) { itr->second((int)SendMessage(scroll, TBM_GETPOS, 0, 0)); } } void OptionPanel::OnVScroll(int code, int delta) { SCROLLINFO si{}; si.cbSize = sizeof(si); si.fMask = SIF_ALL; GetScrollInfo(hwnd_, SB_VERT, &si); int pos = si.nPos; auto line = delta == 0 ? 1 : delta; switch (code) { case SB_LINEUP: si.nPos -= line; break; case SB_LINEDOWN: si.nPos += line; break; case SB_PAGEUP: si.nPos -= si.nPage; break; case SB_PAGEDOWN: si.nPos += si.nPage; break; case SB_THUMBTRACK: si.nPos = si.nTrackPos; break; case SB_TOP: si.nPos = si.nMin; break; case SB_BOTTOM: si.nPos = si.nMax; break; default: return; } si.fMask = SIF_POS; SetScrollInfo(hwnd_, SB_VERT, &si, TRUE); GetScrollInfo(hwnd_, SB_VERT, &si); auto dy = (pos - si.nPos); if (dy == 0) { return; } ScrollContent(dy); } void OptionPanel::OnCommand(int id, int code, HWND handle) { switch (code) { case BN_CLICKED: OnButtonClicked(handle, id); break; } } static bool IsInGroup(std::vector<HWND>& group, HWND hwnd, int index) { if (index < group.size() && hwnd == group.at(index)) { return true; } return false; } void OptionPanel::OnButtonClicked(HWND hwnd, int id) { for (auto& [radios, callback] : radioGroups_) { if (!callback) { continue; } if (IsInGroup(radios, hwnd, id)) { callback(id); return; } } for (auto& [checkboxes, callback] : checkboxGroups_) { if (!callback) { continue; } if (IsInGroup(checkboxes, hwnd, id)) { vector<bool> checked{}; for (auto& checkbox : checkboxes) { checked.push_back(static_cast<bool>(SendMessage(checkbox, BM_GETCHECK, 0, 0))); } callback(checked); return; } } } LRESULT OptionPanel::OnNotify(DWORD id, NMHDR* hdr) { switch (hdr->code) { case NM_CUSTOMDRAW: return OnCustomDraw((NMCUSTOMDRAW*)hdr); default: return 0; } } LRESULT OptionPanel::OnCustomDraw(NMCUSTOMDRAW* nmc) { static TCHAR buff[256]; const auto hwnd = nmc->hdr.hwndFrom; if (customDrawTargets_.find(hwnd) != customDrawTargets_.end()) { if (nmc->dwDrawStage == CDDS_PREERASE) { return CDRF_NOTIFYPOSTERASE; } else if (nmc->dwDrawStage != CDDS_PREPAINT) { return CDRF_DODEFAULT; } GetWindowText(nmc->hdr.hwndFrom, buff, _countof(buff)); auto hdc = nmc->hdc; SetBkMode(hdc, TRANSPARENT); SetTextColor(hdc, Theme::Dark::TextColor); SelectObject(hdc, Theme::TextFont); nmc->rc.left += WinUtil::Pix(17); DrawText(hdc, buff, -1, &nmc->rc, DT_VCENTER | DT_SINGLELINE); return CDRF_SKIPDEFAULT; } else { return CDRF_DODEFAULT; } } LRESULT CALLBACK OptionPanel::FrameWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { switch (msg) { case WM_CREATE: pThis->hwnd_ = hwnd; pThis->OnCreate((LPCREATESTRUCT)lp); return 0; case WM_SIZE: if (wp != 1) { pThis->OnSize(WinUtil::Dpi(LOWORD(lp)), WinUtil::Dpi(HIWORD(lp))); } return 0; case WM_PAINT: pThis->OnPaint(); return 0; case WM_NCHITTEST: if (DefWindowProc(hwnd, msg, wp, lp) == HTVSCROLL) { return HTVSCROLL; } else { if (WinUtil::NonClientHitTest(pThis->parent_, GET_X_LPARAM(lp), GET_Y_LPARAM(lp)) == HTCLIENT) { return HTCLIENT; } else { return HTTRANSPARENT; } } case WM_COMMAND: pThis->OnCommand(LOWORD(wp), HIWORD(wp), (HWND)lp); return 0; case WM_NOTIFY: return pThis->OnNotify(wp, (NMHDR*)lp); case WM_HSCROLL: pThis->OnHScroll((HWND)lp); return 0; case WM_VSCROLL: pThis->OnVScroll(LOWORD(wp), HIWORD(wp)); return 0; case WM_MOUSEWHEEL: if (auto wheel = GET_WHEEL_DELTA_WPARAM(wp); wheel > 0){ SendMessage(pThis->hwnd_, WM_VSCROLL, MAKEWPARAM(SB_LINEUP, wheel / 10), 0); } else { SendMessage(pThis->hwnd_, WM_VSCROLL, MAKEWPARAM(SB_LINEDOWN, abs(wheel) / 10), 0); } return 0; case WM_CTLCOLORBTN: case WM_CTLCOLORSTATIC: return (LRESULT)(Theme::IsEnabledAcrylic ? GetStockObject(BLACK_BRUSH) : Theme::Dark::BgBrush); } return DefWindowProc(hwnd, msg, wp, lp); }
24.30829
123
0.611958
[ "vector" ]
e314a557d239cf3e66ad586b11e9e2ea480089e4
730
cpp
C++
apps/calculator/src/cli/MetricsManager.cpp
mcfongtw/LostInCompilation
ca6a61f7a4fa6f215207a5ab8970471ef2568fd6
[ "MIT" ]
1
2016-11-29T13:41:28.000Z
2016-11-29T13:41:28.000Z
apps/calculator/src/cli/MetricsManager.cpp
mcfongtw/LostInCompilation
ca6a61f7a4fa6f215207a5ab8970471ef2568fd6
[ "MIT" ]
null
null
null
apps/calculator/src/cli/MetricsManager.cpp
mcfongtw/LostInCompilation
ca6a61f7a4fa6f215207a5ab8970471ef2568fd6
[ "MIT" ]
null
null
null
#include "cli/MetricsManager.h" #include <sstream> // Allocating and initializing MetricsManager's // static data member. The pointer is being // allocated - not the object inself. EventListenerPtr MetricsManager::INSTANCE = 0; EventListenerPtr MetricsManager::getInstance() { if(INSTANCE == 0) { INSTANCE = std::make_shared<MetricsManager>(); } return INSTANCE; } std::string MetricsManager::toString() { std::stringstream ss; ss << "Parsing Error Count: " << this->_parsing_error_count << std::endl; return ss.str(); } void MetricsManager::onReceived(Event event) { this->_parsing_error_count++; } int MetricsManager::getParsingErrorCount() { return this->_parsing_error_count; }
23.548387
77
0.709589
[ "object" ]
e31bb288ecfb681f8908dd97e00c077d73b57c71
2,891
cpp
C++
ros_controllers/mode_state_controller/src/mode_state_controller.cpp
hect1995/Robotics_intro
1b687585c20db5f1114d8ca6811a70313d325dd6
[ "BSD-3-Clause" ]
7
2018-10-24T14:52:20.000Z
2021-01-12T14:59:00.000Z
ros_controllers/mode_state_controller/src/mode_state_controller.cpp
hect1995/Robotics_intro
1b687585c20db5f1114d8ca6811a70313d325dd6
[ "BSD-3-Clause" ]
null
null
null
ros_controllers/mode_state_controller/src/mode_state_controller.cpp
hect1995/Robotics_intro
1b687585c20db5f1114d8ca6811a70313d325dd6
[ "BSD-3-Clause" ]
17
2019-09-29T10:22:41.000Z
2021-04-08T12:38:37.000Z
#include <algorithm> #include <cstddef> #include <mode_state_controller/mode_state_controller.h> namespace mode_state_controller { bool ModeStateController::init(hardware_interface::JointModeInterface* hw, ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh) { // get all joint names from the hardware interface const std::vector<std::string>& actuator_names = hw->getNames(); num_hw_joints_ = actuator_names.size(); for (unsigned i = 0; i < num_hw_joints_; i++) ROS_DEBUG("Got actuator %s", actuator_names[i].c_str()); // get publishing period if (!controller_nh.getParam("publish_rate", publish_rate_)) { ROS_ERROR("Parameter 'publish_rate' not set"); return false; } // realtime publisher realtime_pub_.reset(new realtime_tools::RealtimePublisher<mode_state_controller::ModeState>( root_nh, "actuator_mode_state", 4)); // get joints and allocate message for (unsigned i = 0; i < num_hw_joints_; i++) { try { actuator_state_.push_back(hw->getHandle(actuator_names[i])); } catch (const hardware_interface::HardwareInterfaceException& e) { std::vector<std::string> resource_names = hw->getNames(); std::stringstream ss; ss << e.what() << std::endl << "Available resources: " << std::endl; for (size_t i = 0; i < resource_names.size(); ++i) { ss << resource_names[i] << std::endl; } throw hardware_interface::HardwareInterfaceException(ss.str()); } realtime_pub_->msg_.name.push_back(actuator_names[i]); realtime_pub_->msg_.mode.push_back(mode_state_controller::ModeState::NOMODE); } return true; } void ModeStateController::starting(const ros::Time& time) { // initialize time last_publish_time_ = time; } void ModeStateController::update(const ros::Time& time, const ros::Duration& /*period*/) { // limit rate of publishing if (publish_rate_ > 0.0 && last_publish_time_ + ros::Duration(1.0 / publish_rate_) < time) { // try to publish if (realtime_pub_->trylock()) { // we're actually publishing, so increment time last_publish_time_ = last_publish_time_ + ros::Duration(1.0 / publish_rate_); // populate joint state message: // - fill only joints that are present in the JointStateInterface, i.e. indices [0, // num_hw_joints_) // - leave unchanged extra joints, which have static values, i.e. indices from // num_hw_joints_ onwards realtime_pub_->msg_.header.stamp = time; for (unsigned i = 0; i < num_hw_joints_; i++) { realtime_pub_->msg_.mode[i] = actuator_state_[i].getMode(); } realtime_pub_->unlockAndPublish(); } } } void ModeStateController::stopping(const ros::Time& /*time*/) { } } PLUGINLIB_EXPORT_CLASS(mode_state_controller::ModeStateController, controller_interface::ControllerBase)
31.769231
104
0.681425
[ "vector" ]
e31bffe90ea1280972855ba1957be965389398ca
2,668
cc
C++
src/vtk_viewer.cc
Arthur-Na/parallel-heat
492f79fb057541f7195ce8eea879ce61d5a96c5d
[ "MIT" ]
null
null
null
src/vtk_viewer.cc
Arthur-Na/parallel-heat
492f79fb057541f7195ce8eea879ce61d5a96c5d
[ "MIT" ]
null
null
null
src/vtk_viewer.cc
Arthur-Na/parallel-heat
492f79fb057541f7195ce8eea879ce61d5a96c5d
[ "MIT" ]
null
null
null
#include "vtk_viewer.hh" namespace vtk { VtkViewer::VtkViewer() : structured_grid_(vtkSmartPointer<vtkStructuredGrid>::New()) , points_(vtkSmartPointer<vtkPoints>::New()) , colors_(vtkSmartPointer<vtkUnsignedCharArray>::New()) , geometry_filter_(vtkSmartPointer<vtkStructuredGridGeometryFilter>::New()) , mapper_(vtkSmartPointer<vtkPolyDataMapper>::New()) , actor_(vtkSmartPointer<vtkActor>::New()) , renderer_(vtkSmartPointer<vtkRenderer>::New()) , render_window_(vtkSmartPointer<vtkRenderWindow>::New()) , render_window_interactor_(vtkSmartPointer<vtkRenderWindowInteractor>::New()) {} void VtkViewer::init(int size_x, int size_y, int size_z) { for (int i = 0; i < size_x; ++i) for (int j = 0; j < size_y; ++j) for (int k = 0; k < size_z; ++k) points_->InsertNextPoint(i, j, k); structured_grid_->SetDimensions(size_x, size_y, size_z); structured_grid_->SetPoints(points_); colors_->SetNumberOfComponents(3); colors_->SetName("colors"); mapper_->SetInputConnection(geometry_filter_->GetOutputPort()); actor_->SetMapper(mapper_); actor_->GetProperty()->SetPointSize(3); structured_grid_->GetPointData()->SetScalars(colors_); render_window_->AddRenderer(renderer_); render_window_interactor_->SetRenderWindow(render_window_); renderer_->AddActor(actor_); renderer_->SetBackground(.0, .0, .0); } void VtkViewer::update(const std::vector<double>& vect, int size_x, int size_y, double max_val) { colors_->Initialize(); for (unsigned int i = 0; i < structured_grid_->GetNumberOfPoints(); ++i) { double p[3]; structured_grid_->GetPoint(i, p); int index = (p[0] * size_x + p[1]) * size_y + p[2]; double val = vect[index]; float coeff = val / max_val; unsigned char red = static_cast<unsigned char>(255 * coeff); unsigned char blue = static_cast<unsigned char>(255 * (1 - coeff)); unsigned char color[3] = { red, 0, blue }; #if VTK_MAJOR_VERSION > 7 colors_->InsertNextTypedTuple(color); #else colors_->InsertNextTupleValue(color); #endif colors_->Modified(); } structured_grid_->GetPointData()->SetScalars(colors_); structured_grid_->Modified(); #if VTK_MAJOR_VERSION <= 5 geometry_filter_->SetInputConnection(structured_grid_->GetProducerPort()); #else geometry_filter_->SetInputData(structured_grid_); #endif geometry_filter_->Modified(); geometry_filter_->Update(); mapper_->Modified(); mapper_->Update(); render_window_->Render(); } void VtkViewer::show() { render_window_interactor_->Start(); } }
30.318182
97
0.681784
[ "render", "vector" ]
e330bd05957b99b63297c2d6082c673e9c963e6a
42,161
cpp
C++
services/bluetooth_standard/service/src/ble/ble_central_manager_impl.cpp
openharmony-sig-ci/communication_bluetooth
c9d9614e881224abfb423505e25e72163dd25df3
[ "Apache-2.0" ]
null
null
null
services/bluetooth_standard/service/src/ble/ble_central_manager_impl.cpp
openharmony-sig-ci/communication_bluetooth
c9d9614e881224abfb423505e25e72163dd25df3
[ "Apache-2.0" ]
null
null
null
services/bluetooth_standard/service/src/ble/ble_central_manager_impl.cpp
openharmony-sig-ci/communication_bluetooth
c9d9614e881224abfb423505e25e72163dd25df3
[ "Apache-2.0" ]
1
2021-09-13T11:16:33.000Z
2021-09-13T11:16:33.000Z
/* * Copyright (C) 2021 Huawei Device 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 "ble_central_manager_impl.h" #include "ble_adapter.h" #include "ble_feature.h" #include "ble_properties.h" #include "ble_utils.h" #include "common/adapter_manager.h" #include "securec.h" namespace bluetooth { struct BleCentralManagerImpl::impl { /** * @brief register scan callback to gap * * @return @c status. */ int RegisterCallbackToGap(); /** * @brief register extend scan callback to gap * * @return @c status. */ int RegisterExScanCallbackToGap(); /** * @brief Set report delay. * * @return @c status */ void StartReportDelay(); std::recursive_mutex mutex_ {}; /// callback type CALLBACK_TYPE callBackType_ = CALLBACK_TYPE_FIRST_MATCH; /// scan status int scanStatus_ = SCAN_NOT_STARTED; // stop scan type STOP_SCAN_TYPE stopScanType_ = STOP_SCAN_TYPE_NOR; /// scan result list std::vector<BleScanResultImpl> bleScanResult_ {}; /// Is stop scan bool isStopScan_ = false; /// scan settings BleScanSettingsImpl settings_ {}; /// scan parameters BleScanParams scanParams_ {}; /// Report delay timer std::unique_ptr<utility::Timer> timer_ = nullptr; std::map<std::string, std::vector<uint8_t>> incompleteData_ {}; BleCentralManagerImpl *bleCentralManagerImpl_ = nullptr; }; BleCentralManagerImpl::BleCentralManagerImpl( IBleCentralManagerCallback &callback, IAdapterBle &bleAdapter, utility::Dispatcher &dispatch) : centralManagerCallbacks_(&callback), bleAdapter_(&bleAdapter), dispatcher_(&dispatch), pimpl(std::make_unique<BleCentralManagerImpl::impl>()) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); pimpl->bleCentralManagerImpl_ = this; pimpl->scanParams_.ownAddrType = BLE_ADDR_TYPE_PUBLIC; pimpl->scanParams_.scanFilterPolicy = BLE_SCAN_FILTER_ALLOW_ALL; SetActiveScan(true); uint16_t interval = BLE_SCAN_MODE_LOW_POWER_INTERVAL_MS; SetInterval(interval); uint16_t window = BLE_SCAN_MODE_LOW_POWER_WINDOW_MS; SetWindow(window); } BleCentralManagerImpl::~BleCentralManagerImpl() { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); if (pimpl->timer_ != nullptr) { pimpl->timer_->Stop(); pimpl->timer_ = nullptr; } } int BleCentralManagerImpl::impl::RegisterCallbackToGap() { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); GapScanCallback scanCallbacks{}; scanCallbacks.advertisingReport = &BleCentralManagerImpl::AdvertisingReport; scanCallbacks.scanSetParamResult = &BleCentralManagerImpl::ScanSetParamResult; scanCallbacks.scanSetEnableResult = &BleCentralManagerImpl::ScanSetEnableResult; return GAPIF_RegisterScanCallback(&scanCallbacks, bleCentralManagerImpl_); } int BleCentralManagerImpl::impl::RegisterExScanCallbackToGap() { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); GapExScanCallback exScanCallbacks{}; exScanCallbacks.exAdvertisingReport = &BleCentralManagerImpl::ExAdvertisingReport; exScanCallbacks.scanExSetParamResult = &BleCentralManagerImpl::ScanExSetParamResult; exScanCallbacks.scanExSetEnableResult = &BleCentralManagerImpl::ScanExSetEnableResult; exScanCallbacks.directedAdvertisingReport = &BleCentralManagerImpl::DirectedAdvertisingReport; exScanCallbacks.scanTimeoutEvent = &BleCentralManagerImpl::ScanTimeoutEvent; return GAPIF_RegisterExScanCallback(&exScanCallbacks, bleCentralManagerImpl_); } int BleCentralManagerImpl::DeregisterCallbackToGap() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); int ret; if (BleFeature::GetInstance().IsLeExtendedAdvertisingSupported()) { ret = GAPIF_DeregisterExScanCallback(); } else { ret = GAPIF_DeregisterScanCallback(); } return ret; } void BleCentralManagerImpl::AdvertisingReport( uint8_t advType, const BtAddr *peerAddr, GapAdvReportParam reportParam, const BtAddr *currentAddr, void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); auto *centralManager = static_cast<BleCentralManagerImpl *>(context); if ((centralManager != nullptr) && (centralManager->dispatcher_ != nullptr)) { BtAddr addr; (void)memset_s(&addr, sizeof(addr), 0x00, sizeof(addr)); addr.type = peerAddr->type; (void)memcpy_s(addr.addr, BT_ADDRESS_SIZE, peerAddr->addr, BT_ADDRESS_SIZE); std::vector<uint8_t> datas(reportParam.data, reportParam.data + reportParam.dataLen); LOG_INFO("AdvertisingReport Data=%{public}s", BleUtils::ConvertIntToHexString(datas).c_str()); centralManager->dispatcher_->PostTask(std::bind( &BleCentralManagerImpl::AdvertisingReportTask, centralManager, advType, addr, datas, reportParam.rssi)); } } void BleCentralManagerImpl::ExAdvertisingReport( uint8_t advType, const BtAddr *addr, GapExAdvReportParam reportParam, const BtAddr *currentAddr, void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); auto *pCentralManager = static_cast<BleCentralManagerImpl *>(context); if ((pCentralManager != nullptr) && (pCentralManager->dispatcher_)) { BtAddr peerAddr; peerAddr.type = addr->type; (void)memcpy_s(peerAddr.addr, BT_ADDRESS_SIZE, addr->addr, BT_ADDRESS_SIZE); BtAddr peerCurrentAddr; if (currentAddr != nullptr) { peerCurrentAddr.type = currentAddr->type; (void)memcpy_s(peerCurrentAddr.addr, BT_ADDRESS_SIZE, currentAddr->addr, BT_ADDRESS_SIZE); } else { peerCurrentAddr = peerAddr; } std::vector<uint8_t> datas(reportParam.data, reportParam.data + reportParam.dataLen); LOG_INFO("ExAdvertisingReport Data=%{public}s", BleUtils::ConvertIntToHexString(datas).c_str()); pCentralManager->dispatcher_->PostTask(std::bind(&BleCentralManagerImpl::ExAdvertisingReportTask, pCentralManager, advType, peerAddr, datas, reportParam.rssi, peerCurrentAddr)); } } void BleCentralManagerImpl::AdvertisingReportTask( uint8_t advType, const BtAddr &peerAddr, const std::vector<uint8_t> &data, int8_t rssi) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Data = %{public}s", __func__, BleUtils::ConvertIntToHexString(data).c_str()); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); RawAddress advertisedAddress(RawAddress::ConvertToString(peerAddr.addr)); bool ret = false; BlePeripheralDevice device; if (FindDevice(advertisedAddress.GetAddress(), device)) { ret = AddPeripheralDevice(advType, peerAddr, data, rssi, device); if (ret) { /// LE General Discoverable Mode LE Limited Discoverable Mode return; } HandleGapEvent(BLE_GAP_SCAN_RESULT_EVT, 0); return; } ret = AddPeripheralDevice(advType, peerAddr, data, rssi, device); if (ret) { /// LE General Discoverable Mode LE Limited Discoverable Mode return; } HandleGapEvent(BLE_GAP_SCAN_RESULT_EVT, 0); } bool BleCentralManagerImpl::ExtractIncompleteData(uint8_t advType, const std::string &advertisedAddress, const std::vector<uint8_t> &data, std::vector<uint8_t> &completeData) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); if ((advType & BLE_EX_SCAN_DATE_STATUS_INCOMPLETE_MORE) == BLE_EX_SCAN_DATE_STATUS_INCOMPLETE_MORE) { auto iter = pimpl->incompleteData_.find(advertisedAddress); if (iter == pimpl->incompleteData_.end()) { pimpl->incompleteData_.insert(std::make_pair(advertisedAddress, data)); } else { iter->second.insert(iter->second.end(), data.begin(), data.end()); } return true; } else if ((advType & BLE_EX_SCAN_DATE_STATUS_INCOMPLETE_NO_MORE) == 0 && (advType & BLE_EX_SCAN_DATE_STATUS_INCOMPLETE_MORE) == 0) { auto iter = pimpl->incompleteData_.find(advertisedAddress); if (iter != pimpl->incompleteData_.end()) { iter->second.insert(iter->second.end(), data.begin(), data.end()); completeData = iter->second; } } else if ((advType & BLE_EX_SCAN_DATE_STATUS_INCOMPLETE_NO_MORE) == BLE_EX_SCAN_DATE_STATUS_INCOMPLETE_NO_MORE) { auto iter = pimpl->incompleteData_.find(advertisedAddress); if (iter != pimpl->incompleteData_.end()) { iter->second.insert(iter->second.end(), data.begin(), data.end()); completeData = iter->second; } } return false; } void BleCentralManagerImpl::ExAdvertisingReportTask(uint8_t advType, const BtAddr &peerAddr, const std::vector<uint8_t> &data, int8_t rssi, const BtAddr &peerCurrentAddr) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Data = %{public}s", __func__, BleUtils::ConvertIntToHexString(data).c_str()); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); RawAddress advAddress(RawAddress::ConvertToString(peerAddr.addr)); /// Set whether only legacy advertisments should be returned in scan results. if (pimpl->settings_.GetLegacy()) { if ((advType & BLE_LEGACY_ADV_NONCONN_IND_WITH_EX_ADV) == 0) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s: Excepted addr = %{public}s; advType = %{public}d", __func__, advAddress.GetAddress().c_str(), advType); return; } } /// incomplete data RawAddress advCurrentAddress(RawAddress::ConvertToString(peerCurrentAddr.addr)); LOG_DEBUG("[BleCentralManagerImpl] %{public}s:peerAddr = %{public}s, peerCurrentAddr = %{public}s", __func__, advAddress.GetAddress().c_str(), advCurrentAddress.GetAddress().c_str()); std::vector<uint8_t> incompleteData(data.begin(), data.end()); if (ExtractIncompleteData(advType, advCurrentAddress.GetAddress(), data, incompleteData)) { return; } bool ret = false; BlePeripheralDevice device; if (FindDevice(advAddress.GetAddress(), device)) { ret = AddPeripheralDevice(advType, peerAddr, incompleteData, rssi, device); if (ret) { /// not discovery pimpl->incompleteData_.clear(); return; } HandleGapExScanEvent(BLE_GAP_EX_SCAN_RESULT_EVT, 0); pimpl->incompleteData_.clear(); return; } ret = AddPeripheralDevice(advType, peerAddr, incompleteData, rssi, device); if (ret) { /// not discovery pimpl->incompleteData_.clear(); return; } pimpl->incompleteData_.clear(); HandleGapExScanEvent(BLE_GAP_EX_SCAN_RESULT_EVT, 0); } bool BleCentralManagerImpl::AddPeripheralDevice(uint8_t advType, const BtAddr &peerAddr, const std::vector<uint8_t> &data, int8_t rssi, const BlePeripheralDevice &dev) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); BlePeripheralDevice device = dev; RawAddress advertisedAddress(RawAddress::ConvertToString(peerAddr.addr)); device.SetAddress(advertisedAddress); device.SetManufacturerData(""); device.SetRSSI(rssi); if (data.size() > 0) { BlePeripheralDeviceParseAdvData parseAdvData = { .payload = const_cast<uint8_t *>(data.data()), .length = data.size(), }; device.ParseAdvertiserment(parseAdvData); uint8_t falg = device.GetAdFlag(); if (CheckBleScanMode(falg)) { return true; } } else { uint8_t falg = device.GetAdFlag(); if (CheckBleScanMode(falg)) { return true; } } device.SetAddressType(peerAddr.type); if ((advType == SCAN_ADV_SCAN_IND) || (advType == SCAN_ADV_NONCONN_IND)) { device.SetConnectable(false); } else if ((advType == SCAN_ADV_IND) || (advType == SCAN_ADV_DIRECT_IND)) { device.SetConnectable(true); } BleScanResultImpl result; result.SetPeripheralDevice(device); pimpl->bleScanResult_.push_back(result); return false; } bool BleCentralManagerImpl::CheckBleScanMode(uint8_t falg) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:adv flag = %u", __func__, falg); switch (BleConfig::GetInstance().GetBleScanMode()) { case BLE_SCAN_MODE_NON_DISC: if (falg == BLE_ADV_FLAG_NON_LIMIT_DISC) { return false; } break; case BLE_SCAN_MODE_GENERAL: if ((falg & BLE_ADV_FLAG_LIMIT_DISC) == BLE_ADV_FLAG_LIMIT_DISC || (falg & BLE_ADV_FLAG_GEN_DISC) == BLE_ADV_FLAG_GEN_DISC) { return false; } break; case BLE_SCAN_MODE_LIMITED: if ((falg & BLE_ADV_FLAG_LIMIT_DISC) == BLE_ADV_FLAG_LIMIT_DISC) { return false; } break; case BLE_SCAN_MODE_ALL: default: return false; } return true; } void BleCentralManagerImpl::ScanSetParamResult(uint8_t status, void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); auto *centralManager = static_cast<BleCentralManagerImpl *>(context); if ((centralManager != nullptr) && (centralManager->dispatcher_ != nullptr)) { centralManager->dispatcher_->PostTask(std::bind( &BleCentralManagerImpl::HandleGapEvent, centralManager, BLE_GAP_SCAN_PARAM_SET_COMPLETE_EVT, status)); } } void BleCentralManagerImpl::ScanExSetParamResult(uint8_t status, void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); auto *centralManager = static_cast<BleCentralManagerImpl *>(context); if ((centralManager != nullptr) && (centralManager->dispatcher_ != nullptr)) { centralManager->dispatcher_->PostTask(std::bind(&BleCentralManagerImpl::HandleGapExScanEvent, centralManager, BLE_GAP_EX_SCAN_PARAM_SET_COMPLETE_EVT, status)); } } void BleCentralManagerImpl::ScanSetEnableResult(uint8_t status, void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); auto *centralManager = static_cast<BleCentralManagerImpl *>(context); if ((centralManager != nullptr) && (centralManager->dispatcher_ != nullptr)) { centralManager->dispatcher_->PostTask( std::bind(&BleCentralManagerImpl::ScanSetEnableResultTask, centralManager, status)); (static_cast<BleAdapter *>(centralManager->bleAdapter_))->NotifyAllWaitContinue(); } } void BleCentralManagerImpl::ScanSetEnableResultTask(uint8_t status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); if (pimpl->isStopScan_) { if (pimpl->stopScanType_ == STOP_SCAN_TYPE_RESOLVING_LIST) { HandleGapEvent(BLE_GAP_RESOLVING_LIST_ADV_SCAN_STOP_COMPLETE_EVT, status); } else { HandleGapEvent(BLE_GAP_SCAN_STOP_COMPLETE_EVT, status); } } else { if (pimpl->stopScanType_ == STOP_SCAN_TYPE_RESOLVING_LIST) { HandleGapEvent(BLE_GAP_RESOLVING_LIST_ADV_SCAN_START_COMPLETE_EVT, status); } else { HandleGapEvent(BLE_GAP_SCAN_START_COMPLETE_EVT, status); } } } void BleCentralManagerImpl::ScanExSetEnableResult(uint8_t status, void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); auto *centralManager = static_cast<BleCentralManagerImpl *>(context); if ((centralManager != nullptr) && (centralManager->dispatcher_ != nullptr)) { centralManager->dispatcher_->PostTask( std::bind(&BleCentralManagerImpl::ScanExSetEnableResultTask, centralManager, status)); (static_cast<BleAdapter *>(centralManager->bleAdapter_))->NotifyAllWaitContinue(); } } void BleCentralManagerImpl::ScanExSetEnableResultTask(uint8_t status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); if (pimpl->isStopScan_) { if (pimpl->stopScanType_ == STOP_SCAN_TYPE_RESOLVING_LIST) { HandleGapExScanEvent(BLE_GAP_EX_RESOLVING_LIST_ADV_SCAN_STOP_COMPLETE_EVT, status); } else { HandleGapExScanEvent(BLE_GAP_EX_SCAN_STOP_COMPLETE_EVT, status); } } else { if (pimpl->stopScanType_ == STOP_SCAN_TYPE_RESOLVING_LIST) { HandleGapExScanEvent(BLE_GAP_EX_RESOLVING_LIST_ADV_SCAN_START_COMPLETE_EVT, status); } else { HandleGapExScanEvent(BLE_GAP_EX_SCAN_START_COMPLETE_EVT, status); } } } void BleCentralManagerImpl::StartScan() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:<-- Start scan start", __func__); int status = AdapterManager::GetInstance()->GetState(BTTransport::ADAPTER_BLE); if (status != BTStateID::STATE_TURN_ON) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:%{public}s", __func__, "Bluetooth adapter is invalid."); pimpl->scanStatus_ = SCAN_NOT_STARTED; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return; } pimpl->callBackType_ = CALLBACK_TYPE_FIRST_MATCH; Start(false); LOG_DEBUG("[BleCentralManagerImpl] %{public}s:<-- Start scan end", __func__); } void BleCentralManagerImpl::StartScan(const BleScanSettingsImpl &setting) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:<-- Start scan start", __func__); int status = AdapterManager::GetInstance()->GetState(BTTransport::ADAPTER_BLE); if (status != BTStateID::STATE_TURN_ON) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:%{public}s", __func__, "Bluetooth adapter is invalid."); pimpl->scanStatus_ = SCAN_NOT_STARTED; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return; } pimpl->settings_ = setting; int matchingMode; if (setting.GetReportDelayMillisValue() > 0) { matchingMode = CALLBACK_TYPE_ALL_MATCHES; } else { matchingMode = CALLBACK_TYPE_FIRST_MATCH; } SetScanModeDuration(setting.GetScanMode(), matchingMode); if (matchingMode == CALLBACK_TYPE_FIRST_MATCH) { pimpl->callBackType_ = CALLBACK_TYPE_FIRST_MATCH; } else { pimpl->callBackType_ = CALLBACK_TYPE_ALL_MATCHES; } Start(false); LOG_DEBUG("[BleCentralManagerImpl] %{public}s:<-- Start scan end", __func__); } void BleCentralManagerImpl::StopScan() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:-> Stop scan start", __func__); if (pimpl->scanStatus_ == SCAN_NOT_STARTED) { centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return; } Stop(); LOG_DEBUG("[BleCentralManagerImpl] %{public}s:-> Stop scan end", __func__); } void BleCentralManagerImpl::StartOrStopScan(const STOP_SCAN_TYPE &scanType, bool isStartScan) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:-> StartOrStopScan scan start", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); int ret; if (BleFeature::GetInstance().IsExtendedScanSupported()) { ret = SetExScanEnable(isStartScan); } else { ret = SetScanEnable(isStartScan); } if (ret != BT_NO_ERROR) { LOG_ERROR("stop or start extend scan: err: %{public}d isScan : %{public}d", ret, isStartScan); pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; return; } pimpl->stopScanType_ = scanType; pimpl->isStopScan_ = !isStartScan; if (isStartScan) { pimpl->scanStatus_ = SCAN_FAILED_ALREADY_STARTED; LOG_DEBUG("start extend scan successful"); } else { if (scanType != STOP_SCAN_TYPE_RESOLVING_LIST) { pimpl->scanStatus_ = SCAN_NOT_STARTED; } else { pimpl->scanStatus_ = SCAN_FAILED_ALREADY_STARTED; } LOG_DEBUG("stop extend scan successful"); } } void BleCentralManagerImpl::SetActiveScan(bool active) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); if (active) { pimpl->scanParams_.scanType = BLE_SCAN_TYPE_ACTIVE; } else { pimpl->scanParams_.scanType = BLE_SCAN_TYPE_PASSIVE; } } void BleCentralManagerImpl::SetInterval(uint16_t intervalMSecs) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); pimpl->scanParams_.scanInterval = intervalMSecs / BLE_SCAN_UNIT_TIME; } void BleCentralManagerImpl::SetWindow(uint16_t windowMSecs) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); pimpl->scanParams_.scanWindow = windowMSecs / BLE_SCAN_UNIT_TIME; } void BleCentralManagerImpl::ClearResults() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); pimpl->bleScanResult_.clear(); } void BleCentralManagerImpl::SetScanModeDuration(int scanMode, int type) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); switch (scanMode) { case SCAN_MODE_LOW_POWER: if (type == CALLBACK_TYPE_ALL_MATCHES) { uint16_t interval = BLE_SCAN_MODE_BATCH_LOW_POWER_INTERVAL_MS; SetInterval(interval); uint16_t window = BLE_SCAN_MODE_BATCH_LOW_POWER_WINDOW_MS; SetWindow(window); } else { uint16_t interval = BLE_SCAN_MODE_LOW_POWER_INTERVAL_MS; SetInterval(interval); uint16_t window = BLE_SCAN_MODE_LOW_POWER_WINDOW_MS; SetWindow(window); } break; case SCAN_MODE_BALANCED: if (type == CALLBACK_TYPE_ALL_MATCHES) { uint16_t interval = BLE_SCAN_MODE_BATCH_BALANCED_INTERVAL_MS; SetInterval(interval); uint16_t window = BLE_SCAN_MODE_BATCH_BALANCED_WINDOW_MS; SetWindow(window); } else { uint16_t interval = BLE_SCAN_MODE_BALANCED_INTERVAL_MS; SetInterval(interval); uint16_t window = BLE_SCAN_MODE_BALANCED_WINDOW_MS; SetWindow(window); } break; case SCAN_MODE_LOW_LATENCY: if (type == CALLBACK_TYPE_ALL_MATCHES) { uint16_t interval = BLE_SCAN_MODE_BATCH_LOW_LATENCY_INTERVAL_MS; SetInterval(interval); uint16_t window = BLE_SCAN_MODE_BATCH_LOW_LATENCY_WINDOW_MS; SetWindow(window); } else { uint16_t interval = BLE_SCAN_MODE_LOW_LATENCY_INTERVAL_MS; SetInterval(interval); uint16_t window = BLE_SCAN_MODE_LOW_LATENCY_WINDOW_MS; SetWindow(window); } break; default: break; } } void BleCentralManagerImpl::TimerCallback(void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); auto *centralManager = static_cast<BleCentralManagerImpl *>(context); if ((centralManager != nullptr) && (centralManager->dispatcher_ != nullptr)) { centralManager->dispatcher_->PostTask( std::bind(&BleCentralManagerImpl::HandleGapEvent, centralManager, BLE_GAP_SCAN_DELAY_REPORT_RESULT_EVT, 0)); centralManager->dispatcher_->PostTask(std::bind(&BleCentralManagerImpl::StopScan, centralManager)); } } int BleCentralManagerImpl::SetScanParamToGap() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); GapLeScanParam param; param.scanType = pimpl->scanParams_.scanType; param.param.scanInterval = pimpl->scanParams_.scanInterval; param.param.scanWindow = pimpl->scanParams_.scanWindow; return GAPIF_LeScanSetParam(param, pimpl->scanParams_.scanFilterPolicy); } int BleCentralManagerImpl::SetExScanParamToGap() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::vector<GapLeScanParam> params; uint8_t scanPhys = GAP_EX_SCAN_PHY_1M; if (pimpl->settings_.GetLegacy()) { GapLeScanParam param; param.scanType = pimpl->scanParams_.scanType; param.param.scanInterval = pimpl->scanParams_.scanInterval; param.param.scanWindow = pimpl->scanParams_.scanWindow; params.push_back(param); } else { switch (pimpl->settings_.GetPhy()) { case PHY_LE_CODED: scanPhys = GAP_EX_SCAN_PHY_CODED; GapLeScanParam paramCoded; paramCoded.scanType = pimpl->scanParams_.scanType; paramCoded.param.scanInterval = pimpl->scanParams_.scanInterval; paramCoded.param.scanWindow = pimpl->scanParams_.scanWindow; params.push_back(paramCoded); break; case PHY_LE_ALL_SUPPORTED: scanPhys = GAP_EX_SCAN_PHY_1M | GAP_EX_SCAN_PHY_CODED; GapLeScanParam param1M; param1M.scanType = pimpl->scanParams_.scanType; param1M.param.scanInterval = pimpl->scanParams_.scanInterval; param1M.param.scanWindow = pimpl->scanParams_.scanWindow; params.push_back(param1M); GapLeScanParam paramCodedAll; paramCodedAll.scanType = pimpl->scanParams_.scanType; paramCodedAll.param.scanInterval = pimpl->scanParams_.scanInterval; paramCodedAll.param.scanWindow = pimpl->scanParams_.scanWindow; params.push_back(paramCodedAll); break; case PHY_LE_1M: default: scanPhys = GAP_EX_SCAN_PHY_1M; GapLeScanParam param; param.scanType = pimpl->scanParams_.scanType; param.param.scanInterval = pimpl->scanParams_.scanInterval; param.param.scanWindow = pimpl->scanParams_.scanWindow; params.push_back(param); break; } } return GAPIF_LeExScanSetParam(pimpl->scanParams_.scanFilterPolicy, scanPhys, &params[0]); } int BleCentralManagerImpl::SetScanEnable(bool enable) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:%{public}d", __func__, enable); return GAPIF_LeScanSetEnable(enable, isDuplicates_); } int BleCentralManagerImpl::SetExScanEnable(bool enable) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); return GAPIF_LeExScanSetEnable(enable, isDuplicates_, 0, 0); } void BleCentralManagerImpl::impl::StartReportDelay() { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); if ((settings_.GetReportDelayMillisValue() > 0) && (callBackType_ == CALLBACK_TYPE_ALL_MATCHES)) { if (timer_ == nullptr) { timer_ = std::make_unique<utility::Timer>(std::bind(&TimerCallback, bleCentralManagerImpl_)); } timer_->Start(settings_.GetReportDelayMillisValue()); } } bool BleCentralManagerImpl::SetLegacyScanParamToGap() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); bool ret = true; ret = pimpl->RegisterCallbackToGap(); if (ret != BT_NO_ERROR) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:RegisterCallbackToGap failed.", __func__); pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return false; } pimpl->isStopScan_ = false; ret = SetScanParamToGap(); if (ret != BT_NO_ERROR) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:SetScanParamToGap failed.", __func__); pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return false; } return ret; } bool BleCentralManagerImpl::SetExtendScanParamToGap() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); bool ret = true; ret = pimpl->RegisterExScanCallbackToGap(); if (ret != BT_NO_ERROR) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:RegisterExScanCallbackToGap failed.", __func__); pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return false; } pimpl->isStopScan_ = false; ret = SetExScanParamToGap(); if (ret != BT_NO_ERROR) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:SetExScanParamToGap failed.", __func__); pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return false; } return ret; } bool BleCentralManagerImpl::SetScanParamOrExScanParamToGap() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); bool ret = true; if (BleFeature::GetInstance().IsExtendedScanSupported()) { ret = SetExtendScanParamToGap(); } else { ret = SetLegacyScanParamToGap(); } return ret; } bool BleCentralManagerImpl::Start(bool isContinue) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); if (pimpl->scanStatus_ == SCAN_FAILED_ALREADY_STARTED) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:%{public}s", __func__, "Scan already started."); centralManagerCallbacks_->OnStartScanFailed(SCAN_FAILED_ALREADY_STARTED); return true; } pimpl->scanStatus_ = SCAN_FAILED_ALREADY_STARTED; pimpl->stopScanType_ = STOP_SCAN_TYPE_NOR; if (!isContinue) { ClearResults(); } return SetScanParamOrExScanParamToGap(); } void BleCentralManagerImpl::Stop() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); int ret; if (BleFeature::GetInstance().IsExtendedScanSupported()) { ret = SetExScanEnable(false); } else { ret = SetScanEnable(false); } if (ret != BT_NO_ERROR) { LOG_ERROR("stop scanning: err: %{public}d", ret); pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return; } else { std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); pimpl->stopScanType_ = STOP_SCAN_TYPE_NOR; pimpl->isStopScan_ = true; pimpl->settings_.SetReportDelay(0); } } int BleCentralManagerImpl::GetDeviceType(const std::string &address) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); for (auto value : pimpl->bleScanResult_) { if (!address.compare(value.GetPeripheralDevice().GetRawAddress().GetAddress())) { return value.GetPeripheralDevice().GetDeviceType(); } } return BLE_BT_DEVICE_TYPE_UNKNOWN; } int BleCentralManagerImpl::GetDeviceAddrType(const std::string &address) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); for (auto value : pimpl->bleScanResult_) { if (!address.compare(value.GetPeripheralDevice().GetRawAddress().GetAddress())) { return value.GetPeripheralDevice().GetAddressType(); } } return BLE_ADDR_TYPE_UNKNOWN; } std::string BleCentralManagerImpl::GetDeviceName(const std::string &address) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); for (auto value : pimpl->bleScanResult_) { if (!address.compare(value.GetPeripheralDevice().GetRawAddress().GetAddress())) { return value.GetPeripheralDevice().GetName(); } } return std::string(""); } bool BleCentralManagerImpl::FindDevice(const std::string &address, BlePeripheralDevice &dev) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); for (auto it = pimpl->bleScanResult_.begin(); it != pimpl->bleScanResult_.end(); it++) { if (!address.compare(it->GetPeripheralDevice().GetRawAddress().GetAddress())) { dev = it->GetPeripheralDevice(); pimpl->bleScanResult_.erase(it); return true; } } return false; } int BleCentralManagerImpl::GetScanStatus() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); return pimpl->scanStatus_; } void BleCentralManagerImpl::DirectedAdvertisingReport(uint8_t advType, const BtAddr *addr, GapDirectedAdvReportParam reportParam, const BtAddr *currentAddr, void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); } void BleCentralManagerImpl::ScanTimeoutEvent(void *context) { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); } void BleCentralManagerImpl::GapScanParamSetCompleteEvt(int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); if (status != BT_NO_ERROR) { pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; centralManagerCallbacks_->OnStartScanFailed(status); LOG_ERROR("[BleCentralManagerImpl] %{public}s:Set scan param failed! %{public}d.", __func__, status); return; } pimpl->StartReportDelay(); if (pimpl->isStopScan_) { return; } int ret = SetScanEnable(true); if (ret != BT_NO_ERROR) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:SetScanEnable param failed! %{public}d.", __func__, ret); pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return; } } void BleCentralManagerImpl::GapScanResultEvt() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Scan result", __func__); if ((centralManagerCallbacks_ != nullptr) && (pimpl->callBackType_ == CALLBACK_TYPE_FIRST_MATCH)) { std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); centralManagerCallbacks_->OnScanCallback(pimpl->bleScanResult_.back()); } } void BleCentralManagerImpl::GapScanDelayReportResultEvt() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Scan batch results", __func__); if ((centralManagerCallbacks_ != nullptr) && (pimpl->callBackType_ == CALLBACK_TYPE_ALL_MATCHES)) { if (pimpl->timer_ != nullptr) { pimpl->timer_->Stop(); } std::lock_guard<std::recursive_mutex> legacyLock(pimpl->mutex_); centralManagerCallbacks_->OnBleBatchScanResultsEvent(pimpl->bleScanResult_); } } void BleCentralManagerImpl::GapScanStartCompleteEvt(int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Start scan", __func__); centralManagerCallbacks_->OnStartScanFailed(status); if (status != BT_NO_ERROR) { pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; LOG_ERROR("[BleCentralManagerImpl] %{public}s:Start scan failed! %{public}d.", __func__, status); } } void BleCentralManagerImpl::GapScanStopCompleteEvt(int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Stop scan", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); if (status != BT_NO_ERROR) { pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; LOG_ERROR("[BleCentralManagerImpl] %{public}s:Stop scan failed! %{public}d.", __func__, status); } pimpl->scanStatus_ = SCAN_NOT_STARTED; centralManagerCallbacks_->OnStartScanFailed(status); } void BleCentralManagerImpl::GapScanResolvingCompletEvt(int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s: ", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); if (status != BT_NO_ERROR) { pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; LOG_ERROR("[BleCentralManagerImpl] %{public}s:Resovling stop scan failed! %{public}d.", __func__, status); } } void BleCentralManagerImpl::HandleGapEvent(const BLE_GAP_CB_EVENT &event, int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:[event no: %{public}d]", __func__, (int)event); switch (event) { case BLE_GAP_SCAN_PARAM_SET_COMPLETE_EVT: GapScanParamSetCompleteEvt(status); break; case BLE_GAP_SCAN_RESULT_EVT: GapScanResultEvt(); break; case BLE_GAP_SCAN_DELAY_REPORT_RESULT_EVT: GapScanDelayReportResultEvt(); break; case BLE_GAP_SCAN_START_COMPLETE_EVT: GapScanStartCompleteEvt(status); break; case BLE_GAP_RESOLVING_LIST_ADV_SCAN_START_COMPLETE_EVT: GapScanResolvingCompletEvt(status); break; case BLE_GAP_SCAN_STOP_COMPLETE_EVT: GapScanStopCompleteEvt(status); break; case BLE_GAP_RESOLVING_LIST_ADV_SCAN_STOP_COMPLETE_EVT: GapScanResolvingCompletEvt(status); break; default: { LOG_ERROR("[BleCentralManagerImpl] %{public}s:Invalid event! %{public}d.", __func__, event); break; } } } void BleCentralManagerImpl::GapExScanParamSetCompleteEvt(int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); if (status != BT_NO_ERROR) { pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; LOG_ERROR("[BleCentralManagerImpl] %{public}s:Set scan param failed! %{public}d.", __func__, status); centralManagerCallbacks_->OnStartScanFailed(status); return; } pimpl->StartReportDelay(); if (pimpl->isStopScan_) { return; } int ret = SetExScanEnable(true); if (ret != BT_NO_ERROR) { LOG_ERROR("[BleCentralManagerImpl] %{public}s:SetExScanEnable param failed! %{public}d.", __func__, ret); pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; centralManagerCallbacks_->OnStartScanFailed(pimpl->scanStatus_); return; } } void BleCentralManagerImpl::GapExScanResultEvt() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Scan result", __func__); if ((centralManagerCallbacks_ != nullptr) && (pimpl->callBackType_ == CALLBACK_TYPE_FIRST_MATCH)) { std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); centralManagerCallbacks_->OnScanCallback(pimpl->bleScanResult_.back()); } } void BleCentralManagerImpl::GapExScanDelayReportResultEvt() const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Scan batch results", __func__); if ((centralManagerCallbacks_ != nullptr) && (pimpl->callBackType_ == CALLBACK_TYPE_ALL_MATCHES)) { if (pimpl->timer_ != nullptr) { pimpl->timer_->Stop(); } std::lock_guard<std::recursive_mutex> exAdvLock(pimpl->mutex_); centralManagerCallbacks_->OnBleBatchScanResultsEvent(pimpl->bleScanResult_); } } void BleCentralManagerImpl::GapExScanStartCompleteEvt(int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Start scan", __func__); centralManagerCallbacks_->OnStartScanFailed(status); if (status != BT_NO_ERROR) { pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; LOG_ERROR("[BleCentralManagerImpl] %{public}s:Start scan failed! %{public}d.", __func__, status); } } void BleCentralManagerImpl::GapExScanStopCompleteEvt(int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:Stop scan", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); if (status != BT_NO_ERROR) { pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; LOG_ERROR("[BleCentralManagerImpl] %{public}s:Stop scan failed! %{public}d.", __func__, status); } pimpl->scanStatus_ = SCAN_NOT_STARTED; centralManagerCallbacks_->OnStartScanFailed(status); } void BleCentralManagerImpl::GapExScanResolvingCompletEvt(int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:", __func__); std::lock_guard<std::recursive_mutex> lk(pimpl->mutex_); if (status != BT_NO_ERROR) { pimpl->scanStatus_ = SCAN_FAILED_INTERNAL_ERROR; LOG_ERROR("[BleCentralManagerImpl] %{public}s:Resolving stop scan failed! %{public}d.", __func__, status); } } void BleCentralManagerImpl::HandleGapExScanEvent(const BLE_GAP_CB_EVENT &event, int status) const { LOG_DEBUG("[BleCentralManagerImpl] %{public}s:[event no: %{public}d]", __func__, (int)event); switch (event) { case BLE_GAP_EX_SCAN_PARAM_SET_COMPLETE_EVT: GapExScanParamSetCompleteEvt(status); break; case BLE_GAP_EX_SCAN_RESULT_EVT: GapExScanResultEvt(); break; case BLE_GAP_EX_SCAN_DELAY_REPORT_RESULT_EVT: GapExScanDelayReportResultEvt(); break; case BLE_GAP_EX_SCAN_START_COMPLETE_EVT: GapExScanStartCompleteEvt(status); break; case BLE_GAP_EX_RESOLVING_LIST_ADV_SCAN_START_COMPLETE_EVT: GapExScanResolvingCompletEvt(status); break; case BLE_GAP_EX_SCAN_STOP_COMPLETE_EVT: GapExScanStopCompleteEvt(status); break; case BLE_GAP_EX_RESOLVING_LIST_ADV_SCAN_STOP_COMPLETE_EVT: GapExScanResolvingCompletEvt(status); break; default: { LOG_ERROR("[BleCentralManagerImpl] %{public}s:Invalid event! %{public}d.", __func__, event); break; } } } } // namespace bluetooth
37.509786
127
0.684068
[ "vector" ]
e336715da5cbebdb8c58f2578234575cb84d1cc3
9,373
cpp
C++
src/json.cpp
jyf111/easy-json
a341b0437b9d3cd36b88d1e2e11ea7dde3cb4633
[ "MIT" ]
null
null
null
src/json.cpp
jyf111/easy-json
a341b0437b9d3cd36b88d1e2e11ea7dde3cb4633
[ "MIT" ]
null
null
null
src/json.cpp
jyf111/easy-json
a341b0437b9d3cd36b88d1e2e11ea7dde3cb4633
[ "MIT" ]
null
null
null
#include "json.h" #include <iostream> #include <assert.h> json::json() { type = JSON_NULL; } json::json(bool _b) : b(_b) { type = JSON_BOOLEAN; } json::json(double _num) : num(_num) { type = JSON_NUMBER; } json::json(string _value) : value(_value) { type = JSON_STRING; } json::json(vector<shared_ptr<json>> _array) : array(_array) { type = JSON_ARRAY; } json::json(vector<pair<string, shared_ptr<json>>> _object) : object(_object) { type = JSON_OBJECT; } #define TAB_SIZE 2 string tab(int cnt) { return string(cnt*TAB_SIZE, ' '); } string toString(double num) { static char buf[32]; snprintf(buf, sizeof(buf), "%.16g", num); return string(buf); } string json::dump(int indent) { string s; bool tag = true; switch(type) { case JSON_NULL: return "null"; case JSON_BOOLEAN: return (b ? "true" : "false"); case JSON_NUMBER: return toString(num); case JSON_STRING: return value; case JSON_ARRAY: s = "["; for(auto& item : array) { if(!tag) s += ", "; else tag = false; s += item->dump(); } return s + "]"; default: if(object.empty()) return "{}"; s = "{"; indent++; for(auto& attribute : object) { if(!tag) s += ",\n" + tab(indent); else s += "\n" + tab(indent), tag = false; s += '"' + attribute.first + "\": " + attribute.second->dump(indent); } return s + "\n" + tab(indent-1) + "}"; } } jsonType json::getType() { return type; } bool json::getB() { return b; } double json::getNum() { return num; } string json::getValue() { return value; } vector<shared_ptr<json>>& json::getArray() { return array; } vector<pair<string, shared_ptr<json>>>& json::getObject() { return object; } bool json::isAtom() { return type!=JSON_ARRAY && type!=JSON_OBJECT; } bool isWhiteSpace(string::const_iterator it) { return *it==' ' || *it=='\n' || *it=='\t' || *it=='\r'; } bool isDigit(string::const_iterator it) { return *it>='0' && *it<='9'; } bool parser::match(char c, bool omit) { if(omit) while(it!=cend(jstr) && isWhiteSpace(it)) ++it; if(it!=cend(jstr) && *it==c) { ++it; return true; } return false; } bool parser::match(string s) { for(char c : s) { if(it==cend(jstr)) return false; if(!match(c, false)) return false; } return true; } shared_ptr<json> parser::parse() { shared_ptr<json> rt; while(it!=cend(jstr) && isWhiteSpace(it)) ++it; if(it==cend(jstr)) return nullptr; if(isDigit(it) || *it=='.' || *it=='-') { // number string number; do { number += *it; ++it; } while(it!=cend(jstr) && (isDigit(it) || *it=='.')); rt = make_shared<json>(std::strtod(number.c_str(), nullptr)); //TODO accuracy } else if(*it=='[') { // array vector<shared_ptr<json>> array; ++it; if(it==end(jstr)) return nullptr; else if(*it!=']') { while(true) { auto item = parse(); if(item==nullptr) return nullptr; array.emplace_back(item); if(match(',')) { continue; } else if(match(']')) { break; } else return nullptr; } } else ++it; rt = make_shared<json>(array); } else if(*it=='{') { // object vector<pair<string, shared_ptr<json>>> object; ++it; if(it==end(jstr)) return nullptr; else if(*it!='}') { while(true) { if(!match('"')) return nullptr; string key; while(true) { if(it==cend(jstr)) return nullptr; if(*it=='"') { ++it; break; } key += *it; ++it; } if(!match(':')) return nullptr; auto value = parse(); if(value==nullptr) return nullptr; object.emplace_back(key, value); if(match(',')) { continue; } else if(match('}')) { break; } else return nullptr; } } else ++it; rt = make_shared<json>(object); } else { switch(*it) { case 't': if(!match("true")) return nullptr; rt = make_shared<json>(true); break; case 'f': if(!match("false")) return nullptr; rt = make_shared<json>(false); break; case 'n': if(!match("null")) return nullptr; rt = make_shared<json>(); break; case '"': string value; while(true) { ++it; if(it==cend(jstr)) return nullptr; if(*it=='"') { ++it; break; } value += *it; } rt = make_shared<json>(value); break; } } return rt; } void parser::init(string file) { std::fstream fin(file); if(!fin.is_open()) { std::cerr << "Can't open the json file!" << std::endl; exit(1); } jstr.assign((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>()); it = cbegin(jstr); } void parser::genObject(shared_ptr<json> rt, int indent, string label) { assert(rt->getType()==JSON_OBJECT); auto object = rt->getObject(); indent++; fout << tab(indent-1) + "subgraph cluster" + std::to_string(subg_id++) + " {\n" + tab(indent) + "label = \"" + label + "\"\n" + tab(indent) + "color = black\n"; if(object.empty()) { // empty subgraph will not been shown fout << tab(indent) + std::to_string(node_id++) + " [style=\"invis\"]\n"; } else { for(auto& [key, value] : object) { fout << tab(indent) + "subgraph cluster" + std::to_string(subg_id++) + " {\n" + tab(indent+1) + "label = <<B><FONT COLOR=\"red\">" + key + "</FONT></B>>\n" + tab(indent+1) + "color = white\n"; if(value->isAtom()) genAtom(value, indent+1); else if(value->getType()==JSON_ARRAY) genArray(value, indent+1); else genObject(value, indent+1); fout << tab(indent) + "}\n"; } } fout << tab(indent-1) << "}\n"; } void parser::genArray(shared_ptr<json> value, int indent, string label) { assert(value->getType()==JSON_ARRAY); fout << tab(indent) + "subgraph cluster" + std::to_string(subg_id++) + " {\n" + tab(indent+1) + "label = \"" + label + "\"\n" + tab(indent+1) + "color = black\n"; auto array = value->getArray(); int idx = 0; for(auto& item : array) { if(item->isAtom()) { fout << tab(indent+1) + "subgraph cluster" + std::to_string(subg_id++) + " {\n" + tab(indent+2) + "label = \"[" + std::to_string(idx++) + "]\"\n" + tab(indent+2) + "color = black\n"; genAtom(item, indent+2); fout << tab(indent+1) << "}\n"; } else if(item->getType()==JSON_ARRAY) { genArray(item, indent+1, "["+std::to_string(idx++)+"]"); } else { genObject(item, indent+1, "["+std::to_string(idx++)+"]"); } } fout << tab(indent) + "}\n"; } void parser::genAtom(shared_ptr<json> value, int indent) { assert(value->isAtom()); switch(value->getType()) { case JSON_NULL: fout << tab(indent) + std::to_string(node_id++) + " [label=\"null\"]\n"; return; case JSON_BOOLEAN: fout << tab(indent) + std::to_string(node_id++) + " [label=\"" + (value->getB() ? "true" : "false") + "\"]\n"; return; case JSON_NUMBER: fout << tab(indent) + std::to_string(node_id++) + " [label=\"" + toString(value->getNum()) + "\"]\n"; return; default: //string fout << tab(indent) + std::to_string(node_id++) + " [label=\"" + value->getValue() + "\"]\n"; return; } } void parser::show(string file, string json_file) { fout.open(file, std::ios::out); if(!fout.is_open()) { std::cerr << "Can't open the file!" << std::endl; exit(1); } fout << "digraph {\n" + tab(1) + "node [shape=ellipse, color=cadetblue, style=filled]\n" + tab(1) + "label = \"" + json_file + "\"\n" + tab(1) + "edge [minlen=0.1]\n" + tab(1) + "compound = true\n"; genObject(rt, 1); fout << "}"; fout.close(); } int main(int argc, char *argv[]) { parser p; if(argc!=2) { std::cerr << "Please input the json file correctly!" << std::endl; return 1; } string json_file = argv[1]; p.init(json_file); p.rt = p.parse(); if(p.rt!=nullptr) { std::cout << p.rt->dump() << std::endl; p.show("tmp.dot", json_file); } return 0; }
29.945687
122
0.471567
[ "object", "shape", "vector" ]
e33f6c1058e13d6705e97b9151fb648a3bc8abbf
194,609
cpp
C++
tf2_src/utils/hlfaceposer/phonemeeditor.cpp
d3fc0n6/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/utils/hlfaceposer/phonemeeditor.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/utils/hlfaceposer/phonemeeditor.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //===========================================================================// #include <Assert.h> #include <stdio.h> #include <math.h> #include "hlfaceposer.h" #include "PhonemeEditor.h" #include "PhonemeEditorColors.h" #include "snd_audio_source.h" #include "snd_wave_source.h" #include "ifaceposersound.h" #include "choreowidgetdrawhelper.h" #include "mxBitmapButton.h" #include "phonemeproperties.h" #include "tier2/riff.h" #include "StudioModel.h" #include "expressions.h" #include "expclass.h" #include "InputProperties.h" #include "phonemeextractor/PhonemeExtractor.h" #include "PhonemeConverter.h" #include "choreoevent.h" #include "choreoscene.h" #include "ChoreoView.h" #include "filesystem.h" #include "UtlBuffer.h" #include "AudioWaveOutput.h" #include "StudioModel.h" #include "viewerSettings.h" #include "ControlPanel.h" #include "faceposer_models.h" #include "tier1/strtools.h" #include "tabwindow.h" #include "MatSysWin.h" #include "soundflags.h" #include "mdlviewer.h" #include "filesystem_init.h" #include "WaveBrowser.h" #include "tier2/p4helpers.h" #include "vstdlib/random.h" extern IUniformRandomStream *random; float SnapTime( float input, float granularity ); #define MODE_TAB_OFFSET 20 // 10x magnification #define MAX_TIME_ZOOM 1000 // 10% per step #define TIME_ZOOM_STEP 2 #define SCRUBBER_HEIGHT 15 #define TAG_TOP ( 25 + SCRUBBER_HEIGHT ) #define TAG_BOTTOM ( TAG_TOP + 20 ) #define PLENTY_OF_TIME 99999.9 #define MINIMUM_WORD_GAP 0.02f #define MINIMUM_PHONEME_GAP 0.01f #define DEFAULT_WORD_LENGTH 0.25f #define DEFAULT_PHONEME_LENGTH 0.1f #define WORD_DATA_EXTENSION ".txt" // #define ITEM_GAP_EPSILON 0.0025f struct PhonemeEditorColor { int color_number; // For readability int mode_number; // -1 for all COLORREF root_color; COLORREF gray_color; // if mode is wrong... }; static PhonemeEditorColor g_PEColors[ NUM_COLORS ] = { { COLOR_PHONEME_BACKGROUND, -1, RGB( 240, 240, 220 ) }, { COLOR_PHONEME_TEXT, -1, RGB( 63, 63, 63 ) }, { COLOR_PHONEME_LIGHTTEXT, 0, RGB( 180, 180, 120 ) }, { COLOR_PHONEME_PLAYBACKTICK, 0, RGB( 255, 0, 0 ) }, { COLOR_PHONEME_WAVDATA, 0, RGB( 128, 31, 63 ) }, { COLOR_PHONEME_TIMELINE, 0, RGB( 31, 31, 127 ) }, { COLOR_PHONEME_TIMELINE_MAJORTICK, 0, RGB( 200, 200, 255 ) }, { COLOR_PHONEME_TIMELINE_MINORTICK, 0, RGB( 210, 210, 240 ) }, { COLOR_PHONEME_EXTRACTION_RESULT_FAIL, 0, RGB( 180, 180, 0 ) }, { COLOR_PHONEME_EXTRACTION_RESULT_SUCCESS, 0, RGB( 100, 180, 100 ) }, { COLOR_PHONEME_EXTRACTION_RESULT_ERROR, 0, RGB( 255, 31, 31 ) }, { COLOR_PHONEME_EXTRACTION_RESULT_OTHER, 0, RGB( 63, 63, 63 ) }, { COLOR_PHONEME_TAG_BORDER, 0, RGB( 160, 100, 100 ) }, { COLOR_PHONEME_TAG_BORDER_SELECTED, 0, RGB( 255, 40, 60 ) }, { COLOR_PHONEME_TAG_FILLER_NORMAL, 0, RGB( 210, 210, 190 ) }, { COLOR_PHONEME_TAG_SELECTED, 0, RGB( 200, 130, 130 ) }, { COLOR_PHONEME_TAG_TEXT, 0, RGB( 63, 63, 63 ) }, { COLOR_PHONEME_TAG_TEXT_SELECTED, 0, RGB( 250, 250, 250 ) }, { COLOR_PHONEME_WAV_ENDPOINT, 0, RGB( 0, 0, 200 ) }, { COLOR_PHONEME_AB, 0, RGB( 63, 190, 210 ) }, { COLOR_PHONEME_AB_LINE, 0, RGB( 31, 150, 180 ) }, { COLOR_PHONEME_AB_TEXT, 0, RGB( 100, 120, 120 ) }, { COLOR_PHONEME_ACTIVE_BORDER, 0, RGB( 150, 240, 180 ) }, { COLOR_PHONEME_SELECTED_BORDER, 0, RGB( 255, 0, 0 ) }, { COLOR_PHONEME_TIMING_TAG, -1, RGB( 0, 100, 200 ) }, { COLOR_PHONEME_EMPHASIS_BG, 1, RGB( 230, 230, 200 ) }, { COLOR_PHONEME_EMPHASIS_BG_STRONG, 1, RGB( 163, 201, 239 ) }, { COLOR_PHONEME_EMPHASIS_BG_WEAK, 1, RGB( 237, 239, 163 ) }, { COLOR_PHONEME_EMPHASIS_BORDER, 1, RGB( 200, 200, 200 ) }, { COLOR_PHONEME_EMPHASIS_LINECOLOR, 1, RGB( 0, 0, 255 ) }, { COLOR_PHONEME_EMPHASIS_DOTCOLOR, 1, RGB( 0, 0, 255 ) }, { COLOR_PHONEME_EMPHASIS_DOTCOLOR_SELECTED, 1, RGB( 240, 80, 20 ) }, { COLOR_PHONEME_EMPHASIS_TEXT, 1, RGB( 0, 0, 0 ) }, { COLOR_PHONEME_EMPHASIS_MIDLINE, 1, RGB( 100, 150, 200 ) }, }; struct Extractor { PE_APITYPE apitype; CSysModule *module; IPhonemeExtractor *extractor; }; CUtlVector< Extractor > g_Extractors; bool DoesExtractorExistFor( PE_APITYPE type ) { for ( int i=0; i < g_Extractors.Count(); i++ ) { if ( g_Extractors[i].apitype == type ) return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Implements the RIFF i/o interface on stdio //----------------------------------------------------------------------------- class StdIOReadBinary : public IFileReadBinary { public: int open( const char *pFileName ) { return (int)filesystem->Open( pFileName, "rb" ); } int read( void *pOutput, int size, int file ) { if ( !file ) return 0; return filesystem->Read( pOutput, size, (FileHandle_t)file ); } void seek( int file, int pos ) { if ( !file ) return; filesystem->Seek( (FileHandle_t)file, pos, FILESYSTEM_SEEK_HEAD ); } unsigned int tell( int file ) { if ( !file ) return 0; return filesystem->Tell( (FileHandle_t)file ); } unsigned int size( int file ) { if ( !file ) return 0; return filesystem->Size( (FileHandle_t)file ); } void close( int file ) { if ( !file ) return; filesystem->Close( (FileHandle_t)file ); } }; class StdIOWriteBinary : public IFileWriteBinary { public: int create( const char *pFileName ) { MakeFileWriteable( pFileName ); return (int)filesystem->Open( pFileName, "wb" ); } int write( void *pData, int size, int file ) { return filesystem->Write( pData, size, (FileHandle_t)file ); } void close( int file ) { filesystem->Close( (FileHandle_t)file ); } void seek( int file, int pos ) { filesystem->Seek( (FileHandle_t)file, pos, FILESYSTEM_SEEK_HEAD ); } unsigned int tell( int file ) { return filesystem->Tell( (FileHandle_t)file ); } }; // Interface objects static StdIOWriteBinary io_out; static StdIOReadBinary io_in; class CPhonemeModeTab : public CTabWindow { public: typedef CTabWindow BaseClass; CPhonemeModeTab( mxWindow *parent, int x, int y, int w, int h, int id = 0, int style = 0 ) : CTabWindow( parent, x, y, w, h, id, style ) { SetInverted( true ); } virtual void ShowRightClickMenu( int mx, int my ) { // Nothing } void Init( void ) { add( "Phonemes" ); add( "Emphasis" ); select( 0 ); } }; PhonemeEditor * g_pPhonemeEditor = 0; //----------------------------------------------------------------------------- // Purpose: // Input : *parent - //----------------------------------------------------------------------------- PhonemeEditor::PhonemeEditor( mxWindow *parent ) : IFacePoserToolWindow( "PhonemeEditor", "Phoneme Editor" ), mxWindow( parent, 0, 0, 0, 0 ) { SetAutoProcess( false ); m_flPlaybackRate = 1.0f; m_flScrub = 0.0f; m_flScrubTarget = 0.0f; m_CurrentMode = MODE_PHONEMES; Emphasis_Init(); SetupPhonemeEditorColors(); m_bRedoPending = false; m_nUndoLevel = 0; m_bWordsActive = false; m_pWaveFile = NULL; m_pMixer = NULL; m_pEvent = NULL; m_nClickX = 0; m_WorkFile.m_bDirty = false; m_WorkFile.m_szWaveFile[ 0 ] = 0; m_WorkFile.m_szWorkingFile[ 0 ] = 0; m_WorkFile.m_szBasePath[ 0 ] = 0; m_nTickHeight = 20; m_flPixelsPerSecond = 500.0f; m_nTimeZoom = 100; m_nTimeZoomStep = TIME_ZOOM_STEP; m_pHorzScrollBar = new mxScrollbar( this, 0, 0, 18, 100, IDC_PHONEME_SCROLL, mxScrollbar::Horizontal ); m_hPrevCursor = 0; m_nStartX = 0; m_nStartY = 0; m_nLastX = 0; m_nLastY = 0; m_nDragType = DRAGTYPE_NONE; SetClickedPhoneme( -1, -1 ); m_nSelection[ 0 ] = m_nSelection[ 1 ] = 0; m_bSelectionActive = false; m_nSelectedPhonemeCount = 0; m_nSelectedWordCount = 0; m_btnSave = new mxButton( this, 0, 0, 16, 16, "Save (Ctrl+S)", IDC_SAVE_LINGUISTIC ); m_btnRedoPhonemeExtraction = new mxButton( this, 38, 14, 80, 16, "Re-extract (Ctrl+R)", IDC_REDO_PHONEMEEXTRACTION ); m_btnLoad = new mxButton( this, 0, 0, 0, 0, "Load (Ctrl+O)", IDC_LOADWAVEFILE ); m_btnPlay = new mxButton( this, 0, 0, 16, 16, "Play (Spacebar)", IDC_PLAYBUTTON ); m_pPlaybackRate = new mxSlider( this, 0, 0, 16, 16, IDC_PLAYBACKRATE ); m_pPlaybackRate->setRange( 0.0, 2.0, 40 ); m_pPlaybackRate->setValue( m_flPlaybackRate ); m_pModeTab = new CPhonemeModeTab( this, 0, 0, 500, 20, IDC_MODE_TAB ); m_pModeTab->Init(); m_nLastExtractionResult = SR_RESULT_NORESULT; ClearDragLimit(); SetSuffix( " - Normal" ); m_flScrubberTimeOffset = 0.0f; LoadPhonemeConverters(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::OnDelete() { if ( m_pWaveFile ) { char fn[ 512 ]; Q_snprintf( fn, sizeof( fn ), "%s%s", m_WorkFile.m_szBasePath, m_WorkFile.m_szWorkingFile ); filesystem->RemoveFile( fn, "GAME" ); } delete m_pWaveFile; m_pWaveFile = NULL; m_Tags.Reset(); m_TagsExt.Reset(); UnloadPhonemeConverters(); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::CanClose() { if ( !GetDirty() ) return true; int retval = mxMessageBox( this, va( "Save current changes to %s", m_WorkFile.m_szWaveFile ), "Phoneme Editor", MX_MB_QUESTION | MX_MB_YESNOCANCEL ); // Cancel if ( retval == 2 ) { return false; } // Yes if ( retval == 0 ) { CommitChanges(); } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- PhonemeEditor::~PhonemeEditor( void ) { } void PhonemeEditor::SetupPhonemeEditorColors( void ) { int i; for ( i = 0; i < NUM_COLORS; i++ ) { PhonemeEditorColor *p = &g_PEColors[ i ]; Assert( p->color_number == i ); if ( p->mode_number == -1 ) { p->gray_color = p->root_color; } else { COLORREF bgColor = g_PEColors[ COLOR_PHONEME_BACKGROUND ].root_color; int bgr, bgg, bgb; bgr = GetRValue( bgColor ); bgg = GetGValue( bgColor ); bgb = GetBValue( bgColor ); int r, g, b; r = GetRValue( p->root_color ); g = GetGValue( p->root_color ); b = GetBValue( p->root_color ); int avg = ( r + g + b ) / 3; int bgavg = ( bgr + bgg + bgb ) / 3; // Bias toward bg color avg += ( bgavg - avg ) / 2.5; p->gray_color = RGB( avg, avg, avg ); } } } COLORREF PhonemeEditor::PEColor( int colornum ) { COLORREF clr = RGB( 0, 0, 0 ); if ( colornum < 0 || colornum >= NUM_COLORS ) { Assert( 0 ); return clr; } PhonemeEditorColor *p = &g_PEColors[ colornum ]; if ( p->mode_number == -1 ) { return p->root_color; } int modenum = (int)GetMode(); if ( p->mode_number == modenum ) { return p->root_color; } return p->gray_color; } void PhonemeEditor::EditWord( CWordTag *pWord, bool positionDialog /*= false*/ ) { if ( !pWord ) { Con_Printf( "PhonemeEditor::EditWord: pWord == NULL\n" ); return; } CInputParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Edit Word" ); strcpy( params.m_szPrompt, "Current Word:" ); V_strcpy_safe( params.m_szInputText, pWord->GetWord() ); params.m_nLeft = -1; params.m_nTop = -1; params.m_bPositionDialog = positionDialog; if ( params.m_bPositionDialog ) { RECT rcWord; GetWordRect( pWord, rcWord ); // Convert to screen coords POINT pt; pt.x = rcWord.left; pt.y = rcWord.top; ClientToScreen( (HWND)getHandle(), &pt ); params.m_nLeft = pt.x; params.m_nTop = pt.y; } int iret = InputProperties( &params ); SetFocus( (HWND)getHandle() ); if ( !iret ) { return; } // Validate parameters if ( CSentence::CountWords( params.m_szInputText ) != 1 ) { Con_ErrorPrintf( "Edit word: %s has multiple words in it!!!\n", params.m_szInputText ); return; } SetFocus( (HWND)getHandle() ); SetDirty( true ); PushUndo(); // Set the word and clear out the phonemes // ->m_nPhonemeCode = TextToPhoneme( params.m_szName ); pWord->SetWord( params.m_szInputText ); PushRedo(); redraw(); } //----------------------------------------------------------------------------- // Purpose: // Input : *pPhoneme - // positionDialog - //----------------------------------------------------------------------------- void PhonemeEditor::EditPhoneme( CPhonemeTag *pPhoneme, bool positionDialog /*= false*/ ) { if ( !pPhoneme ) { Con_Printf( "PhonemeEditor::EditPhoneme: pPhoneme == NULL\n" ); return; } CPhonemeParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Phoneme/Viseme Properties" ); V_strcpy_safe( params.m_szName, ConvertPhoneme( pPhoneme->GetPhonemeCode() ) ); params.m_nLeft = -1; params.m_nTop = -1; params.m_bPositionDialog = positionDialog; if ( params.m_bPositionDialog ) { RECT rcPhoneme; GetPhonemeRect( pPhoneme, rcPhoneme ); // Convert to screen coords POINT pt; pt.x = rcPhoneme.left; pt.y = rcPhoneme.top; ClientToScreen( (HWND)getHandle(), &pt ); params.m_nLeft = pt.x; params.m_nTop = pt.y; } int iret = PhonemeProperties( &params ); SetFocus( (HWND)getHandle() ); if ( !iret ) { return; } SetDirty( true ); PushUndo(); pPhoneme->SetPhonemeCode( TextToPhoneme( params.m_szName ) ); PushRedo(); redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditPhoneme( void ) { if ( GetMode() != MODE_PHONEMES ) return; CPhonemeTag *pPhoneme = GetClickedPhoneme(); if ( !pPhoneme ) return; EditPhoneme( pPhoneme, false ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditWord( void ) { if ( GetMode() != MODE_PHONEMES ) return; CWordTag *pWord = GetClickedWord(); if ( !pWord ) return; EditWord( pWord, false ); } //----------------------------------------------------------------------------- // Purpose: // Input : dragtype - // startx - // cursor - //----------------------------------------------------------------------------- void PhonemeEditor::StartDragging( int dragtype, int startx, int starty, HCURSOR cursor ) { m_nDragType = dragtype; m_nStartX = startx; m_nLastX = startx; m_nStartY = starty; m_nLastY = starty; if ( m_hPrevCursor ) { SetCursor( m_hPrevCursor ); m_hPrevCursor = NULL; } m_hPrevCursor = SetCursor( cursor ); m_FocusRects.Purge(); RECT rc; GetWorkspaceRect( rc ); RECT rcStart; rcStart.left = startx; rcStart.right = startx; bool addrect = true; switch ( dragtype ) { default: case DRAGTYPE_SCRUBBER: { RECT rcScrub; GetScrubHandleRect( rcScrub, true ); rcStart = rcScrub; rcStart.left = ( rcScrub.left + rcScrub.right ) / 2; rcStart.right = rcStart.left; rcStart.bottom = h2() - 18 - MODE_TAB_OFFSET; } break; case DRAGTYPE_EMPHASIS_SELECT: { RECT rcEmphasis; Emphasis_GetRect( rc, rcEmphasis ); rcStart.top = starty; rcStart.bottom = starty; } break; case DRAGTYPE_EMPHASIS_MOVE: { SetDirty( true ); PushUndo(); Emphasis_MouseDrag( startx, starty ); m_Tags.Resort(); addrect = false; } break; case DRAGTYPE_SELECTSAMPLES: case DRAGTYPE_MOVESELECTIONSTART: case DRAGTYPE_MOVESELECTIONEND: rcStart.top = rc.top; rcStart.bottom = rc.bottom; break; case DRAGTYPE_MOVESELECTION: { rcStart.top = rc.top; rcStart.bottom = rc.bottom; // Compute left/right pixels for selection rcStart.left = GetPixelForSample( m_nSelection[ 0 ] ); rcStart.right = GetPixelForSample( m_nSelection[ 1 ] ); } break; case DRAGTYPE_PHONEME: { GetPhonemeTrayTopBottom( rcStart ); m_bWordsActive = false; } break; case DRAGTYPE_WORD: { GetWordTrayTopBottom( rcStart ); m_bWordsActive = true; } break; case DRAGTYPE_MOVEWORD: { TraverseWords( &PhonemeEditor::ITER_AddFocusRectSelectedWords, 0.0f ); addrect = false; m_bWordsActive = true; } break; case DRAGTYPE_MOVEPHONEME: { TraversePhonemes( &PhonemeEditor::ITER_AddFocusRectSelectedPhonemes, 0.0f ); addrect = false; m_bWordsActive = false; } break; case DRAGTYPE_EVENTTAG_MOVE: { rcStart.top = TAG_TOP; rcStart.bottom = TAG_BOTTOM; rcStart.left -= 10; rcStart.right += 10; } break; } if ( addrect ) { AddFocusRect( rcStart ); } DrawFocusRect( "start" ); SetDragLimit( m_nDragType ); } //----------------------------------------------------------------------------- // Purpose: // Input : *event - // Output : int //----------------------------------------------------------------------------- int PhonemeEditor::handleEvent( mxEvent *event ) { MDLCACHE_CRITICAL_SECTION_( g_pMDLCache ); int iret = 0; if ( HandleToolEvent( event ) ) { return iret; } switch ( event->event ) { case mxEvent::Action: { iret = 1; switch ( event->action ) { case IDC_EXPORT_SENTENCE: { OnExport(); } break; case IDC_IMPORT_SENTENCE: { OnImport(); } break; case IDC_PLAYBACKRATE: { m_flPlaybackRate = m_pPlaybackRate->getValue(); redraw(); } break; case IDC_MODE_TAB: { // The mode changed, so reset stuff here EditorMode newMode = (EditorMode)m_pModeTab->getSelectedIndex(); bool needpaint = ( m_CurrentMode != newMode ); m_CurrentMode = newMode; if ( needpaint ) { switch ( GetMode() ) { default: case MODE_PHONEMES: SetSuffix( " - Normal" ); break; case MODE_EMPHASIS: SetSuffix( " - Emphasis Track" ); break; } OnModeChanged(); redraw(); } } break; case IDC_EMPHASIS_DELETE: Emphasis_Delete(); break; case IDC_EMPHASIS_DESELECT: Emphasis_DeselectAll(); break; case IDC_EMPHASIS_SELECTALL: Emphasis_SelectAll(); break; case IDC_API_SAPI: OnSAPI(); break; case IDC_API_LIPSINC: OnLipSinc(); break; case IDC_PLAYBUTTON: Play(); break; case IDC_UNDO: Undo(); break; case IDC_REDO: Redo(); break; case IDC_CLEARUNDO: ClearUndo(); break; case IDC_ADDTAG: AddTag(); break; case IDC_DELETETAG: DeleteTag(); break; case IDC_COMMITEXTRACTED: CommitExtracted(); SetFocus( (HWND)getHandle() ); break; case IDC_CLEAREXTRACTED: ClearExtracted(); break; case IDC_SEPARATEPHONEMES: SeparatePhonemes(); break; case IDC_SNAPPHONEMES: SnapPhonemes(); break; case IDC_SEPARATEWORDS: SeparateWords(); break; case IDC_SNAPWORDS: SnapWords(); break; case IDC_EDITWORDLIST: EditWordList(); break; case IDC_EDIT_PHONEME: EditPhoneme(); break; case IDC_EDIT_WORD: EditWord(); break; case IDC_EDIT_INSERTPHONEMEBEFORE: EditInsertPhonemeBefore(); break; case IDC_EDIT_INSERTPHONEMEAFTER: EditInsertPhonemeAfter(); break; case IDC_EDIT_INSERTWORDBEFORE: EditInsertWordBefore(); break; case IDC_EDIT_INSERTWORDAFTER: EditInsertWordAfter(); break; case IDC_EDIT_DELETEPHONEME: EditDeletePhoneme(); break; case IDC_EDIT_DELETEWORD: EditDeleteWord(); break; case IDC_EDIT_INSERTFIRSTPHONEMEOFWORD: EditInsertFirstPhonemeOfWord(); break; case IDC_PHONEME_PLAY_ORIG: { StopPlayback(); if ( m_pWaveFile ) { // Make sure phonemes are loaded FacePoser_EnsurePhonemesLoaded(); sound->PlaySound( m_pWaveFile, VOL_NORM, &m_pMixer ); } } break; case IDC_PHONEME_SCROLL: if (event->modifiers == SB_THUMBTRACK) { MoveTimeSliderToPos( event->height ); } else if ( event->modifiers == SB_PAGEUP ) { int offset = m_pHorzScrollBar->getValue(); offset -= 10; offset = max( offset, m_pHorzScrollBar->getMinValue() ); MoveTimeSliderToPos( offset ); } else if ( event->modifiers == SB_PAGEDOWN ) { int offset = m_pHorzScrollBar->getValue(); offset += 10; offset = min( offset, m_pHorzScrollBar->getMaxValue() ); MoveTimeSliderToPos( offset ); } break; case IDC_REDO_PHONEMEEXTRACTION: if ( m_Tags.m_Words.Size() <= 0 ) { // This calls redo LISET if some words are actually entered EditWordList(); } else { RedoPhonemeExtraction(); } SetFocus( (HWND)getHandle() ); break; case IDC_REDO_PHONEMEEXTRACTION_SELECTION: { RedoPhonemeExtractionSelected(); } SetFocus( (HWND)getHandle() ); break; case IDC_DESELECT: Deselect(); redraw(); break; case IDC_PLAY_EDITED: PlayEditedWave( false ); SetFocus( (HWND)getHandle() ); break; case IDC_PLAY_EDITED_SELECTION: PlayEditedWave( true ); SetFocus( (HWND)getHandle() ); break; case IDC_SAVE_LINGUISTIC: CommitChanges(); SetFocus( (HWND)getHandle() ); break; case IDC_LOADWAVEFILE: LoadWaveFile(); SetFocus( (HWND)getHandle() ); break; case IDC_CANCELPLAYBACK: StopPlayback(); SetFocus( (HWND)getHandle() ); break; case IDC_SELECT_WORDSRIGHT: SelectWords( true ); break; case IDC_SELECT_WORDSLEFT: SelectWords( false ); break; case IDC_SELECT_PHONEMESRIGHT: SelectPhonemes( true ); break; case IDC_SELECT_PHONEMESLEFT: SelectPhonemes( false ); break; case IDC_DESELECT_PHONEMESANDWORDS: DeselectPhonemes(); DeselectWords(); redraw(); break; case IDC_CLEANUP: CleanupWordsAndPhonemes( true ); redraw(); break; case IDC_REALIGNPHONEMES: RealignPhonemesToWords( true ); redraw(); break; case IDC_REALIGNWORDS: RealignWordsToPhonemes( true ); redraw(); break; case IDC_TOGGLE_VOICEDUCK: OnToggleVoiceDuck(); break; } if ( iret == 1 ) { SetActiveTool( this ); SetFocus( (HWND)getHandle() ); } } break; case mxEvent::MouseWheeled: { // Zoom time in / out if ( event->height > 0 ) { m_nTimeZoom = min( m_nTimeZoom + m_nTimeZoomStep, MAX_TIME_ZOOM ); } else { m_nTimeZoom = max( m_nTimeZoom - m_nTimeZoomStep, m_nTimeZoomStep ); } RepositionHSlider(); iret = 1; } break; case mxEvent::Size: { int bw = 100; int x = 5; int by = h2() - 18 - MODE_TAB_OFFSET; m_pModeTab->setBounds( 0, h2() - MODE_TAB_OFFSET, w2(), MODE_TAB_OFFSET ); m_btnRedoPhonemeExtraction->setBounds( x, by, bw, 16 ); x += bw; m_btnSave->setBounds( x, by, bw, 16 ); x += bw; m_btnLoad->setBounds( x, by, bw, 16 ); x += bw; m_btnPlay->setBounds( x, by, bw, 16 ); x += bw; m_pPlaybackRate->setBounds( x, by, 100, 16 ); RepositionHSlider(); iret = 1; } break; case mxEvent::MouseDown: { iret = 1; CPhonemeTag *pt; CWordTag *wt; pt = GetPhonemeTagUnderMouse( (short)event->x, (short)event->y ); wt = GetWordTagUnderMouse( (short)event->x, (short)event->y ); bool ctrldown = ( event->modifiers & mxEvent::KeyCtrl ) ? true : false; bool shiftdown = ( event->modifiers & mxEvent::KeyShift ) ? true : false; if ( event->buttons & mxEvent::MouseRightButton ) { RECT rc; GetWorkspaceRect( rc ); if ( IsMouseOverWordRow( (short)event->y ) ) { ShowWordMenu( wt, (short)event->x, (short)event->y ); } else if ( IsMouseOverPhonemeRow( (short)event->y ) ) { ShowPhonemeMenu( pt, (short)event->x, (short)event->y ); } else if ( IsMouseOverTagRow( (short)event->y ) ) { ShowTagMenu( (short)event->x, (short)event->y ); } else if ( IsMouseOverScrubArea( event ) ) { float t = GetTimeForPixel( (short)event->x ); ClampTimeToSelectionInterval( t ); SetScrubTime( t ); SetScrubTargetTime( t ); redraw(); } else { ShowContextMenu( (short)event->x, (short)event->y ); } return iret; } if ( m_nDragType == DRAGTYPE_NONE ) { CountSelected(); int type = IsMouseOverBoundary( event ); if ( IsMouseOverScrubArea( event ) ) { if ( IsMouseOverScrubHandle( event ) ) { StartDragging( DRAGTYPE_SCRUBBER, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEWE ) ); float t = GetTimeForPixel( (short)event->x ); m_flScrubberTimeOffset = m_flScrub - t; float maxoffset = 0.5f * (float)SCRUBBER_HANDLE_WIDTH / GetPixelsPerSecond(); m_flScrubberTimeOffset = clamp( m_flScrubberTimeOffset, -maxoffset, maxoffset ); t += m_flScrubberTimeOffset; ClampTimeToSelectionInterval( t ); SetScrubTime( t ); SetScrubTargetTime( t ); DrawScrubHandle(); iret = true; } else { float t = GetTimeForPixel( (short)event->x ); ClampTimeToSelectionInterval( t ); SetScrubTargetTime( t ); iret = true; } return iret; } else if ( GetMode() == MODE_EMPHASIS ) { CEmphasisSample *sample = Emphasis_GetSampleUnderMouse( event ); if ( sample ) { if ( shiftdown ) { sample->selected = !sample->selected; redraw(); } else if ( sample->selected ) { StartDragging( DRAGTYPE_EMPHASIS_MOVE, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEALL ) ); } else { if ( !shiftdown ) { Emphasis_DeselectAll(); redraw(); } StartDragging( DRAGTYPE_EMPHASIS_SELECT, (short)event->x, (short)event->y, NULL ); } return true; } else if ( ctrldown ) { // Add a sample point float t = GetTimeForPixel( (short)event->x ); RECT rcWork; GetWorkspaceRect( rcWork ); RECT rcEmphasis; Emphasis_GetRect( rcWork, rcEmphasis ); int eh = rcEmphasis.bottom - rcEmphasis.top; int dy = (short)event->y - rcEmphasis.top; CEmphasisSample sample; sample.time = t; Assert( eh >= 0 ); sample.value = (float)( dy ) / ( float ) eh; sample.value = 1.0f - clamp( sample.value, 0.0f, 1.0f ); sample.selected = false; Emphasis_AddSample( sample ); redraw(); return true; } else { if ( !shiftdown ) { Emphasis_DeselectAll(); redraw(); } StartDragging( DRAGTYPE_EMPHASIS_SELECT, (short)event->x, (short)event->y, NULL ); return true; } } else { if ( type == BOUNDARY_PHONEME && m_nSelectedPhonemeCount <= 1 ) { StartDragging( DRAGTYPE_PHONEME, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEWE ) ); return true; } else if ( type == BOUNDARY_WORD && m_nSelectedWordCount <= 1 ) { StartDragging( DRAGTYPE_WORD, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEWE ) ); return true; } else if ( IsMouseOverSamples( (short)event->x, (short)event->y ) ) { if ( !m_bSelectionActive ) { StartDragging( DRAGTYPE_SELECTSAMPLES, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEWE ) ); } else { // Either move, move edge if ctrl key is held, or deselect if ( IsMouseOverSelection( (short)event->x, (short)event->y ) ) { if ( IsMouseOverSelectionStartEdge( event ) ) { StartDragging( DRAGTYPE_MOVESELECTIONSTART, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEWE ) ); } else if ( IsMouseOverSelectionEndEdge( event ) ) { StartDragging( DRAGTYPE_MOVESELECTIONEND, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEWE ) ); } else { if ( shiftdown ) { StartDragging( DRAGTYPE_MOVESELECTION, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEALL ) ); } } } else { Deselect(); redraw(); return iret; } } return true; } } if ( IsMouseOverTag( (short)event->x, (short)event->y ) ) { StartDragging( DRAGTYPE_EVENTTAG_MOVE, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEALL ) ); return true; } else { if ( pt ) { // Can only move when holding down shift key if ( shiftdown ) { pt->m_bSelected = true; StartDragging( DRAGTYPE_MOVEPHONEME, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEALL ) ); } else { // toggle the selection pt->m_bSelected = !pt->m_bSelected; } m_bWordsActive = false; redraw(); return true; } else if ( wt ) { // Can only move when holding down shift key if ( shiftdown ) { wt->m_bSelected = true; StartDragging( DRAGTYPE_MOVEWORD, (short)event->x, (short)event->y, LoadCursor( NULL, IDC_SIZEALL ) ); } else { // toggle the selection wt->m_bSelected = !wt->m_bSelected; } m_bWordsActive = true; redraw(); return true; } else if ( type == BOUNDARY_NONE ) { DeselectPhonemes(); DeselectWords(); redraw(); return true; } } } } break; case mxEvent::MouseMove: case mxEvent::MouseDrag: { OnMouseMove( event ); iret = 1; } break; case mxEvent::MouseUp: { if ( m_nDragType != DRAGTYPE_NONE ) { int mx = (short)event->x; LimitDrag( mx ); event->x = (short)mx; DrawFocusRect( "finish" ); if ( m_hPrevCursor ) { SetCursor( m_hPrevCursor ); m_hPrevCursor = 0; } switch ( m_nDragType ) { case DRAGTYPE_WORD: FinishWordMove( m_nStartX, (short)event->x ); break; case DRAGTYPE_PHONEME: FinishPhonemeMove( m_nStartX, (short)event->x ); break; case DRAGTYPE_SELECTSAMPLES: FinishSelect( m_nStartX, (short)event->x ); break; case DRAGTYPE_MOVESELECTION: FinishMoveSelection( m_nStartX, (short)event->x ); break; case DRAGTYPE_MOVESELECTIONSTART: FinishMoveSelectionStart( m_nStartX, (short)event->x ); break; case DRAGTYPE_MOVESELECTIONEND: FinishMoveSelectionEnd( m_nStartX, (short)event->x ); break; case DRAGTYPE_MOVEWORD: FinishWordDrag( m_nStartX, (short)event->x ); break; case DRAGTYPE_MOVEPHONEME: FinishPhonemeDrag( m_nStartX, (short)event->x ); break; case DRAGTYPE_EVENTTAG_MOVE: FinishEventTagDrag( m_nStartX, (short)event->x ); break; case DRAGTYPE_EMPHASIS_MOVE: { Emphasis_MouseDrag( (short)event->x, (short)event->y ); m_Tags.Resort(); PushRedo(); redraw(); } break; case DRAGTYPE_EMPHASIS_SELECT: { Emphasis_SelectPoints(); redraw(); } break; case DRAGTYPE_SCRUBBER: { float t = GetTimeForPixel( (short)event->x ); t += m_flScrubberTimeOffset; m_flScrubberTimeOffset = 0.0f; ClampTimeToSelectionInterval( t ); SetScrubTime( t ); SetScrubTargetTime( t ); sound->Flush(); DrawScrubHandle(); } break; default: break; } m_nDragType = DRAGTYPE_NONE; } iret = 1; } break; case mxEvent::KeyUp: { bool shiftDown = GetAsyncKeyState( VK_SHIFT ) ? true : false; bool ctrlDown = GetAsyncKeyState( VK_CONTROL ) ? true : false; switch( event->key ) { case VK_TAB: { int direction = shiftDown ? -1 : 1; SelectNextWord( direction ); } break; case VK_NEXT: case VK_PRIOR: { m_bWordsActive = event->key == VK_PRIOR ? true : false; redraw(); } break; case VK_UP: case VK_RETURN: if ( m_bWordsActive ) { if ( event->key == VK_UP || ctrlDown ) { CountSelected(); if ( m_nSelectedWordCount == 1 ) { // Find the selected one for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word || !word->m_bSelected ) continue; EditWord( word, true ); } } } } else { if ( event->key == VK_UP || ctrlDown ) { CountSelected(); if ( m_nSelectedPhonemeCount == 1 ) { // Find the selected one for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; for ( int j = 0; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *phoneme = word->m_Phonemes[ j ]; if ( !phoneme ) continue; if ( !phoneme->m_bSelected ) continue; EditPhoneme( phoneme, true ); } } } } } break; case VK_DELETE: if ( GetMode() == MODE_EMPHASIS ) { Emphasis_Delete(); } else { if ( m_bWordsActive ) { EditDeleteWord(); } else { EditDeletePhoneme(); } } break; case VK_INSERT: if ( m_bWordsActive ) { if ( shiftDown ) { EditInsertWordBefore(); } else { EditInsertWordAfter(); } } else { if ( shiftDown ) { EditInsertPhonemeBefore(); } else { EditInsertPhonemeAfter(); } } break; case VK_SPACE: if ( m_pWaveFile && sound->IsSoundPlaying( m_pMixer ) ) { Con_Printf( "Stopping playback\n" ); m_btnPlay->setLabel( "Play (Spacebar)" ); StopPlayback(); } else { Con_Printf( "Playing .wav\n" ); m_btnPlay->setLabel( "Stop[ (Spacebar)" ); PlayEditedWave( m_bSelectionActive ); } break; case VK_SHIFT: case VK_CONTROL: { // Force mouse move POINT pt; GetCursorPos( &pt ); SetCursorPos( pt.x, pt.y ); return 0; } break; case VK_ESCAPE: { // If playing sound, stop it, otherwise, deselect all if ( !StopPlayback() ) { Deselect(); DeselectPhonemes(); DeselectWords(); Emphasis_DeselectAll(); redraw(); } } break; case 'O': { if ( ctrlDown ) { LoadWaveFile(); } } break; case 'S': { if ( ctrlDown ) { CommitChanges(); } } break; case 'T': { if ( ctrlDown ) { // Edit sentence text EditWordList(); } } break; case 'G': { if ( ctrlDown ) { // Commit extraction CommitExtracted(); } } break; case 'R': { if ( ctrlDown ) { RedoPhonemeExtraction(); } } break; default: break; } SetFocus( (HWND)getHandle() ); iret = 1; } break; case mxEvent::KeyDown: { switch ( event->key ) { case 'Z': if ( GetAsyncKeyState( VK_CONTROL ) ) { Undo(); } break; case 'Y': if ( GetAsyncKeyState( VK_CONTROL ) ) { Redo(); } break; case VK_RIGHT: case VK_LEFT: { int direction = event->key == VK_LEFT ? -1 : 1; if ( !m_bWordsActive ) { if ( GetAsyncKeyState( VK_CONTROL ) ) { ExtendSelectedPhonemeEndTime( direction ); } else if ( GetAsyncKeyState( VK_SHIFT ) ) { ShiftSelectedPhoneme( direction ); } else { SelectNextPhoneme( direction ); } } else { if ( GetAsyncKeyState( VK_CONTROL ) ) { ExtendSelectedWordEndTime( direction ); } else if ( GetAsyncKeyState( VK_SHIFT ) ) { ShiftSelectedWord( direction ); } else { SelectNextWord( direction ); } } } break; case VK_RETURN: { } break; case VK_SHIFT: case VK_CONTROL: { // Force mouse move POINT pt; GetCursorPos( &pt ); //SetCursorPos( pt.x -1, pt.y ); SetCursorPos( pt.x, pt.y ); return 0; } break; default: break; } iret = 1; } break; } return iret; } void PhonemeEditor::DrawWords( CChoreoWidgetDrawHelper& drawHelper, RECT& rcWorkSpace, CSentence& sentence, int type, bool showactive /* = true */ ) { float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; int ypos = rcWorkSpace.top + m_nTickHeight + 2; if ( type == 1 ) { ypos += m_nTickHeight + 5; } const char *fontName = "Arial"; bool drawselected; for ( int pass = 0; pass < 2 ; pass++ ) { drawselected = pass == 0 ? false : true; for (int k = 0; k < sentence.m_Words.Size(); k++) { CWordTag *word = sentence.m_Words[ k ]; if ( !word ) continue; if ( word->m_bSelected != drawselected ) continue; bool hasselectedphonemes = false; for ( int p = 0; p < word->m_Phonemes.Size() && !hasselectedphonemes; p++ ) { CPhonemeTag *t = word->m_Phonemes[ p ]; if ( t->m_bSelected ) { hasselectedphonemes = true; } } float t1 = word->m_flStartTime; float t2 = word->m_flEndTime; // Tag it float frac = ( t1 - starttime ) / ( endtime - starttime ); int xpos = ( int )( frac * rcWorkSpace.right ); if ( frac <= 0.0 ) xpos = 0; // Draw duration float frac2 = ( t2 - starttime ) / ( endtime - starttime ); if ( frac2 < 0.0 ) continue; int xpos2 = ( int )( frac2 * rcWorkSpace.right ); // Draw line and vertical ticks RECT rcWord; rcWord.left = xpos; rcWord.right = xpos2; rcWord.top = ypos - m_nTickHeight + 1; rcWord.bottom = ypos; drawHelper.DrawFilledRect( PEColor( word->m_bSelected ? COLOR_PHONEME_TAG_SELECTED : COLOR_PHONEME_TAG_FILLER_NORMAL ), rcWord ); COLORREF border = PEColor( word->m_bSelected ? COLOR_PHONEME_TAG_BORDER_SELECTED : COLOR_PHONEME_TAG_BORDER ); if ( showactive && m_bWordsActive ) { drawHelper.DrawFilledRect( PEColor( COLOR_PHONEME_ACTIVE_BORDER ), xpos, ypos - m_nTickHeight, xpos2, ypos - m_nTickHeight + 4 ); } drawHelper.DrawColoredLine( border, PS_SOLID, 1, xpos, ypos, xpos2, ypos ); drawHelper.DrawColoredLine( border, PS_SOLID, 1, xpos, ypos, xpos, ypos - m_nTickHeight ); drawHelper.DrawColoredLine( border, PS_SOLID, 1, xpos2, ypos, xpos2, ypos - m_nTickHeight ); drawHelper.DrawColoredLine( border, PS_SOLID, 1, xpos, ypos - m_nTickHeight, xpos2, ypos - m_nTickHeight ); if ( hasselectedphonemes ) { drawHelper.DrawFilledRect( PEColor( COLOR_PHONEME_SELECTED_BORDER ), xpos, ypos - 3, xpos2, ypos ); } //if ( frac >= 0.0 && frac <= 1.0 ) { int fontsize = 9; RECT rcText; rcText.left = xpos; rcText.right = xpos + 500; rcText.top = ypos - m_nTickHeight + 4; rcText.bottom = rcText.top + fontsize + 2; int length = drawHelper.CalcTextWidth( fontName, fontsize, FW_NORMAL, "%s", word->GetWord() ); rcText.right = max( (LONG)xpos2 - 2, rcText.left + length + 1 ); int w = rcText.right - rcText.left; if ( w > length ) { rcText.left += ( w - length ) / 2; } drawHelper.DrawColoredText( fontName, fontsize, FW_NORMAL, PEColor( word->m_bSelected ? COLOR_PHONEME_TAG_TEXT_SELECTED : COLOR_PHONEME_TAG_TEXT ), rcText, "%s", word->GetWord() ); } } } } void PhonemeEditor::DrawPhonemes( CChoreoWidgetDrawHelper& drawHelper, RECT& rcWorkSpace, CSentence& sentence, int type, bool showactive /* = true */ ) { float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; int ypos = rcWorkSpace.bottom - m_nTickHeight - 2; if ( type == 1 ) { ypos -= ( m_nTickHeight + 5 ); } const char *fontName = "Arial"; bool drawselected; for ( int pass = 0; pass < 2 ; pass++ ) { drawselected = pass == 0 ? false : true; for ( int i = 0; i < sentence.m_Words.Size(); i++ ) { CWordTag *w = sentence.m_Words[ i ]; if ( !w ) continue; if ( w->m_bSelected != drawselected ) continue; for ( int k = 0; k < w->m_Phonemes.Size(); k++ ) { CPhonemeTag *pPhoneme = w->m_Phonemes[ k ]; float t1 = pPhoneme->GetStartTime(); float t2 = pPhoneme->GetEndTime(); // Tag it float frac = ( t1 - starttime ) / ( endtime - starttime ); int xpos = ( int )( frac * rcWorkSpace.right ); if ( frac <= 0.0 ) { xpos = 0; } // Draw duration float frac2 = ( t2 - starttime ) / ( endtime - starttime ); if ( frac2 < 0.0 ) { continue; } int xpos2 = ( int )( frac2 * rcWorkSpace.right ); RECT rcFrame; rcFrame.left = xpos; rcFrame.right = xpos2; rcFrame.top = ypos - m_nTickHeight + 1; rcFrame.bottom = ypos; drawHelper.DrawFilledRect( PEColor( pPhoneme->m_bSelected ? COLOR_PHONEME_TAG_SELECTED : COLOR_PHONEME_TAG_FILLER_NORMAL ), rcFrame ); COLORREF border = PEColor( pPhoneme->m_bSelected ? COLOR_PHONEME_TAG_BORDER_SELECTED : COLOR_PHONEME_TAG_BORDER ); if ( showactive && !m_bWordsActive ) { drawHelper.DrawFilledRect( PEColor( COLOR_PHONEME_ACTIVE_BORDER ), xpos, ypos - 3, xpos2, ypos ); } drawHelper.DrawColoredLine( border, PS_SOLID, 1, xpos, ypos - m_nTickHeight, xpos2, ypos - m_nTickHeight ); drawHelper.DrawColoredLine( border, PS_SOLID, 1, xpos, ypos, xpos, ypos - m_nTickHeight ); drawHelper.DrawColoredLine( border, PS_SOLID, 1, xpos2, ypos, xpos2, ypos - m_nTickHeight ); drawHelper.DrawColoredLine( border, PS_SOLID, 1, xpos, ypos, xpos2, ypos ); if ( w->m_bSelected ) { drawHelper.DrawFilledRect( PEColor( COLOR_PHONEME_SELECTED_BORDER ), xpos, ypos - m_nTickHeight + 1, xpos2, ypos - m_nTickHeight + 4 ); } //if ( frac >= 0.0 && frac <= 1.0 ) { int fontsize = 9; RECT rcText; rcText.left = xpos; rcText.right = xpos + 500; rcText.top = ypos - m_nTickHeight + 4; rcText.bottom = rcText.top + fontsize + 2; int length = drawHelper.CalcTextWidth( fontName, fontsize, FW_NORMAL, "%s", ConvertPhoneme( pPhoneme->GetPhonemeCode() ) ); rcText.right = max( (LONG)xpos2 - 2, rcText.left + length + 1 ); int w = rcText.right - rcText.left; if ( w > length ) { rcText.left += ( w - length ) / 2; } drawHelper.DrawColoredText( fontName, fontsize, FW_NORMAL, PEColor( pPhoneme->m_bSelected ? COLOR_PHONEME_TAG_TEXT_SELECTED : COLOR_PHONEME_TAG_TEXT ), rcText, "%s", ConvertPhoneme( pPhoneme->GetPhonemeCode() ) ); } } } } } //----------------------------------------------------------------------------- // Purpose: // Input : drawHelper - // rc - //----------------------------------------------------------------------------- void PhonemeEditor::DrawRelativeTags( CChoreoWidgetDrawHelper& drawHelper, RECT& rc ) { if ( !m_pEvent || !m_pWaveFile ) return; drawHelper.DrawColoredText( "Arial", 9, FW_NORMAL, PEColor( COLOR_PHONEME_TIMING_TAG ), rc, "Timing Tags:" ); float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; for ( int i = 0; i < m_pEvent->GetNumRelativeTags(); i++ ) { CEventRelativeTag *tag = m_pEvent->GetRelativeTag( i ); if ( !tag ) continue; // float tagtime = tag->GetPercentage() * m_pWaveFile->GetRunningLength(); if ( tagtime < starttime || tagtime > endtime ) continue; float frac = ( tagtime - starttime ) / ( endtime - starttime ); int left = rc.left + (int)( frac * ( float )( rc.right - rc.left ) + 0.5f ); RECT rcMark; rcMark = rc; rcMark.top = rc.bottom - 8; rcMark.bottom = rc.bottom; rcMark.left = left - 4; rcMark.right = left + 4; drawHelper.DrawTriangleMarker( rcMark, PEColor( COLOR_PHONEME_TIMING_TAG ) ); RECT rcText; rcText = rc; rcText.bottom = rc.bottom - 10; rcText.top = rcText.bottom - 10; int len = drawHelper.CalcTextWidth( "Arial", 9, FW_NORMAL, tag->GetName() ); rcText.left = left - len / 2; rcText.right = rcText.left + len + 2; drawHelper.DrawColoredText( "Arial", 9, FW_NORMAL, PEColor( COLOR_PHONEME_TIMING_TAG ), rcText, tag->GetName() ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::redraw( void ) { if ( !ToolCanDraw() ) return; CChoreoWidgetDrawHelper drawHelper( this ); HandleToolRedraw( drawHelper ); if ( !m_pWaveFile ) return; HDC dc = drawHelper.GrabDC(); RECT rc; GetWorkspaceRect( rc ); float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; // Now draw the time legend RECT rcLabel; float granularity = 0.5f; drawHelper.DrawColoredLine( PEColor( COLOR_PHONEME_TIMELINE ), PS_SOLID, 1, rc.left, rc.bottom - m_nTickHeight, rc.right, rc.bottom - m_nTickHeight ); if ( GetMode() != MODE_EMPHASIS ) { Emphasis_Redraw( drawHelper, rc ); } sound->RenderWavToDC( dc, rc, PEColor( COLOR_PHONEME_WAVDATA ), starttime, endtime, m_pWaveFile, m_bSelectionActive, m_nSelection[ 0 ], m_nSelection[ 1 ] ); float f = SnapTime( starttime, granularity ); while ( f <= endtime ) { float frac = ( f - starttime ) / ( endtime - starttime ); if ( frac >= 0.0f && frac <= 1.0f ) { drawHelper.DrawColoredLine( ( COLOR_PHONEME_TIMELINE_MAJORTICK ), PS_SOLID, 1, (int)( frac * rc.right ), rc.top, (int)( frac * rc.right ), rc.bottom - m_nTickHeight ); rcLabel.left = (int)( frac * rc.right ); rcLabel.bottom = rc.bottom; rcLabel.top = rcLabel.bottom - 10; char sz[ 32 ]; sprintf( sz, "%.2f", f ); int textWidth = drawHelper.CalcTextWidth( "Arial", 9, FW_NORMAL, sz ); rcLabel.right = rcLabel.left + textWidth; OffsetRect( &rcLabel, -textWidth / 2, 0 ); drawHelper.DrawColoredText( "Arial", 9, FW_NORMAL, PEColor( COLOR_PHONEME_TEXT ), rcLabel, sz ); } f += granularity; } HBRUSH br = CreateSolidBrush( PEColor( COLOR_PHONEME_TEXT ) ); FrameRect( dc, &rc, br ); DeleteObject( br ); RECT rcTags = rc; rcTags.top = TAG_TOP; rcTags.bottom = TAG_BOTTOM; DrawRelativeTags( drawHelper, rcTags ); int fontsize = 9; RECT rcText = rc; rcText.top = rcText.bottom + 5; rcText.left += 5; rcText.bottom = rcText.top + fontsize + 1; rcText.right -= 5; int fontweight = FW_NORMAL; const char *font = "Arial"; if ( m_nLastExtractionResult != SR_RESULT_NORESULT ) { COLORREF clr = PEColor( COLOR_PHONEME_EXTRACTION_RESULT_OTHER ); switch ( m_nLastExtractionResult ) { case SR_RESULT_ERROR: clr = PEColor( COLOR_PHONEME_EXTRACTION_RESULT_ERROR ); break; case SR_RESULT_SUCCESS: clr = PEColor( COLOR_PHONEME_EXTRACTION_RESULT_SUCCESS ); break; case SR_RESULT_FAILED: clr = PEColor( COLOR_PHONEME_EXTRACTION_RESULT_FAIL ); break; default: break; } drawHelper.DrawColoredText( font, fontsize, fontweight, clr, rcText, "Last Extraction Result: %s", GetExtractionResultString( m_nLastExtractionResult ) ); OffsetRect( &rcText, 0, fontsize + 1 ); } if ( m_pEvent && !Q_stristr( m_pEvent->GetParameters(), ".wav" ) ) { drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, "Sound: '%s', file: %s, length %.2f seconds", m_pEvent->GetParameters(), m_WorkFile.m_szWaveFile, m_pWaveFile->GetRunningLength() ); } else { drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, "File: %s, length %.2f seconds", m_WorkFile.m_szWaveFile, m_pWaveFile->GetRunningLength() ); } OffsetRect( &rcText, 0, fontsize + 1 ); drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, "Number of samples %i at %ikhz (%i bits/sample) %s", (int) (m_pWaveFile->GetRunningLength() * m_pWaveFile->SampleRate() ), m_pWaveFile->SampleRate(), (m_pWaveFile->SampleSize()<<3), m_Tags.GetVoiceDuck() ? "duck other audio" : "no ducking" ); OffsetRect( &rcText, 0, fontsize + 1 ); drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, "[ %i ] Words [ %i ] Phonemes / Zoom %i %%", m_Tags.m_Words.Size(), m_Tags.CountPhonemes(), m_nTimeZoom ); if ( m_pEvent ) { OffsetRect( &rcText, 0, fontsize + 1 ); drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, "Event %s", m_pEvent->GetName() ); } OffsetRect( &rcText, 0, fontsize + 1 ); drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, "Using: %s", GetSpeechAPIName() ); char text[ 4096 ]; sprintf( text, "Sentence Text: %s", m_Tags.GetText() ); int halfwidth = ( rc.right - rc.left ) / 2; rcText = rc; rcText.left = halfwidth; rcText.top = rcText.bottom + 5; rcText.right = rcText.left + halfwidth * 0.6; drawHelper.CalcTextRect( font, fontsize, fontweight, halfwidth, rcText, text ); drawHelper.DrawColoredTextMultiline( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, text ); CWordTag *cw = GetSelectedWord(); if ( cw ) { char wordInfo[ 512 ]; sprintf( wordInfo, "Word: %s, start %.2f end %.2f, duration %.2f ms phonemes %i", cw->GetWord(), cw->m_flStartTime, cw->m_flEndTime, 1000.0f * ( cw->m_flEndTime - cw->m_flStartTime ), cw->m_Phonemes.Size() ); int length = drawHelper.CalcTextWidth( font, fontsize, fontweight, wordInfo ); OffsetRect( &rcText, 0, ( rcText.bottom - rcText.top ) + 2 ); rcText.left = rcText.right - length - 10; rcText.bottom = rcText.top + fontsize + 1; drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, wordInfo ); } CPhonemeTag *cp = GetSelectedPhoneme(); if ( cp ) { char phonemeInfo[ 512 ]; sprintf( phonemeInfo, "Phoneme: %s, start %.2f end %.2f, duration %.2f ms", ConvertPhoneme( cp->GetPhonemeCode() ), cp->GetStartTime(), cp->GetEndTime(), 1000.0f * ( cp->GetEndTime() - cp->GetStartTime() ) ); int length = drawHelper.CalcTextWidth( font, fontsize, fontweight, phonemeInfo ); OffsetRect( &rcText, 0, ( rcText.bottom - rcText.top ) + 2 ); rcText.left = rcText.right - length - 10; rcText.bottom = rcText.top + fontsize + 1; drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, phonemeInfo ); } // Draw playback rate { char sz[ 48 ]; sprintf( sz, "Speed: %.2fx", m_flPlaybackRate ); int length = drawHelper.CalcTextWidth( font, fontsize, fontweight, sz); rcText = rc; rcText.top = rc.bottom + 60; rcText.bottom = rcText.top + fontsize + 1; rcText.left = m_pPlaybackRate->x() + m_pPlaybackRate->w() - x(); rcText.right = rcText.left + length + 2; drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_TEXT ), rcText, sz ); } if ( m_UndoStack.Size() > 0 ) { int length = drawHelper.CalcTextWidth( font, fontsize, fontweight, "Undo levels: %i/%i", m_nUndoLevel, m_UndoStack.Size() ); rcText = rc; rcText.top = rc.bottom + 60; rcText.bottom = rcText.top + fontsize + 1; rcText.right -= 5; rcText.left = rcText.right - length - 10; drawHelper.DrawColoredText( font, fontsize, fontweight, PEColor( COLOR_PHONEME_EXTRACTION_RESULT_SUCCESS ), rcText, "Undo levels: %i/%i", m_nUndoLevel, m_UndoStack.Size() ); } float endfrac = ( m_pWaveFile->GetRunningLength() - starttime ) / ( endtime - starttime ); if ( endfrac >= 0.0f && endfrac <= 1.0f ) { int endpos = ( int ) ( rc.right * endfrac ); drawHelper.DrawColoredLine( PEColor( COLOR_PHONEME_WAV_ENDPOINT ), PS_DOT, 2, endpos, rc.top, endpos, rc.bottom - m_nTickHeight ); } DrawPhonemes( drawHelper, rc, m_Tags, 0 ); DrawPhonemes( drawHelper, rc, m_TagsExt, 1, false ); DrawWords( drawHelper, rc, m_Tags, 0 ); DrawWords( drawHelper, rc, m_TagsExt, 1, false ); if ( GetMode() == MODE_EMPHASIS ) { Emphasis_Redraw( drawHelper, rc ); } DrawScrubHandle( drawHelper ); } #define MOTION_RANGE 3000 #define MOTION_MAXSTEP 500 //----------------------------------------------------------------------------- // Purpose: Brown noise simulates brownian motion centered around 127.5 but we cap the walking // to just a couple of units // Input : *buffer - // count - // Output : static void //----------------------------------------------------------------------------- static void WriteBrownNoise( void *buffer, int count ) { int currentValue = 127500; int maxValue = currentValue + ( MOTION_RANGE / 2 ); int minValue = currentValue - ( MOTION_RANGE / 2 ); unsigned char *pos = ( unsigned char *)buffer; while ( --count >= 0 ) { currentValue += random->RandomInt( -MOTION_MAXSTEP, MOTION_MAXSTEP ); currentValue = min( maxValue, currentValue ); currentValue = max( minValue, currentValue ); // Downsample to 0-255 range *pos++ = (unsigned char)( ( (float)currentValue / 1000.0f ) + 0.5f ); } } //----------------------------------------------------------------------------- // Purpose: Replace with brownian noice parts of the wav file that we dont' want processed by the // speech recognizer // Input : store - // *format - // chunkname - // *buffer - // buffersize - //----------------------------------------------------------------------------- void PhonemeEditor::ResampleChunk( IterateOutputRIFF& store, void *format, int chunkname, char *buffer, int buffersize, int start_silence /*=0*/, int end_silence /*=0*/ ) { WAVEFORMATEX *pFormat = ( WAVEFORMATEX * )format; Assert( pFormat ); if ( pFormat->wFormatTag == WAVE_FORMAT_PCM ) { int silience_time = start_silence + end_silence; // Leave room for silence at start + end int resamplesize = buffersize + silience_time * pFormat->nSamplesPerSec; char *resamplebuffer = new char[ resamplesize + 4 ]; memset( resamplebuffer, (unsigned char)128, resamplesize + 4 ); int startpos = (int)( start_silence * pFormat->nSamplesPerSec ); if ( startpos > 0 ) { WriteBrownNoise( resamplebuffer, startpos ); } if ( startpos + buffersize < resamplesize ) { WriteBrownNoise( &resamplebuffer[ startpos + buffersize ], resamplesize - ( startpos + buffersize ) ); } memcpy( &resamplebuffer[ startpos ], buffer, buffersize ); store.ChunkWriteData( resamplebuffer, resamplesize ); return; } store.ChunkWriteData( buffer, buffersize ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::ReadLinguisticTags( void ) { if ( !m_pWaveFile ) return; CAudioSource *wave = sound->LoadSound( m_WorkFile.m_szWorkingFile ); if ( !wave ) return; m_Tags.Reset(); CSentence *sentence = wave->GetSentence(); if ( sentence ) { // Copy data from sentence to m_Tags m_Tags.Reset(); m_Tags = *sentence; } delete wave; } //----------------------------------------------------------------------------- // Purpose: Switch wave files // Input : *wavefile - // force - //----------------------------------------------------------------------------- void PhonemeEditor::SetCurrentWaveFile( const char *wavefile, bool force /*=false*/, CChoreoEvent *event /*=NULL*/ ) { // No change? if ( !force && !stricmp( m_WorkFile.m_szWaveFile, wavefile ) ) return; StopPlayback(); if ( GetDirty() ) { int retval = mxMessageBox( this, va( "Save current changes to %s", m_WorkFile.m_szWaveFile ), "Phoneme Editor", MX_MB_QUESTION | MX_MB_YESNOCANCEL ); // Cancel if ( retval == 2 ) return; // Yes if ( retval == 0 ) { CommitChanges(); } } ClearExtracted(); m_Tags.Reset(); m_TagsExt.Reset(); Deselect(); if ( m_pWaveFile ) { char fn[ 512 ]; Q_snprintf( fn, sizeof( fn ), "%s%s", m_WorkFile.m_szBasePath, m_WorkFile.m_szWorkingFile ); filesystem->RemoveFile( fn, "GAME" ); } delete m_pWaveFile; m_pWaveFile = NULL; SetDirty( false ); // Set up event and scene m_pEvent = event; // Try an dload new sound m_pWaveFile = sound->LoadSound( wavefile ); Q_strncpy( m_WorkFile.m_szWaveFile, wavefile, sizeof( m_WorkFile.m_szWaveFile ) ); char fullpath[ 512 ]; filesystem->RelativePathToFullPath( wavefile, "GAME", fullpath, sizeof( fullpath ) ); int len = Q_strlen( fullpath ); int charstocopy = len - Q_strlen( wavefile ) + 1; m_WorkFile.m_szBasePath[ 0 ] = 0; if ( charstocopy >= 0 ) { Q_strncpy( m_WorkFile.m_szBasePath, fullpath, charstocopy ); m_WorkFile.m_szBasePath[ charstocopy ] = 0; } Q_StripExtension( wavefile, m_WorkFile.m_szWorkingFile, sizeof( m_WorkFile.m_szWorkingFile ) ); Q_strncat( m_WorkFile.m_szWorkingFile, "_work.wav", sizeof( m_WorkFile.m_szWorkingFile ), COPY_ALL_CHARACTERS ); Q_FixSlashes( m_WorkFile.m_szWaveFile ); Q_FixSlashes( m_WorkFile.m_szWorkingFile ); Q_FixSlashes( m_WorkFile.m_szBasePath ); if ( !m_pWaveFile ) { Con_ErrorPrintf( "Couldn't set current .wav file to %s\n", m_WorkFile.m_szWaveFile ); return; } Con_Printf( "Current .wav file set to %s\n", m_WorkFile.m_szWaveFile ); g_pWaveBrowser->SetCurrent( m_WorkFile.m_szWaveFile ); // Copy over and overwrite file FPCopyFile( m_WorkFile.m_szWaveFile, m_WorkFile.m_szWorkingFile, false ); // Make it writable MakeFileWriteable( m_WorkFile.m_szWorkingFile ); ReadLinguisticTags(); Deselect(); RepositionHSlider(); } //----------------------------------------------------------------------------- // Purpose: // Input : x - //----------------------------------------------------------------------------- void PhonemeEditor::MoveTimeSliderToPos( int x ) { m_nLeftOffset = x; m_pHorzScrollBar->setValue( m_nLeftOffset ); InvalidateRect( (HWND)m_pHorzScrollBar->getHandle(), NULL, TRUE ); redraw(); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int PhonemeEditor::ComputeHPixelsNeeded( void ) { int pixels = 0; if ( m_pWaveFile ) { float maxtime = m_pWaveFile->GetRunningLength(); maxtime += 1.0f; pixels = (int)( maxtime * GetPixelsPerSecond() ); } return pixels; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::RepositionHSlider( void ) { int pixelsneeded = ComputeHPixelsNeeded(); if ( pixelsneeded <= w2() ) { m_pHorzScrollBar->setVisible( false ); } else { m_pHorzScrollBar->setVisible( true ); } m_pHorzScrollBar->setBounds( 0, GetCaptionHeight(), w2(), 12 ); m_pHorzScrollBar->setRange( 0, pixelsneeded ); m_pHorzScrollBar->setValue( 0 ); m_nLeftOffset = 0; m_pHorzScrollBar->setPagesize( w2() ); redraw(); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float PhonemeEditor::GetPixelsPerSecond( void ) { return m_flPixelsPerSecond * GetTimeZoomScale(); } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float PhonemeEditor::GetTimeZoomScale( void ) { return ( float )m_nTimeZoom / 100.0f; } //----------------------------------------------------------------------------- // Purpose: // Input : scale - //----------------------------------------------------------------------------- void PhonemeEditor::SetTimeZoomScale( int scale ) { m_nTimeZoom = scale; } //----------------------------------------------------------------------------- // Purpose: // Input : dt - //----------------------------------------------------------------------------- void PhonemeEditor::Think( float dt ) { if ( !m_pWaveFile ) return; bool scrubbing = ( m_nDragType == DRAGTYPE_SCRUBBER ) ? true : false; ScrubThink( dt, scrubbing ); if ( m_pMixer && !sound->IsSoundPlaying( m_pMixer ) ) { m_pMixer = NULL; } } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // my - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- int PhonemeEditor::IsMouseOverBoundary( mxEvent *event ) { int mx, my; mx = (short)event->x; my = (short)event->y; // Deterime if phoneme boundary is under the cursor // if ( !m_pWaveFile ) return BOUNDARY_NONE; if ( !(event->modifiers & mxEvent::KeyCtrl ) ) { return BOUNDARY_NONE; } RECT rc; GetWorkspaceRect( rc ); if ( IsMouseOverPhonemeRow( my ) ) { float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; int mouse_tolerance = 3; for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; for ( int k = 0; k < word->m_Phonemes.Size(); k++ ) { CPhonemeTag *pPhoneme = word->m_Phonemes[ k ]; float t1 = pPhoneme->GetStartTime(); float t2 = pPhoneme->GetEndTime(); // Tag it float frac1 = ( t1 - starttime ) / ( endtime - starttime ); float frac2 = ( t2 - starttime ) / ( endtime - starttime ); int xpos1 = ( int )( frac1 * w2() ); int xpos2 = ( int )( frac2 * w2() ); if ( abs( xpos1 - mx ) <= mouse_tolerance || abs( xpos2 - mx ) <= mouse_tolerance ) { return BOUNDARY_PHONEME; } } } } if ( IsMouseOverWordRow( my ) ) { float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; int mouse_tolerance = 3; for ( int k = 0; k < m_Tags.m_Words.Size(); k++ ) { CWordTag *word = m_Tags.m_Words[ k ]; float t1 = word->m_flStartTime; float t2 = word->m_flEndTime; // Tag it float frac1 = ( t1 - starttime ) / ( endtime - starttime ); float frac2 = ( t2 - starttime ) / ( endtime - starttime ); int xpos1 = ( int )( frac1 * w2() ); int xpos2 = ( int )( frac2 * w2() ); if ( ( abs( xpos1 - mx ) <= mouse_tolerance ) || ( abs( xpos2 - mx ) <= mouse_tolerance ) ) { return BOUNDARY_WORD; } } } return BOUNDARY_NONE; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::DrawFocusRect( char *reason ) { HDC dc = GetDC( NULL ); for ( int i = 0; i < m_FocusRects.Size(); i++ ) { RECT rc = m_FocusRects[ i ].m_rcFocus; ::DrawFocusRect( dc, &rc ); } ReleaseDC( NULL, dc ); } //----------------------------------------------------------------------------- // Purpose: // Input : &rc - //----------------------------------------------------------------------------- void PhonemeEditor::GetWorkspaceRect( RECT &rc ) { GetClientRect( (HWND)getHandle(), &rc ); rc.top += TAG_BOTTOM; rc.bottom = rc.bottom - 75 - MODE_TAB_OFFSET; InflateRect( &rc, -1, -1 ); } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // my - //----------------------------------------------------------------------------- void PhonemeEditor::ShowWordMenu( CWordTag *word, int mx, int my ) { CountSelected(); mxPopupMenu *pop = new mxPopupMenu(); Assert( pop ); pop->add( va( "Edit sentence text..." ), IDC_EDITWORDLIST ); if ( m_nSelectedWordCount > 0 && word ) { pop->addSeparator(); pop->add( va( "Delete %s", m_nSelectedWordCount > 1 ? "words" : va( "'%s'", word->GetWord() ) ), IDC_EDIT_DELETEWORD ); if ( m_nSelectedWordCount == 1 ) { int index = IndexOfWord( word ); bool valid = false; if ( index != -1 ) { SetClickedPhoneme( index, -1 ); valid = true; } if ( valid ) { pop->add( va( "Edit word '%s'...", word->GetWord() ), IDC_EDIT_WORD ); float nextGap = GetTimeGapToNextWord( true, word ); float prevGap = GetTimeGapToNextWord( false, word ); if ( nextGap > MINIMUM_WORD_GAP || prevGap > MINIMUM_WORD_GAP ) { pop->addSeparator(); if ( prevGap > MINIMUM_WORD_GAP ) { pop->add( va( "Insert word before '%s'...", word->GetWord() ), IDC_EDIT_INSERTWORDBEFORE ); } if ( nextGap > MINIMUM_WORD_GAP ) { pop->add( va( "Insert word after '%s'...", word->GetWord() ), IDC_EDIT_INSERTWORDAFTER ); } } if ( word->m_Phonemes.Size() == 0 ) { pop->addSeparator(); pop->add( va( "Add phoneme to '%s'...", word->GetWord() ), IDC_EDIT_INSERTFIRSTPHONEMEOFWORD ); } pop->addSeparator(); pop->add( va( "Select all words after '%s'", word->GetWord() ), IDC_SELECT_WORDSRIGHT ); pop->add( va( "Select all words before '%s'", word->GetWord() ), IDC_SELECT_WORDSLEFT ); } } } if ( AreSelectedWordsContiguous() && m_nSelectedWordCount > 1 ) { pop->addSeparator(); pop->add( va( "Merge words" ), IDC_SNAPWORDS ); if ( m_nSelectedWordCount == 2 ) { pop->add( va( "Separate words" ), IDC_SEPARATEWORDS ); } } if ( m_nSelectedWordCount > 0 ) { pop->addSeparator(); pop->add( va( "Deselect all" ), IDC_DESELECT_PHONEMESANDWORDS ); } if ( m_Tags.m_Words.Size() > 0 ) { pop->addSeparator(); pop->add( va( "Cleanup words/phonemes" ), IDC_CLEANUP ); } if ( m_Tags.m_Words.Size() > 0 ) { pop->addSeparator(); pop->add( va( "Realign phonemes to words" ), IDC_REALIGNPHONEMES ); } pop->popup( this, mx, my ); } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // my - //----------------------------------------------------------------------------- void PhonemeEditor::ShowPhonemeMenu( CPhonemeTag *pho, int mx, int my ) { CountSelected(); SetClickedPhoneme( -1, -1 ); if ( !pho ) return; if ( m_Tags.CountPhonemes() == 0 ) { Con_Printf( "No phonemes, try extracting from .wav first\n" ); return; } mxPopupMenu *pop = new mxPopupMenu(); bool valid = false; CWordTag *tag = m_Tags.GetWordForPhoneme( pho ); if ( tag ) { int wordNum = IndexOfWord( tag ); int pi = tag->IndexOfPhoneme( pho ); SetClickedPhoneme( wordNum, pi ); valid = true; } if ( valid ) { if ( m_nSelectedPhonemeCount == 1 ) { pop->add( va( "Edit '%s'...", ConvertPhoneme( pho->GetPhonemeCode() ) ), IDC_EDIT_PHONEME ); float nextGap = GetTimeGapToNextPhoneme( true, pho ); float prevGap = GetTimeGapToNextPhoneme( false, pho ); if ( nextGap > MINIMUM_PHONEME_GAP || prevGap > MINIMUM_PHONEME_GAP ) { pop->addSeparator(); if ( prevGap > MINIMUM_PHONEME_GAP ) { pop->add( va( "Insert phoneme before '%s'...", ConvertPhoneme( pho->GetPhonemeCode() ) ), IDC_EDIT_INSERTPHONEMEBEFORE ); } if ( nextGap > MINIMUM_PHONEME_GAP ) { pop->add( va( "Insert phoneme after '%s'...", ConvertPhoneme( pho->GetPhonemeCode() ) ), IDC_EDIT_INSERTPHONEMEAFTER ); } } pop->addSeparator(); pop->add( va( "Select all phonemes after '%s'", ConvertPhoneme( pho->GetPhonemeCode() ) ), IDC_SELECT_PHONEMESRIGHT ); pop->add( va( "Select all phonemes before '%s'",ConvertPhoneme( pho->GetPhonemeCode() ) ), IDC_SELECT_PHONEMESLEFT ); pop->addSeparator(); } if ( AreSelectedPhonemesContiguous() && m_nSelectedPhonemeCount > 1 ) { pop->add( va( "Merge phonemes" ), IDC_SNAPPHONEMES ); if ( m_nSelectedPhonemeCount == 2 ) { pop->add( va( "Separate phonemes" ), IDC_SEPARATEPHONEMES ); } pop->addSeparator(); } if ( m_nSelectedPhonemeCount >= 1 ) { pop->add( va( "Delete %s", m_nSelectedPhonemeCount == 1 ? va( "'%s'", ConvertPhoneme( pho->GetPhonemeCode() ) ) : "phonemes" ), IDC_EDIT_DELETEPHONEME ); pop->addSeparator(); pop->add( va( "Deselect all" ), IDC_DESELECT_PHONEMESANDWORDS ); } } if ( m_Tags.m_Words.Size() > 0 ) { pop->addSeparator(); pop->add( va( "Cleanup words/phonemes" ), IDC_CLEANUP ); } if ( m_Tags.m_Words.Size() > 0 ) { pop->addSeparator(); pop->add( va( "Realign words to phonemes" ), IDC_REALIGNWORDS ); } pop->popup( this, mx, my ); } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // Output : float //----------------------------------------------------------------------------- float PhonemeEditor::GetTimeForPixel( int mx ) { RECT rc; GetWorkspaceRect( rc ); float starttime = m_nLeftOffset / GetPixelsPerSecond(); float time = (float)mx / GetPixelsPerSecond() + starttime; return time; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // **pp1 - // **pp2 - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::FindSpanningPhonemes( float time, CPhonemeTag **pp1, CPhonemeTag **pp2 ) { Assert( pp1 && pp2 ); *pp1 = NULL; *pp2 = NULL; // Three pixels double time_epsilon = ( 1.0f / GetPixelsPerSecond() ) * 3; CPhonemeTag *previous = NULL; for ( int w = 0; w < m_Tags.m_Words.Size(); w++ ) { CWordTag *word = m_Tags.m_Words[ w ]; for ( int i = 0; i < word->m_Phonemes.Size(); i++ ) { CPhonemeTag *current = word->m_Phonemes[ i ]; double dt; if ( !previous ) { dt = fabs( current->GetStartTime() - time ); if ( dt < time_epsilon ) { *pp2 = current; return true; } } else { int found = 0; dt = fabs( previous->GetEndTime() - time ); if ( dt < time_epsilon ) { *pp1 = previous; found++; } dt = fabs( current->GetStartTime() - time ); if ( dt < time_epsilon ) { *pp2 = current; found++; } if ( found != 0 ) { return true; } } previous = current; } } if ( m_Tags.m_Words.Size() > 0 ) { // Check last word, but only if it has some phonemes CWordTag *lastWord = m_Tags.m_Words[ m_Tags.m_Words.Size() - 1 ]; if ( lastWord && ( lastWord->m_Phonemes.Size() > 0 ) ) { CPhonemeTag *last = lastWord->m_Phonemes[ lastWord->m_Phonemes.Size() - 1 ]; float dt; dt = fabs( last->GetEndTime() - time ); if ( dt < time_epsilon ) { *pp1 = last; return true; } } } return false; } //----------------------------------------------------------------------------- // Purpose: // Input : time - // **pp1 - // **pp2 - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::FindSpanningWords( float time, CWordTag **pp1, CWordTag **pp2 ) { Assert( pp1 && pp2 ); *pp1 = NULL; *pp2 = NULL; // Three pixels double time_epsilon = ( 1.0f / GetPixelsPerSecond() ) * 3; CWordTag *previous = NULL; for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *current = m_Tags.m_Words[ i ]; double dt; if ( !previous ) { dt = fabs( current->m_flStartTime - time ); if ( dt < time_epsilon ) { *pp2 = current; return true; } } else { int found = 0; dt = fabs( previous->m_flEndTime - time ); if ( dt < time_epsilon ) { *pp1 = previous; found++; } dt = fabs( current->m_flStartTime - time ); if ( dt < time_epsilon ) { *pp2 = current; found++; } if ( found != 0 ) { return true; } } previous = current; } if ( m_Tags.m_Words.Size() > 0 ) { CWordTag *last = m_Tags.m_Words[ m_Tags.m_Words.Size() - 1 ]; float dt; dt = fabs( last->m_flEndTime - time ); if ( dt < time_epsilon ) { *pp1 = last; return true; } } return false; } int PhonemeEditor::FindWordForTime( float time ) { for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *pCurrent = m_Tags.m_Words[ i ]; if ( time < pCurrent->m_flStartTime ) continue; if ( time > pCurrent->m_flEndTime ) continue; return i; } return -1; } void PhonemeEditor::FinishWordDrag( int startx, int endx ) { float clicktime = GetTimeForPixel( startx ); float endtime = GetTimeForPixel( endx ); float dt = endtime - clicktime; SetDirty( true ); PushUndo(); TraverseWords( &PhonemeEditor::ITER_MoveSelectedWords, dt ); RealignPhonemesToWords( false ); CleanupWordsAndPhonemes( false ); PushRedo(); redraw(); } void PhonemeEditor::FinishWordMove( int startx, int endx ) { float clicktime = GetTimeForPixel( startx ); float endtime = GetTimeForPixel( endx ); // Find the phonemes who have the closest start/endtime to the starting click time CWordTag *current, *next; if ( !FindSpanningWords( clicktime, &current, &next ) ) { return; } SetDirty( true ); PushUndo(); if ( current && !next ) { // cap movement current->m_flEndTime += ( endtime - clicktime ); } else if ( !current && next ) { // cap movement next->m_flStartTime += ( endtime - clicktime ); } else { // cap movement endtime = min( endtime, next->m_flEndTime - 1.0f / GetPixelsPerSecond() ); endtime = max( endtime, current->m_flStartTime + 1.0f / GetPixelsPerSecond() ); current->m_flEndTime = endtime; next->m_flStartTime = endtime; } RealignPhonemesToWords( false ); CleanupWordsAndPhonemes( false ); PushRedo(); redraw(); } CPhonemeTag *PhonemeEditor::FindPhonemeForTime( float time ) { for ( int w = 0 ; w < m_Tags.m_Words.Size(); w++ ) { CWordTag *word = m_Tags.m_Words[ w ]; for ( int i = 0; i < word->m_Phonemes.Size(); i++ ) { CPhonemeTag *pCurrent = word->m_Phonemes[ i ]; if ( time < pCurrent->GetStartTime() ) continue; if ( time > pCurrent->GetEndTime() ) continue; return pCurrent; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : phoneme - // startx - // endx - //----------------------------------------------------------------------------- void PhonemeEditor::FinishPhonemeDrag( int startx, int endx ) { float clicktime = GetTimeForPixel( startx ); float endtime = GetTimeForPixel( endx ); float dt = endtime - clicktime; SetDirty( true ); PushUndo(); TraversePhonemes( &PhonemeEditor::ITER_MoveSelectedPhonemes, dt ); RealignWordsToPhonemes( false ); CleanupWordsAndPhonemes( false ); PushRedo(); redraw(); } //----------------------------------------------------------------------------- // Purpose: // Input : phoneme - // startx - // endx - //----------------------------------------------------------------------------- void PhonemeEditor::FinishPhonemeMove( int startx, int endx ) { float clicktime = GetTimeForPixel( startx ); float endtime = GetTimeForPixel( endx ); // Find the phonemes who have the closest start/endtime to the starting click time CPhonemeTag *current, *next; if ( !FindSpanningPhonemes( clicktime, &current, &next ) ) { return; } SetDirty( true ); PushUndo(); if ( current && !next ) { // cap movement current->AddEndTime( endtime - clicktime ); } else if ( !current && next ) { // cap movement next->AddStartTime( endtime - clicktime ); } else { // cap movement endtime = min( endtime, next->GetEndTime() - 1.0f / GetPixelsPerSecond() ); endtime = max( endtime, current->GetStartTime() + 1.0f / GetPixelsPerSecond() ); current->SetEndTime( endtime ); next->SetStartTime( endtime ); } RealignWordsToPhonemes( false ); CleanupWordsAndPhonemes( false ); PushRedo(); redraw(); } //----------------------------------------------------------------------------- // Purpose: // Input : dirty - //----------------------------------------------------------------------------- void PhonemeEditor::SetDirty( bool dirty, bool clearundo /*=true*/ ) { m_WorkFile.m_bDirty = dirty; if ( !dirty && clearundo ) { WipeUndo(); redraw(); } SetPrefix( dirty ? "* " : "" ); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::GetDirty( void ) { return m_WorkFile.m_bDirty; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditInsertPhonemeBefore( void ) { if ( GetMode() != MODE_PHONEMES ) return; CPhonemeTag *cp = GetSelectedPhoneme(); if ( !cp ) return; float gap = GetTimeGapToNextPhoneme( false, cp ); if ( gap < MINIMUM_PHONEME_GAP ) { Con_Printf( "Can't insert before, gap of %.2f ms is too small\n", 1000.0f * gap ); return; } // Don't have really long phonemes gap = min( gap, DEFAULT_PHONEME_LENGTH ); CWordTag *word = m_Tags.GetWordForPhoneme( cp ); if ( !word ) { Con_Printf( "EditInsertPhonemeBefore: phoneme not a member of any known word!!!\n" ); return; } int clicked = word->IndexOfPhoneme( cp ); if ( clicked < 0 ) { Con_Printf( "EditInsertPhonemeBefore: phoneme not a member of any specified word!!!\n" ); Assert( 0 ); return; } CPhonemeTag phoneme; CPhonemeParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Phoneme/Viseme Properties" ); strcpy( params.m_szName, "" ); int iret = PhonemeProperties( &params ); SetFocus( (HWND)getHandle() ); if ( !iret ) { return; } SetDirty( true ); PushUndo(); phoneme.SetPhonemeCode( TextToPhoneme( params.m_szName ) ); phoneme.SetTag( params.m_szName ); phoneme.SetEndTime( cp->GetStartTime() ); phoneme.SetStartTime( cp->GetStartTime() - gap ); phoneme.m_bSelected = true; cp->m_bSelected = false; word->m_Phonemes.InsertBefore( clicked, new CPhonemeTag( phoneme ) ); PushRedo(); // Add it redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditInsertPhonemeAfter( void ) { if ( GetMode() != MODE_PHONEMES ) return; CPhonemeTag *cp = GetSelectedPhoneme(); if ( !cp ) return; float gap = GetTimeGapToNextPhoneme( true, cp ); if ( gap < MINIMUM_PHONEME_GAP ) { Con_Printf( "Can't insert after, gap of %.2f ms is too small\n", 1000.0f * gap ); return; } // Don't have really long phonemes gap = min( gap, DEFAULT_PHONEME_LENGTH ); CWordTag *word = m_Tags.GetWordForPhoneme( cp ); if ( !word ) { Con_Printf( "EditInsertPhonemeAfter: phoneme not a member of any known word!!!\n" ); return; } int clicked = word->IndexOfPhoneme( cp ); if ( clicked < 0 ) { Con_Printf( "EditInsertPhonemeAfter: phoneme not a member of any specified word!!!\n" ); Assert( 0 ); return; } CPhonemeTag phoneme; CPhonemeParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Phoneme/Viseme Properties" ); strcpy( params.m_szName, "" ); int iret = PhonemeProperties( &params ); SetFocus( (HWND)getHandle() ); if ( !iret ) { return; } SetDirty( true ); PushUndo(); phoneme.SetPhonemeCode( TextToPhoneme( params.m_szName ) ); phoneme.SetTag( params.m_szName ); phoneme.SetEndTime( cp->GetEndTime() + gap ); phoneme.SetStartTime( cp->GetEndTime() ); phoneme.m_bSelected = true; cp->m_bSelected = false; word->m_Phonemes.InsertAfter( clicked, new CPhonemeTag( phoneme ) ); PushRedo(); // Add it redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditInsertWordBefore( void ) { if ( GetMode() != MODE_PHONEMES ) return; CWordTag *cw = GetSelectedWord(); if ( !cw ) return; float gap = GetTimeGapToNextWord( false, cw ); if ( gap < MINIMUM_WORD_GAP ) { Con_Printf( "Can't insert before, gap of %.2f ms is too small\n", 1000.0f * gap ); return; } // Don't have really long words gap = min( gap, DEFAULT_WORD_LENGTH ); int clicked = IndexOfWord( cw ); if ( clicked < 0 ) { Con_Printf( "EditInsertWordBefore: word not in sentence!!!\n" ); Assert( 0 ); return; } CInputParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Insert Word" ); strcpy( params.m_szPrompt, "Word:" ); strcpy( params.m_szInputText, "" ); params.m_nLeft = -1; params.m_nTop = -1; params.m_bPositionDialog = true; if ( params.m_bPositionDialog ) { RECT rcWord; GetWordRect( cw, rcWord ); // Convert to screen coords POINT pt; pt.x = rcWord.left; pt.y = rcWord.top; ClientToScreen( (HWND)getHandle(), &pt ); params.m_nLeft = pt.x; params.m_nTop = pt.y; } int iret = InputProperties( &params ); SetFocus( (HWND)getHandle() ); if ( !iret ) { return; } if ( strlen( params.m_szInputText ) <= 0 ) { return; } int wordCount = CSentence::CountWords( params.m_szInputText ); if ( wordCount > 1 ) { Con_Printf( "Can only insert one word at a time, %s has %i words in it!\n", params.m_szInputText, wordCount ); return; } SetDirty( true ); PushUndo(); CWordTag newword; newword.SetWord( params.m_szInputText ); newword.m_flEndTime = cw->m_flStartTime; newword.m_flStartTime = cw->m_flStartTime - gap; newword.m_bSelected = true; cw->m_bSelected = false; m_Tags.m_Words.InsertBefore( clicked, new CWordTag( newword ) ); PushRedo(); // Add it redraw(); // Jump to phoneme insertion UI EditInsertFirstPhonemeOfWord(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditInsertWordAfter( void ) { if ( GetMode() != MODE_PHONEMES ) return; CWordTag *cw = GetSelectedWord(); if ( !cw ) return; float gap = GetTimeGapToNextWord( true, cw ); if ( gap < MINIMUM_WORD_GAP ) { Con_Printf( "Can't insert after, gap of %.2f ms is too small\n", 1000.0f * gap ); return; } // Don't have really long words gap = min( gap, DEFAULT_WORD_LENGTH ); int clicked = IndexOfWord( cw ); if ( clicked < 0 ) { Con_Printf( "EditInsertWordBefore: word not in sentence!!!\n" ); Assert( 0 ); return; } CInputParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Insert Word" ); strcpy( params.m_szPrompt, "Word:" ); strcpy( params.m_szInputText, "" ); params.m_nLeft = -1; params.m_nTop = -1; params.m_bPositionDialog = true; if ( params.m_bPositionDialog ) { RECT rcWord; GetWordRect( cw, rcWord ); // Convert to screen coords POINT pt; pt.x = rcWord.left; pt.y = rcWord.top; ClientToScreen( (HWND)getHandle(), &pt ); params.m_nLeft = pt.x; params.m_nTop = pt.y; } int iret = InputProperties( &params ); SetFocus( (HWND)getHandle() ); if ( !iret ) { return; } if ( strlen( params.m_szInputText ) <= 0 ) { return; } int wordCount = CSentence::CountWords( params.m_szInputText ); if ( wordCount > 1 ) { Con_Printf( "Can only insert one word at a time, %s has %i words in it!\n", params.m_szInputText, wordCount ); return; } SetDirty( true ); PushUndo(); CWordTag newword; newword.SetWord( params.m_szInputText ); newword.m_flEndTime = cw->m_flEndTime + gap; newword.m_flStartTime = cw->m_flEndTime; newword.m_bSelected = true; cw->m_bSelected = false; CWordTag *w = new CWordTag( newword ); Assert( w ); if ( w ) { m_Tags.m_Words.InsertAfter( clicked, w ); } PushRedo(); // Add it redraw(); EditInsertFirstPhonemeOfWord(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditDeletePhoneme( void ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); if ( m_nSelectedPhonemeCount < 1 ) { return; } SetDirty( true ); PushUndo(); for ( int i = m_Tags.m_Words.Size() - 1; i >= 0; i-- ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; for ( int j = word->m_Phonemes.Size() - 1; j >= 0; j-- ) { CPhonemeTag *p = word->m_Phonemes[ j ]; if ( !p || !p->m_bSelected ) continue; // Delete it word->m_Phonemes.Remove( j ); } } PushRedo(); redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditDeleteWord( void ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); if ( m_nSelectedWordCount < 1 ) { return; } SetDirty( true ); PushUndo(); for ( int i = m_Tags.m_Words.Size() - 1; i >= 0; i-- ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word || !word->m_bSelected ) continue; m_Tags.m_Words.Remove( i ); } PushRedo(); redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::PlayEditedWave( bool selection /* = false */ ) { StopPlayback(); if ( !m_pWaveFile ) return; // Make sure phonemes are loaded FacePoser_EnsurePhonemesLoaded(); SaveLinguisticData(); SetScrubTime( 0.0f ); SetScrubTargetTime( m_pWaveFile->GetRunningLength() ); } typedef struct channel_s { int leftvol; int rightvol; int rleftvol; int rrightvol; float pitch; } channel_t; bool PhonemeEditor::CreateCroppedWave( char const *filename, int startsample, int endsample ) { Assert( sound ); CAudioWaveOutput *pWaveOutput = ( CAudioWaveOutput * )sound->GetAudioOutput(); if ( !pWaveOutput ) return false; CAudioSource *wave = sound->LoadSound( m_WorkFile.m_szWaveFile ); if ( !wave ) return false; CAudioMixer *pMixer = wave->CreateMixer(); if ( !pMixer ) return false; // Create out put file OutFileRIFF riffout( filename, io_out ); // Create output iterator IterateOutputRIFF store( riffout ); WAVEFORMATEX format; format.cbSize = sizeof( format ); format.wFormatTag = WAVE_FORMAT_PCM; format.nAvgBytesPerSec = (int)wave->SampleRate(); format.nChannels = 1; format.wBitsPerSample = 8; format.nSamplesPerSec = (int)wave->SampleRate(); format.nBlockAlign = 1; // (int)wave->SampleSize(); store.ChunkWrite( WAVE_FMT, &format, sizeof( format ) ); // Pull in data and write it out int currentsample = 0; store.ChunkStart( WAVE_DATA ); // need a bit of space short samples[ 2 ]; channel_t channel; channel.leftvol = 255; channel.rightvol = 255; channel.pitch = 1.0; while ( 1 ) { pWaveOutput->m_audioDevice.MixBegin(); if ( !pMixer->MixDataToDevice( &pWaveOutput->m_audioDevice, &channel, currentsample, 1, wave->SampleRate(), true ) ) break; pWaveOutput->m_audioDevice.TransferBufferStereo16( samples, 1 ); currentsample = pMixer->GetSamplePosition(); if ( currentsample >= startsample && currentsample <= endsample ) { // left + right (2 channels ) * 16 bits float s1 = (float)( samples[ 0 ] >> 8 ); float s2 = (float)( samples[ 1 ] >> 8 ); float avg = ( s1 + s2 ) / 2.0f; unsigned char chopped = (unsigned char)( avg + 127.0f ); store.ChunkWriteData( &chopped, sizeof( byte ) ); } } store.ChunkFinish(); delete pMixer; delete wave; return true; } void PhonemeEditor::SentenceFromString( CSentence& sentence, char const *str ) { sentence.Reset(); if ( !str || !str[0] || CSentence::CountWords( str ) == 0 ) { return; } char word[ 256 ]; unsigned char const *in = (unsigned char *)str; char *out = word; while ( *in ) { if ( *in > 32 ) { *out++ = *in++; } else { *out = 0; while ( *in && *in <= 32 ) { in++; } if ( strlen( word ) > 0 ) { CWordTag *w = new CWordTag( (char *)word ); Assert( w ); if ( w ) { sentence.m_Words.AddToTail( w ); } } out = word; } } *out = 0; if ( strlen( word ) > 0 ) { CWordTag *w = new CWordTag( (char *)word ); Assert( w ); if ( w ) { sentence.m_Words.AddToTail( w ); } } sentence.SetText( str ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::RedoPhonemeExtractionSelected( void ) { if ( GetMode() != MODE_PHONEMES ) return; if ( !CheckSpeechAPI() ) return; if ( !m_pWaveFile ) { Con_Printf( "Can't redo extraction, no wavefile loaded!\n" ); Assert( 0 ); return; } if ( !m_bSelectionActive ) { Con_Printf( "Please select a portion of the .wav from which to re-extract phonemes\n" ); return; } // Now copy data back into original list, offsetting by samplestart time float numsamples = m_pWaveFile->GetRunningLength() * m_pWaveFile->SampleRate(); float selectionstarttime = 0.0f; if ( numsamples > 0.0f ) { // Convert sample #'s to time selectionstarttime = ( m_nSelection[ 0 ] / numsamples ) * m_pWaveFile->GetRunningLength(); selectionstarttime = max( 0.0f, selectionstarttime ); } else { Con_Printf( "Original .wav file %s has no samples!!!\n", m_WorkFile.m_szWaveFile ); return; } int i; // Create input array of just selected words CSentence m_InputWords; CSentence m_Results; CountSelected(); bool usingselection = true; if ( m_nSelectedWordCount == 0 ) { // Allow user to type in text // Build word string char wordstring[ 1024 ]; strcpy( wordstring, "" ); CInputParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Phrase Word List" ); strcpy( params.m_szPrompt, "Phrase" ); strcpy( params.m_szInputText, wordstring ); if ( !InputProperties( &params ) ) return; if ( strlen( params.m_szInputText ) <= 0 ) { Con_ErrorPrintf( "Edit word list: No words entered!\n" ); return; } SentenceFromString( m_InputWords, params.m_szInputText ); if ( m_InputWords.m_Words.Size() == 0 ) { Con_Printf( "You must either select words, or type in a set of words in order to extract phonemes!\n" ); return; } usingselection = false; } else { if ( !AreSelectedWordsContiguous() ) { Con_Printf( "Can only redo extraction on a contiguous subset of words\n" ); return; } char temp[ 4096 ]; bool killspace = false; Q_strncpy( temp, m_InputWords.GetText(), sizeof( temp ) ); // Iterate existing words, looking for contiguous selected words for ( i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word || !word->m_bSelected ) continue; // Now add "clean slate" to input list m_InputWords.m_Words.AddToTail( new CWordTag( *word ) ); Q_strncat( temp, word->GetWord(), sizeof( temp ), COPY_ALL_CHARACTERS ); Q_strncat( temp, " ", sizeof( temp ), COPY_ALL_CHARACTERS ); killspace = true; } // Kill terminal space character int len = Q_strlen( temp ); if ( killspace && ( len >= 1 ) ) { Assert( temp[ len -1 ] == ' ' ); temp[ len - 1 ] = 0; } m_InputWords.SetText( temp ); } m_nLastExtractionResult = SR_RESULT_NORESULT; char szCroppedFile[ 512 ]; char szBaseFile[ 512 ]; Q_StripExtension( m_WorkFile.m_szWaveFile, szBaseFile, sizeof( szBaseFile ) ); Q_snprintf( szCroppedFile, sizeof( szCroppedFile ), "%s%s_work1.wav", m_WorkFile.m_szBasePath, szBaseFile ); filesystem->RemoveFile( szCroppedFile, "GAME" ); if ( !CreateCroppedWave( szCroppedFile, m_nSelection[ 0 ], m_nSelection[ 1 ] ) ) { Con_Printf( "Unable to create cropped wave file %s from samples %i to %i\n", szCroppedFile, m_nSelection[ 0 ], m_nSelection[ 1 ] ); return; } CAudioSource *m_pCroppedWave = sound->LoadSound( szCroppedFile ); if ( !m_pCroppedWave ) { Con_Printf( "Unable to load cropped wave file %s from samples %i to %i\n", szCroppedFile, m_nSelection[ 0 ], m_nSelection[ 1 ] ); return; } // Save any pending stuff SaveLinguisticData(); // Store off copy of complete sentence m_TagsExt = m_Tags; char filename[ 512 ]; Q_snprintf( filename, sizeof( filename ), "%s%s", m_WorkFile.m_szBasePath, szCroppedFile ); m_nLastExtractionResult = m_pPhonemeExtractor->Extract( filename, (int)( m_pCroppedWave->GetRunningLength() * m_pCroppedWave->SampleRate() * m_pCroppedWave->TrueSampleSize() ), Con_Printf, m_InputWords, m_Results ); if ( m_InputWords.m_Words.Size() != m_Results.m_Words.Size() ) { Con_Printf( "Extraction returned %i words, source had %i, try adjusting selection\n", m_Results.m_Words.Size(), m_InputWords.m_Words.Size() ); filesystem->RemoveFile( filename, "GAME" ); redraw(); return; } float bytespersecond = m_pCroppedWave->SampleRate() * m_pCroppedWave->TrueSampleSize(); // Tracker 57389: // Total hack to fix a bug where the Lipsinc extractor is messing up the # channels on 16 bit stereo waves if ( m_pPhonemeExtractor->GetAPIType() == SPEECH_API_LIPSINC && m_pCroppedWave->IsStereoWav() && m_pCroppedWave->SampleSize() == 16 ) { bytespersecond *= 2.0f; } // Now convert byte offsets to times for ( i = 0; i < m_Results.m_Words.Size(); i++ ) { CWordTag *tag = m_Results.m_Words[ i ]; Assert( tag ); if ( !tag ) continue; tag->m_flStartTime = ( float )(tag->m_uiStartByte ) / bytespersecond; tag->m_flEndTime = ( float )(tag->m_uiEndByte ) / bytespersecond; for ( int j = 0; j < tag->m_Phonemes.Size(); j++ ) { CPhonemeTag *ptag = tag->m_Phonemes[ j ]; Assert( ptag ); if ( !ptag ) continue; ptag->SetStartTime( ( float )(ptag->m_uiStartByte ) / bytespersecond ); ptag->SetEndTime( ( float )(ptag->m_uiEndByte ) / bytespersecond ); } } if ( usingselection ) { // Copy data into m_TagsExt, offseting times by selectionstarttime CWordTag *from; CWordTag *to; int fromWord = 0; for ( i = 0; i < m_TagsExt.m_Words.Size() ; i++ ) { to = m_TagsExt.m_Words[ i ]; if ( !to || !to->m_bSelected ) continue; // Found start of contiguous run if ( fromWord >= m_Results.m_Words.Size() ) break; from = m_Results.m_Words[ fromWord++ ]; Assert( from ); if ( !from ) continue; // Remove all phonemes from destination while ( to->m_Phonemes.Size() > 0 ) { CPhonemeTag *p = to->m_Phonemes[ 0 ]; Assert( p ); to->m_Phonemes.Remove( 0 ); delete p; } // Now copy phonemes from source for ( int j = 0; j < from->m_Phonemes.Size(); j++ ) { CPhonemeTag *fromPhoneme = from->m_Phonemes[ j ]; Assert( fromPhoneme ); if ( !fromPhoneme ) continue; CPhonemeTag newPhoneme( *fromPhoneme ); // Offset start time newPhoneme.AddStartTime( selectionstarttime ); newPhoneme.AddEndTime( selectionstarttime ); // Add it back in with corrected timing data CPhonemeTag *p = new CPhonemeTag( newPhoneme ); Assert( p ); if ( p ) { to->m_Phonemes.AddToTail( p ); } } // Done if ( fromWord >= m_Results.m_Words.Size() ) break; } } else { // Find word just before starting point of selection and // place input words into list starting that that point int startWord = 0; CWordTag *firstWordOfPhrase = m_Results.m_Words[ 0 ]; Assert( firstWordOfPhrase ); for ( ; startWord < m_TagsExt.m_Words.Size(); startWord++ ) { CWordTag *w = m_TagsExt.m_Words[ startWord ]; Assert( w ); if ( !w ) continue; if ( w->m_flStartTime > firstWordOfPhrase->m_flStartTime + selectionstarttime ) break; } for ( i = 0; i < m_Results.m_Words.Size(); i++ ) { CWordTag *from = m_Results.m_Words[ i ]; Assert( from ); if ( !from ) continue; CWordTag *to = new CWordTag( *from ); Assert( to ); to->m_flStartTime += selectionstarttime; to->m_flEndTime += selectionstarttime; // Now adjust phoneme times for ( int j = 0; j < to->m_Phonemes.Size(); j++ ) { CPhonemeTag *toPhoneme = to->m_Phonemes[ j ]; Assert( toPhoneme ); if ( !toPhoneme ) continue; // Offset start time toPhoneme->AddStartTime( selectionstarttime ); toPhoneme->AddEndTime( selectionstarttime ); } m_TagsExt.m_Words.InsertBefore( startWord++, to ); } } Con_Printf( "Cleaning up...\n" ); filesystem->RemoveFile( filename, "GAME" ); SetFocus( (HWND)getHandle() ); redraw(); } void PhonemeEditor::RedoPhonemeExtraction( void ) { if ( GetMode() != MODE_PHONEMES ) return; if ( !CheckSpeechAPI() ) return; m_nLastExtractionResult = SR_RESULT_NORESULT; if ( !m_pWaveFile ) return; SaveLinguisticData(); // Send m_WorkFile.m_szWorkingFile to extractor and retrieve resulting data // m_TagsExt.Reset(); Assert( m_pPhonemeExtractor ); char filename[ 512 ]; Q_snprintf( filename, sizeof( filename ), "%s%s", m_WorkFile.m_szBasePath, m_WorkFile.m_szWorkingFile ); m_nLastExtractionResult = m_pPhonemeExtractor->Extract( filename, (int)( m_pWaveFile->GetRunningLength() * m_pWaveFile->SampleRate() * m_pWaveFile->TrueSampleSize() ), Con_Printf, m_Tags, m_TagsExt ); float bytespersecond = m_pWaveFile->SampleRate() * m_pWaveFile->TrueSampleSize(); // Now convert byte offsets to times int i; for ( i = 0; i < m_TagsExt.m_Words.Size(); i++ ) { CWordTag *tag = m_TagsExt.m_Words[ i ]; Assert( tag ); if ( !tag ) continue; tag->m_flStartTime = ( float )(tag->m_uiStartByte ) / bytespersecond; tag->m_flEndTime = ( float )(tag->m_uiEndByte ) / bytespersecond; for ( int j = 0; j < tag->m_Phonemes.Size(); j++ ) { CPhonemeTag *ptag = tag->m_Phonemes[ j ]; Assert( ptag ); if ( !ptag ) continue; ptag->SetStartTime( ( float )(ptag->m_uiStartByte ) / bytespersecond ); ptag->SetEndTime( ( float )(ptag->m_uiEndByte ) / bytespersecond ); } } SetFocus( (HWND)getHandle() ); redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::Deselect( void ) { m_nSelection[ 0 ] = m_nSelection[ 1 ] = 0; m_bSelectionActive = false; } void PhonemeEditor::ITER_SelectSpanningWords( CWordTag *word, float amount ) { Assert( word ); word->m_bSelected = false; if ( !m_bSelectionActive ) return; if ( !m_pWaveFile ) return; float numsamples = m_pWaveFile->GetRunningLength() * m_pWaveFile->SampleRate(); if ( numsamples > 0.0f ) { // Convert sample #'s to time float starttime = ( m_nSelection[ 0 ] / numsamples ) * m_pWaveFile->GetRunningLength(); float endtime = ( m_nSelection[ 1 ] / numsamples ) * m_pWaveFile->GetRunningLength(); if ( word->m_flEndTime >= starttime && word->m_flStartTime <= endtime ) { word->m_bSelected = true; m_bWordsActive = true; } } } //----------------------------------------------------------------------------- // Purpose: // Input : start - // end - //----------------------------------------------------------------------------- void PhonemeEditor::SelectSamples( int start, int end ) { if ( !m_pWaveFile ) return; // Make sure order is correct if ( end < start ) { int temp = end; end = start; start = temp; } Deselect(); m_nSelection[ 0 ] = start; m_nSelection[ 1 ] = end; m_bSelectionActive = true; // Select any words that span the selection // TraverseWords( &PhonemeEditor::ITER_SelectSpanningWords, 0.0f ); redraw(); } void PhonemeEditor::FinishMoveSelection( int startx, int mx ) { if ( !m_pWaveFile ) return; int sampleStart = GetSampleForMouse( startx ); int sampleEnd = GetSampleForMouse( mx ); int delta = sampleEnd - sampleStart; for ( int i = 0; i < 2; i++ ) { m_nSelection[ i ] += delta; } // Select any words that span the selection // TraverseWords( &PhonemeEditor::ITER_SelectSpanningWords, 0.0f ); redraw(); } void PhonemeEditor::FinishMoveSelectionStart( int startx, int mx ) { if ( !m_pWaveFile ) return; int sampleStart = GetSampleForMouse( startx ); int sampleEnd = GetSampleForMouse( mx ); int delta = sampleEnd - sampleStart; m_nSelection[ 0 ] += delta; if ( m_nSelection[ 0 ] >= m_nSelection[ 1 ] ) { Deselect(); } // Select any words that span the selection // TraverseWords( &PhonemeEditor::ITER_SelectSpanningWords, 0.0f ); redraw(); } void PhonemeEditor::FinishMoveSelectionEnd( int startx, int mx ) { if ( !m_pWaveFile ) return; int sampleStart = GetSampleForMouse( startx ); int sampleEnd = GetSampleForMouse( mx ); int delta = sampleEnd - sampleStart; m_nSelection[ 1 ] += delta; if ( m_nSelection[ 1 ] <= m_nSelection[ 0 ] ) { Deselect(); } // Select any words that span the selection // TraverseWords( &PhonemeEditor::ITER_SelectSpanningWords, 0.0f ); redraw(); } //----------------------------------------------------------------------------- // Purpose: // Input : startx - // mx - //----------------------------------------------------------------------------- void PhonemeEditor::FinishSelect( int startx, int mx ) { if ( !m_pWaveFile ) return; // Don't select really small areas if ( abs( startx - mx ) < 2 ) return; int sampleStart = GetSampleForMouse( startx ); int sampleEnd = GetSampleForMouse( mx ); SelectSamples( sampleStart, sampleEnd ); } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // my - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::IsMouseOverSamples( int mx, int my ) { if ( GetMode() != MODE_PHONEMES ) return false; // Deterime if phoneme boundary is under the cursor // if ( !m_pWaveFile ) return false; RECT rc; GetWorkspaceRect( rc ); // Over tag if ( my >= TAG_TOP && my <= TAG_BOTTOM ) return false; if ( IsMouseOverPhonemeRow( my ) ) return false; if ( IsMouseOverWordRow( my ) ) return false; RECT rcWord; GetWordTrayTopBottom( rcWord ); RECT rcPhoneme; GetPhonemeTrayTopBottom( rcPhoneme ); if ( my < rcWord.bottom ) return false; if ( my > rcPhoneme.top ) return false; return true; } void PhonemeEditor::GetScreenStartAndEndTime( float &starttime, float& endtime ) { starttime = m_nLeftOffset / GetPixelsPerSecond(); endtime = w2() / GetPixelsPerSecond() + starttime; } float PhonemeEditor::GetTimePerPixel( void ) { RECT rc; GetWorkspaceRect( rc ); float starttime, endtime; GetScreenStartAndEndTime( starttime, endtime ); if ( rc.right - rc.left <= 0 ) { return ( endtime - starttime ); } float timeperpixel = ( endtime - starttime ) / (float)( rc.right - rc.left ); return timeperpixel; } int PhonemeEditor::GetPixelForSample( int sample ) { RECT rc; GetWorkspaceRect( rc ); if ( !m_pWaveFile ) return rc.left; // Determine start/stop positions int totalsamples = (int)( m_pWaveFile->GetRunningLength() * m_pWaveFile->SampleRate() ); if ( totalsamples <= 0 ) { return rc.left; } float starttime, endtime; GetScreenStartAndEndTime( starttime, endtime ); float sampleFrac = (float)sample / (float)totalsamples; float sampleTime = sampleFrac * (float)m_pWaveFile->GetRunningLength(); if ( endtime - starttime < 0.0f ) { return rc.left; } float windowFrac = ( sampleTime - starttime ) / ( endtime - starttime ); return rc.left + (int)( windowFrac * ( rc.right - rc.left ) ); } int PhonemeEditor::GetSampleForMouse( int mx ) { if ( !m_pWaveFile ) return 0; RECT rc; GetWorkspaceRect( rc ); // Determine start/stop positions int totalsamples = (int)( m_pWaveFile->GetRunningLength() * m_pWaveFile->SampleRate() ); float starttime, endtime; GetScreenStartAndEndTime( starttime, endtime ); if ( GetPixelsPerSecond() <= 0 ) return 0; // Start and end times float clickTime = (float)mx / GetPixelsPerSecond() + starttime; // What sample do these correspond to if ( (float)m_pWaveFile->GetRunningLength() <= 0.0f ) return 0; int sampleNumber = (int) ( (float)totalsamples * clickTime / (float)m_pWaveFile->GetRunningLength() ); return sampleNumber; } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // my - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::IsMouseOverSelection( int mx, int my ) { if ( GetMode() != MODE_PHONEMES ) return false; if ( !m_pWaveFile ) return false; if ( !m_bSelectionActive ) return false; if ( !IsMouseOverSamples( mx, my ) ) return false; int sampleNumber = GetSampleForMouse( mx ); if ( sampleNumber >= m_nSelection[ 0 ] - 3 && sampleNumber <= m_nSelection[ 1 ] + 3 ) { return true; } return false; } bool PhonemeEditor::IsMouseOverSelectionStartEdge( mxEvent *event ) { if ( GetMode() != MODE_PHONEMES ) return false; if ( !m_pWaveFile ) return false; int mx, my; mx = (short)event->x; my = (short)event->y; if ( !(event->modifiers & mxEvent::KeyCtrl ) ) return false; if ( !IsMouseOverSelection( mx, my ) ) return false; int sample = GetSampleForMouse( mx ); int mouse_tolerance = 5; RECT rc; GetWorkspaceRect( rc ); // Determine start/stop positions float timeperpixel = GetTimePerPixel(); int samplesperpixel = (int)( timeperpixel * m_pWaveFile->SampleRate() ); if ( abs( sample - m_nSelection[ 0 ] ) < mouse_tolerance * samplesperpixel ) { return true; } return false; } bool PhonemeEditor::IsMouseOverSelectionEndEdge( mxEvent *event ) { if ( GetMode() != MODE_PHONEMES ) return false; if ( !m_pWaveFile ) return false; int mx, my; mx = (short)event->x; my = (short)event->y; if ( !(event->modifiers & mxEvent::KeyCtrl ) ) return false; if ( !IsMouseOverSelection( mx, my ) ) return false; int sample = GetSampleForMouse( mx ); int mouse_tolerance = 5; RECT rc; GetWorkspaceRect( rc ); if ( GetPixelsPerSecond() <= 0.0f ) return false; if ( ( rc.right - rc.left ) <= 0 ) return false; // Determine start/stop positions float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; float timeperpixel = ( endtime - starttime ) / (float)( rc.right - rc.left ); int samplesperpixel = (int)( timeperpixel * m_pWaveFile->SampleRate() ); if ( abs( sample - m_nSelection[ 1 ] ) < mouse_tolerance * samplesperpixel ) { return true; } return false; } void PhonemeEditor::OnImport() { char filename[ 512 ]; if ( !FacePoser_ShowOpenFileNameDialog( filename, sizeof( filename ), "sound", "*" WORD_DATA_EXTENSION ) ) { return; } ImportValveDataChunk( filename ); } void PhonemeEditor::OnExport() { if ( !m_pWaveFile ) return; char filename[ 512 ]; if ( !FacePoser_ShowSaveFileNameDialog( filename, sizeof( filename ), "sound", "*" WORD_DATA_EXTENSION ) ) { return; } Q_SetExtension( filename, WORD_DATA_EXTENSION, sizeof( filename ) ); ExportValveDataChunk( filename ); } //----------------------------------------------------------------------------- // Purpose: // Input : store - //----------------------------------------------------------------------------- void PhonemeEditor::StoreValveDataChunk( IterateOutputRIFF& store ) { // Buffer and dump data CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER ); m_Tags.SaveToBuffer( buf ); // Copy into store store.ChunkWriteData( buf.Base(), buf.TellPut() ); } //----------------------------------------------------------------------------- // Purpose: // Input : *tempfile - //----------------------------------------------------------------------------- void PhonemeEditor::ExportValveDataChunk( char const *tempfile ) { if ( m_Tags.m_Words.Count() <= 0 ) { Con_ErrorPrintf( "PhonemeEditor::ExportValveDataChunk: Sentence has no word data\n" ); return; } FileHandle_t fh = filesystem->Open( tempfile, "wb" ); if ( !fh ) { Con_ErrorPrintf( "PhonemeEditor::ExportValveDataChunk: Unable to write to %s (read-only?)\n", tempfile ); return; } else { // Buffer and dump data CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER ); m_Tags.SaveToBuffer( buf ); filesystem->Write( buf.Base(), buf.TellPut(), fh ); filesystem->Close(fh); Con_Printf( "Exported %i words to %s\n", m_Tags.m_Words.Count(), tempfile ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *tempfile - //----------------------------------------------------------------------------- void PhonemeEditor::ImportValveDataChunk( char const *tempfile ) { FileHandle_t fh = filesystem->Open( tempfile, "rb" ); if ( !fh ) { Con_ErrorPrintf( "PhonemeEditor::ImportValveDataChunk: Unable to read from %s\n", tempfile ); return; } int len = filesystem->Size( fh ); if ( len <= 4 ) { Con_ErrorPrintf( "PhonemeEditor::ImportValveDataChunk: File %s has length 0\n", tempfile ); return; } ClearExtracted(); unsigned char *buf = new unsigned char[ len + 1 ]; filesystem->Read( buf, len, fh ); filesystem->Close( fh ); m_TagsExt.InitFromDataChunk( (void *)( buf ), len ); delete[] buf; Con_Printf( "Imported %i words from %s\n", m_TagsExt.m_Words.Count(), tempfile ); redraw(); } //----------------------------------------------------------------------------- // Purpose: Copy file over, but update phoneme lump with new data //----------------------------------------------------------------------------- void PhonemeEditor::SaveLinguisticData( void ) { if ( !m_pWaveFile ) return; InFileRIFF riff( m_WorkFile.m_szWaveFile, io_in ); Assert( riff.RIFFName() == RIFF_WAVE ); // set up the iterator for the whole file (root RIFF is a chunk) IterateRIFF walk( riff, riff.RIFFSize() ); char fullout[ 512 ]; Q_snprintf( fullout, sizeof( fullout ), "%s%s", m_WorkFile.m_szBasePath, m_WorkFile.m_szWorkingFile ); OutFileRIFF riffout( fullout, io_out ); IterateOutputRIFF store( riffout ); bool formatset = false; WAVEFORMATEX format; bool wordtrackwritten = false; // Walk input chunks and copy to output while ( walk.ChunkAvailable() ) { unsigned int originalPos = store.ChunkGetPosition(); store.ChunkStart( walk.ChunkName() ); bool skipchunk = false; switch ( walk.ChunkName() ) { case WAVE_VALVEDATA: // Overwrite data StoreValveDataChunk( store ); wordtrackwritten = true; break; case WAVE_FMT: { formatset = true; char *buffer = new char[ walk.ChunkSize() ]; Assert( buffer ); walk.ChunkRead( buffer ); format = *(WAVEFORMATEX *)buffer; store.ChunkWriteData( buffer, walk.ChunkSize() ); delete[] buffer; } break; case WAVE_DATA: { Assert( formatset ); char *buffer = new char[ walk.ChunkSize() ]; Assert( buffer ); walk.ChunkRead( buffer ); // Resample it ResampleChunk( store, (void *)&format, walk.ChunkName(), buffer, walk.ChunkSize() ); delete[] buffer; } break; default: store.CopyChunkData( walk ); break; } store.ChunkFinish(); if ( skipchunk ) { store.ChunkSetPosition( originalPos ); } walk.ChunkNext(); } if ( !wordtrackwritten ) { store.ChunkStart( WAVE_VALVEDATA ); StoreValveDataChunk( store ); store.ChunkFinish(); } } //----------------------------------------------------------------------------- // Purpose: Copy phoneme data in from wave file we sent for resprocessing //----------------------------------------------------------------------------- void PhonemeEditor::RetrieveLinguisticData( void ) { if ( !m_pWaveFile ) return; m_Tags.Reset(); ReadLinguisticTags(); redraw(); } bool PhonemeEditor::StopPlayback( void ) { bool bret = false; if ( m_pWaveFile ) { SetScrubTargetTime( m_flScrub ); if ( sound->IsSoundPlaying( m_pMixer ) ) { sound->StopAll(); bret = true; } } sound->Flush(); return bret; } CPhonemeTag *PhonemeEditor::GetPhonemeTagUnderMouse( int mx, int my ) { if ( GetMode() != MODE_PHONEMES ) return NULL; if ( !m_pWaveFile ) return NULL; // FIXME: Don't read from file, read from arrays after LISET finishes // Deterime if phoneme boundary is under the cursor // RECT rc; GetWorkspaceRect( rc ); if ( !IsMouseOverPhonemeRow( my ) ) return NULL; if ( GetPixelsPerSecond() <= 0 ) return NULL; float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; if ( endtime - starttime <= 0.0f ) return NULL; for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; Assert( word ); if ( !word ) continue; for ( int k = 0; k < word->m_Phonemes.Size(); k++ ) { CPhonemeTag *pPhoneme = word->m_Phonemes[ k ]; Assert( pPhoneme ); if ( !pPhoneme ) continue; float t1 = pPhoneme->GetStartTime(); float t2 = pPhoneme->GetEndTime(); float frac1 = ( t1 - starttime ) / ( endtime - starttime ); float frac2 = ( t2 - starttime ) / ( endtime - starttime ); frac1 = min( 1.0f, frac1 ); frac1 = max( 0.0f, frac1 ); frac2 = min( 1.0f, frac2 ); frac2 = max( 0.0f, frac2 ); if ( frac1 == frac2 ) continue; int x1 = ( int )( frac1 * w2() ); int x2 = ( int )( frac2 * w2() ); if ( mx >= x1 && mx <= x2 ) { return pPhoneme; } } } return NULL; } CWordTag *PhonemeEditor::GetWordTagUnderMouse( int mx, int my ) { if ( GetMode() != MODE_PHONEMES ) return NULL; // Deterime if phoneme boundary is under the cursor // if ( !m_pWaveFile ) return NULL; RECT rc; GetWorkspaceRect( rc ); if ( !IsMouseOverWordRow( my ) ) return NULL; if ( GetPixelsPerSecond() <= 0 ) return NULL; float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; if ( endtime - starttime <= 0.0f ) return NULL; for ( int k = 0; k < m_Tags.m_Words.Size(); k++ ) { CWordTag *word = m_Tags.m_Words[ k ]; Assert( word ); if ( !word ) continue; float t1 = word->m_flStartTime; float t2 = word->m_flEndTime; float frac1 = ( t1 - starttime ) / ( endtime - starttime ); float frac2 = ( t2 - starttime ) / ( endtime - starttime ); frac1 = min( 1.0f, frac1 ); frac1 = max( 0.0f, frac1 ); frac2 = min( 1.0f, frac2 ); frac2 = max( 0.0f, frac2 ); if ( frac1 == frac2 ) continue; int x1 = ( int )( frac1 * w2() ); int x2 = ( int )( frac2 * w2() ); if ( mx >= x1 && mx <= x2 ) { return word; } } return NULL; } void PhonemeEditor::DeselectWords( void ) { if ( GetMode() != MODE_PHONEMES ) return; for ( int i = 0 ; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *w = m_Tags.m_Words[ i ]; Assert( w ); if ( !w ) continue; w->m_bSelected = false; } } void PhonemeEditor::DeselectPhonemes( void ) { if ( GetMode() != MODE_PHONEMES ) return; for ( int w = 0 ; w < m_Tags.m_Words.Size(); w++ ) { CWordTag *word = m_Tags.m_Words[ w ]; Assert( word ); if ( !word ) continue; for ( int i = 0 ; i < word->m_Phonemes.Size(); i++ ) { CPhonemeTag *pt = word->m_Phonemes[ i ]; Assert( pt ); if ( !pt ) continue; pt->m_bSelected = false; } } } void PhonemeEditor::SnapWords( void ) { if ( GetMode() != MODE_PHONEMES ) return; if ( m_Tags.m_Words.Size() < 2 ) { Con_Printf( "Can't snap, need at least two contiguous selected words\n" ); return; } SetDirty( true ); PushUndo(); for ( int i = 0; i < m_Tags.m_Words.Size() - 1; i++ ) { CWordTag *current = m_Tags.m_Words[ i ]; CWordTag *next = m_Tags.m_Words[ i + 1 ]; Assert( current && next ); if ( !current->m_bSelected || !next->m_bSelected ) continue; // Move next word to end of current next->m_flStartTime = current->m_flEndTime; } PushRedo(); redraw(); } void PhonemeEditor::SeparateWords( void ) { if ( GetMode() != MODE_PHONEMES ) return; if ( GetPixelsPerSecond() <= 0.0f ) return; if ( m_Tags.m_Words.Size() < 2 ) { Con_Printf( "Can't separate, need at least two contiguous selected words\n" ); return; } // Three pixels double time_epsilon = ( 1.0f / GetPixelsPerSecond() ) * 6; SetDirty( true ); PushUndo(); for ( int i = 0; i < m_Tags.m_Words.Size() - 1; i++ ) { CWordTag *current = m_Tags.m_Words[ i ]; CWordTag *next = m_Tags.m_Words[ i + 1 ]; Assert( current && next ); if ( !current->m_bSelected || !next->m_bSelected ) continue; // Close enough? if ( fabs( current->m_flEndTime - next->m_flStartTime ) > time_epsilon ) { Con_Printf( "Can't split %s and %s, already split apart\n", current->GetWord(), next->GetWord() ); continue; } // Offset next word start time a bit next->m_flStartTime += time_epsilon; break; } PushRedo(); redraw(); } void PhonemeEditor::CreateEvenWordDistribution( const char *wordlist ) { if ( GetMode() != MODE_PHONEMES ) return; if( !m_pWaveFile ) return; Assert( wordlist ); if ( !wordlist ) return; m_Tags.CreateEventWordDistribution( wordlist, m_pWaveFile->GetRunningLength() ); redraw(); } void PhonemeEditor::EditWordList( void ) { if ( GetMode() != MODE_PHONEMES ) return; if ( !m_pWaveFile ) return; // Build word string char wordstring[ 1024 ]; V_strcpy_safe( wordstring, m_Tags.GetText() ); CInputParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Word List" ); strcpy( params.m_szPrompt, "Sentence:" ); strcpy( params.m_szInputText, wordstring ); if ( !InputProperties( &params ) ) return; if ( strlen( params.m_szInputText ) <= 0 ) { // Could be foreign language... Warning( "Edit word list: No words entered!\n" ); } SetDirty( true ); PushUndo(); // Clear any current LISET results ClearExtracted(); // Force text m_Tags.SetText( params.m_szInputText ); if ( m_Tags.m_Words.Size() == 0 ) { // First text we've seen, just distribute words evenly CreateEvenWordDistribution( params.m_szInputText ); // Redo liset RedoPhonemeExtraction(); } PushRedo(); SetFocus( (HWND)getHandle() ); redraw(); } //----------------------------------------------------------------------------- // Purpose: Overwrite original wave with changes //----------------------------------------------------------------------------- void PhonemeEditor::CommitChanges( void ) { SaveLinguisticData(); // Make it writable - if possible MakeFileWriteable( m_WorkFile.m_szWaveFile ); //Open a message box to warn the user if the file was unable to be made non-read only if ( !IsFileWriteable( m_WorkFile.m_szWaveFile ) ) { mxMessageBox( NULL, va( "Unable to save file '%s'. File is read-only or in use.", m_WorkFile.m_szWaveFile ), g_appTitle, MX_MB_OK ); } else { // Copy over and overwrite file FPCopyFile( m_WorkFile.m_szWorkingFile, m_WorkFile.m_szWaveFile, true ); Msg( "Changes saved to '%s'\n", m_WorkFile.m_szWaveFile ); SetDirty( false, false ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::LoadWaveFile( void ) { char filename[ 512 ]; if ( !FacePoser_ShowOpenFileNameDialog( filename, sizeof( filename ), "sound", "*.wav" ) ) { return; } StopPlayback(); // Strip out the game directory SetCurrentWaveFile( filename ); } void PhonemeEditor::SnapPhonemes( void ) { if ( GetMode() != MODE_PHONEMES ) return; SetDirty( true ); PushUndo(); CPhonemeTag *prev = NULL; for ( int w = 0; w < m_Tags.m_Words.Size(); w++ ) { CWordTag *word = m_Tags.m_Words[ w ]; Assert( word ); if ( !word ) continue; for ( int i = 0; i < word->m_Phonemes.Size(); i++ ) { CPhonemeTag *current = word->m_Phonemes[ i ]; Assert( current ); if ( current->m_bSelected ) { if (prev) { // More start of next to end of previous prev->SetEndTime( current->GetStartTime() ); } prev = current; } else { prev = NULL; } } } PushRedo(); redraw(); } void PhonemeEditor::SeparatePhonemes( void ) { if ( GetMode() != MODE_PHONEMES ) return; SetDirty( true ); PushUndo(); // Three pixels double time_epsilon = ( 1.0f / GetPixelsPerSecond() ) * 6; CPhonemeTag *prev = NULL; for ( int w = 0; w < m_Tags.m_Words.Size(); w++ ) { CWordTag *word = m_Tags.m_Words[ w ]; Assert( word ); if ( !word ) continue; for ( int i = 0; i < word->m_Phonemes.Size(); i++ ) { CPhonemeTag *current = word->m_Phonemes[ i ]; Assert( current ); if ( current->m_bSelected ) { if ( prev ) { // Close enough? if ( fabs( prev->GetEndTime() - current->GetStartTime() ) > time_epsilon ) { Con_Printf( "Can't split already split apart\n" ); continue; } current->AddStartTime( time_epsilon ); } prev = current; } else { prev = NULL; } } } PushRedo(); redraw(); } bool PhonemeEditor::IsMouseOverWordRow( int my ) { if ( GetMode() != MODE_PHONEMES ) return false; RECT rc; GetWordTrayTopBottom( rc ); if ( my < rc.top ) return false; if ( my > rc.bottom ) return false; return true; } bool PhonemeEditor::IsMouseOverPhonemeRow( int my ) { if ( GetMode() != MODE_PHONEMES ) return false; RECT rc; GetPhonemeTrayTopBottom( rc ); if ( my < rc.top ) return false; if ( my > rc.bottom ) return false; return true; } void PhonemeEditor::GetPhonemeTrayTopBottom( RECT& rc ) { RECT wkrc; GetWorkspaceRect( wkrc ); rc.top = wkrc.bottom - 2 * m_nTickHeight; rc.bottom = wkrc.bottom - m_nTickHeight; } void PhonemeEditor::GetWordTrayTopBottom( RECT& rc ) { RECT wkrc; GetWorkspaceRect( wkrc ); rc.top = wkrc.top; rc.bottom = wkrc.top + m_nTickHeight; } int PhonemeEditor::GetMouseForTime( float time ) { RECT rc; GetWorkspaceRect( rc ); if ( GetPixelsPerSecond() < 0.0f ) return rc.left; float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; if ( endtime - starttime <= 0.0f ) return rc.left; float frac; frac = ( time - starttime ) / ( endtime - starttime ); return rc.left + ( int )( rc.right * frac ); } void PhonemeEditor::GetWordRect( const CWordTag *tag, RECT& rc ) { Assert( tag ); GetWordTrayTopBottom( rc ); rc.left = GetMouseForTime( tag->m_flStartTime ); rc.right = GetMouseForTime( tag->m_flEndTime ); } void PhonemeEditor::GetPhonemeRect( const CPhonemeTag *tag, RECT& rc ) { Assert( tag ); GetPhonemeTrayTopBottom( rc ); rc.left = GetMouseForTime( tag->GetStartTime() ); rc.right = GetMouseForTime( tag->GetEndTime() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::CommitExtracted( void ) { if ( GetMode() != MODE_PHONEMES ) return; m_nLastExtractionResult = SR_RESULT_NORESULT; if ( !m_TagsExt.m_Words.Size() ) return; SetDirty( true ); PushUndo(); m_Tags.Reset(); m_Tags = m_TagsExt; PushRedo(); ClearExtracted(); redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::ClearExtracted( void ) { if ( GetMode() != MODE_PHONEMES ) return; m_nLastExtractionResult = SR_RESULT_NORESULT; m_TagsExt.Reset(); redraw(); } //----------------------------------------------------------------------------- // Purpose: // Input : resultCode - // Output : const char //----------------------------------------------------------------------------- const char *PhonemeEditor::GetExtractionResultString( int resultCode ) { switch ( resultCode ) { case SR_RESULT_NORESULT: return "no extraction info."; case SR_RESULT_ERROR: return "an error occurred during extraction."; case SR_RESULT_SUCCESS: return "successful."; case SR_RESULT_FAILED: return "results retrieved, but full recognition failed."; default: break; } return "unknown result code."; } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // Output : CEventRelativeTag //----------------------------------------------------------------------------- CEventRelativeTag *PhonemeEditor::GetTagUnderMouse( int mx ) { if ( GetMode() != MODE_PHONEMES ) return NULL; // Figure out tag positions if ( !m_pEvent || !m_pWaveFile ) return NULL; RECT rc; GetWorkspaceRect( rc ); RECT rcTags = rc; if ( GetPixelsPerSecond() <= 0.0f ) return NULL; float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; if ( endtime - starttime < 0 ) return NULL; for ( int i = 0; i < m_pEvent->GetNumRelativeTags(); i++ ) { CEventRelativeTag *tag = m_pEvent->GetRelativeTag( i ); if ( !tag ) continue; // float tagtime = tag->GetPercentage() * m_pWaveFile->GetRunningLength(); if ( tagtime < starttime || tagtime > endtime ) continue; float frac = ( tagtime - starttime ) / ( endtime - starttime ); int left = rcTags.left + (int)( frac * ( float )( rcTags.right - rcTags.left ) + 0.5f ); if ( abs( mx - left ) < 10 ) return tag; } return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // my - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::IsMouseOverTag( int mx, int my ) { if ( GetMode() != MODE_PHONEMES ) return false; if ( !IsMouseOverTagRow( my ) ) return false; CEventRelativeTag *tag = GetTagUnderMouse( mx ); if ( !tag ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: // Input : startx - // endx - //----------------------------------------------------------------------------- void PhonemeEditor::FinishEventTagDrag( int startx, int endx ) { if ( !m_pWaveFile ) return; if ( !m_pWaveFile->GetRunningLength() ) return; // Find starting tag CEventRelativeTag *tag = GetTagUnderMouse( startx ); if ( !tag ) return; if ( GetPixelsPerSecond() <= 0 ) return; // Convert mouse position to time float starttime = m_nLeftOffset / GetPixelsPerSecond(); float clicktime = (float)endx / GetPixelsPerSecond() + starttime; float percent = clicktime / m_pWaveFile->GetRunningLength(); percent = clamp( percent, 0.0f, 1.0f ); tag->SetPercentage( percent ); redraw(); if ( g_pChoreoView ) { g_pChoreoView->InvalidateLayout(); } } //----------------------------------------------------------------------------- // Purpose: // Input : my - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::IsMouseOverTagRow( int my ) { if ( GetMode() != MODE_PHONEMES ) return false; if ( my < TAG_TOP || my > TAG_BOTTOM ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: // Input : mx - // my - //----------------------------------------------------------------------------- void PhonemeEditor::ShowTagMenu( int mx, int my ) { if ( GetMode() != MODE_PHONEMES ) return; // Figure out tag positions if ( !m_pEvent || !m_pWaveFile ) return; if ( !IsMouseOverTagRow( my ) ) return; CEventRelativeTag *tag = GetTagUnderMouse( mx ); mxPopupMenu *pop = new mxPopupMenu(); if ( tag ) { pop->add( va( "Delete tag '%s'", tag->GetName() ), IDC_DELETETAG ); } else { pop->add( va( "Add tag..." ), IDC_ADDTAG ); } m_nClickX = mx; pop->popup( this, mx, my ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::DeleteTag( void ) { if ( GetMode() != MODE_PHONEMES ) return; // Figure out tag positions if ( !m_pEvent ) return; CEventRelativeTag *tag = GetTagUnderMouse( m_nClickX ); if ( !tag ) return; // Remove it m_pEvent->RemoveRelativeTag( tag->GetName() ); g_pChoreoView->InvalidateLayout(); redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::AddTag( void ) { if ( GetMode() != MODE_PHONEMES ) return; // Figure out tag positions if ( !m_pEvent || !m_pWaveFile ) return; CInputParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Event Tag Name" ); strcpy( params.m_szPrompt, "Name:" ); strcpy( params.m_szInputText, "" ); if ( !InputProperties( &params ) ) return; if ( strlen( params.m_szInputText ) <= 0 ) { Con_ErrorPrintf( "Event Tag Name: No name entered!\n" ); return; } // Convert mouse position to time float starttime = m_nLeftOffset / GetPixelsPerSecond(); float clicktime = (float)m_nClickX / GetPixelsPerSecond() + starttime; float percent = clicktime / m_pWaveFile->GetRunningLength(); percent = min( 1.0f, percent ); percent = max( 0.0f, percent ); m_pEvent->AddRelativeTag( params.m_szInputText, percent ); g_pChoreoView->InvalidateLayout(); SetFocus( (HWND)getHandle() ); redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::ClearEvent( void ) { m_pEvent = NULL; redraw(); } void PhonemeEditor::TraverseWords( PEWORDITERFUNC pfn, float fparam ) { for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; (this->*pfn)( word, fparam ); } } void PhonemeEditor::TraversePhonemes( PEPHONEMEITERFUNC pfn, float fparam ) { for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; for ( int j = 0; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *phoneme = word->m_Phonemes[ j ]; if ( !phoneme ) continue; (this->*pfn)( phoneme, word, fparam ); } } } //----------------------------------------------------------------------------- // Purpose: // Input : amount - //----------------------------------------------------------------------------- void PhonemeEditor::ITER_MoveSelectedWords( CWordTag *word, float amount ) { if ( !word->m_bSelected ) return; word->m_flStartTime += amount; word->m_flEndTime += amount; } void PhonemeEditor::ITER_MoveSelectedPhonemes( CPhonemeTag *phoneme, CWordTag *word, float amount ) { if ( !phoneme->m_bSelected ) return; phoneme->AddStartTime( amount ); phoneme->AddEndTime( amount ); } void PhonemeEditor::ITER_ExtendSelectedPhonemeEndTimes( CPhonemeTag *phoneme, CWordTag *word, float amount ) { if ( !phoneme->m_bSelected ) return; if ( phoneme->GetEndTime() + amount <= phoneme->GetStartTime() ) return; phoneme->AddEndTime( amount ); // Fixme, check for extending into next phoneme } void PhonemeEditor::ITER_ExtendSelectedWordEndTimes( CWordTag *word, float amount ) { if ( !word->m_bSelected ) return; if ( word->m_flEndTime + amount <= word->m_flStartTime ) return; word->m_flEndTime += amount; // Fixme, check for extending into next word } void PhonemeEditor::ITER_AddFocusRectSelectedWords( CWordTag *word, float amount ) { if ( !word->m_bSelected ) return; RECT wordRect; GetWordRect( word, wordRect ); AddFocusRect( wordRect ); } void PhonemeEditor::ITER_AddFocusRectSelectedPhonemes( CPhonemeTag *phoneme, CWordTag *word, float amount ) { if ( !phoneme->m_bSelected ) return; RECT phonemeRect; GetPhonemeRect( phoneme, phonemeRect ); AddFocusRect( phonemeRect ); } void PhonemeEditor::AddFocusRect( RECT& rc ) { RECT rcFocus = rc; POINT offset; offset.x = 0; offset.y = 0; ClientToScreen( (HWND)getHandle(), &offset ); OffsetRect( &rcFocus, offset.x, offset.y ); // Convert to screen space? CFocusRect fr; fr.m_rcFocus = rcFocus; fr.m_rcOrig = rcFocus; m_FocusRects.AddToTail( fr ); } void PhonemeEditor::CountSelected( void ) { m_nSelectedPhonemeCount = 0; m_nSelectedWordCount = 0; TraverseWords( &PhonemeEditor::ITER_CountSelectedWords, 0.0f ); TraversePhonemes( &PhonemeEditor::ITER_CountSelectedPhonemes, 0.0f ); } void PhonemeEditor::ITER_CountSelectedWords( CWordTag *word, float amount ) { if ( !word->m_bSelected ) return; m_nSelectedWordCount++; } void PhonemeEditor::ITER_CountSelectedPhonemes( CPhonemeTag *phoneme, CWordTag *word, float amount ) { if ( !phoneme->m_bSelected ) return; m_nSelectedPhonemeCount++; } // Undo/Redo void PhonemeEditor::Undo( void ) { if ( m_UndoStack.Size() > 0 && m_nUndoLevel > 0 ) { m_nUndoLevel--; PEUndo *u = m_UndoStack[ m_nUndoLevel ]; Assert( u->undo ); m_Tags = *(u->undo); SetClickedPhoneme( -1, -1 ); } redraw(); } void PhonemeEditor::Redo( void ) { if ( m_UndoStack.Size() > 0 && m_nUndoLevel <= m_UndoStack.Size() - 1 ) { PEUndo *u = m_UndoStack[ m_nUndoLevel ]; Assert( u->redo ); m_Tags = *(u->redo); m_nUndoLevel++; SetClickedPhoneme( -1, -1 ); } redraw(); } void PhonemeEditor::PushUndo( void ) { Assert( !m_bRedoPending ); m_bRedoPending = true; WipeRedo(); // Copy current data CSentence *u = new CSentence(); *u = m_Tags; PEUndo *undo = new PEUndo; undo->undo = u; undo->redo = NULL; m_UndoStack.AddToTail( undo ); m_nUndoLevel++; } void PhonemeEditor::PushRedo( void ) { Assert( m_bRedoPending ); m_bRedoPending = false; // Copy current data CSentence *r = new CSentence(); *r = m_Tags; PEUndo *undo = m_UndoStack[ m_nUndoLevel - 1 ]; undo->redo = r; } void PhonemeEditor::WipeUndo( void ) { while ( m_UndoStack.Size() > 0 ) { PEUndo *u = m_UndoStack[ 0 ]; delete u->undo; delete u->redo; delete u; m_UndoStack.Remove( 0 ); } m_nUndoLevel = 0; } void PhonemeEditor::WipeRedo( void ) { // Wipe everything above level while ( m_UndoStack.Size() > m_nUndoLevel ) { PEUndo *u = m_UndoStack[ m_nUndoLevel ]; delete u->undo; delete u->redo; delete u; m_UndoStack.Remove( m_nUndoLevel ); } } //----------------------------------------------------------------------------- // Purpose: // Input : word - // phoneme - //----------------------------------------------------------------------------- void PhonemeEditor::SetClickedPhoneme( int word, int phoneme ) { m_nClickedPhoneme = phoneme; m_nClickedWord = word; } //----------------------------------------------------------------------------- // Purpose: // Output : CPhonemeTag //----------------------------------------------------------------------------- CPhonemeTag *PhonemeEditor::GetClickedPhoneme( void ) { if ( m_nClickedPhoneme < 0 || m_nClickedWord < 0 ) return NULL; if ( m_nClickedWord >= m_Tags.m_Words.Size() ) return NULL; CWordTag *word = m_Tags.m_Words[ m_nClickedWord ]; if ( !word ) return NULL; if ( m_nClickedPhoneme >= word->m_Phonemes.Size() ) return NULL; CPhonemeTag *phoneme = word->m_Phonemes[ m_nClickedPhoneme ]; return phoneme; } //----------------------------------------------------------------------------- // Purpose: // Output : CWordTag //----------------------------------------------------------------------------- CWordTag *PhonemeEditor::GetClickedWord( void ) { if ( m_nClickedWord < 0 ) return NULL; if ( m_nClickedWord >= m_Tags.m_Words.Size() ) return NULL; CWordTag *word = m_Tags.m_Words[ m_nClickedWord ]; return word; } void PhonemeEditor::ShowContextMenu_Phonemes( int mx, int my ) { CountSelected(); // Construct main mxPopupMenu *pop = new mxPopupMenu(); if ( m_pWaveFile ) { mxPopupMenu *play = new mxPopupMenu; play->add( va( "Original" ), IDC_PHONEME_PLAY_ORIG ); play->add( va( "Edited" ), IDC_PLAY_EDITED ); if ( m_bSelectionActive ) { play->add( va( "Selection" ), IDC_PLAY_EDITED_SELECTION ); } pop->addMenu( "Play", play ); if ( sound->IsSoundPlaying( m_pMixer ) ) { pop->add( va( "Cancel playback" ), IDC_CANCELPLAYBACK ); } pop->addSeparator(); } pop->add( va( "Load..." ), IDC_LOADWAVEFILE ); if ( m_pWaveFile ) { pop->add( va( "Save" ), IDC_SAVE_LINGUISTIC ); } if ( m_bSelectionActive ) { pop->addSeparator(); pop->add( va( "Deselect" ), IDC_DESELECT ); } if ( m_pWaveFile ) { pop->addSeparator(); pop->add( va( "Redo Extraction" ), IDC_REDO_PHONEMEEXTRACTION ); if ( m_nSelectedWordCount < 1 || AreSelectedWordsContiguous() ) { pop->add( va( "Redo Extraction of selected words" ), IDC_REDO_PHONEMEEXTRACTION_SELECTION ); } } if ( m_pWaveFile && m_TagsExt.m_Words.Size() ) { pop->addSeparator(); pop->add( va( "Commit extraction" ) , IDC_COMMITEXTRACTED ); pop->add( va( "Clear extraction" ), IDC_CLEAREXTRACTED ); } if ( m_nUndoLevel != 0 || m_nUndoLevel != m_UndoStack.Size() ) { pop->addSeparator(); if ( m_nUndoLevel != 0 ) { pop->add( va( "Undo" ), IDC_UNDO ); } if ( m_nUndoLevel != m_UndoStack.Size() ) { pop->add( va( "Redo" ), IDC_REDO ); } pop->add( va( "Clear Undo Info" ), IDC_CLEARUNDO ); } if ( m_Tags.m_Words.Size() > 0 ) { pop->addSeparator(); pop->add( va( "Cleanup words/phonemes" ), IDC_CLEANUP ); } // Show hierarchical options menu { mxPopupMenu *api = 0; if ( DoesExtractorExistFor( SPEECH_API_SAPI ) ) { api = new mxPopupMenu(); api->add( "Microsoft Speech API", IDC_API_SAPI ); if ( g_viewerSettings.speechapiindex == SPEECH_API_SAPI ) { api->setChecked( IDC_API_SAPI, true ); } } if ( DoesExtractorExistFor( SPEECH_API_LIPSINC ) ) { if ( !api ) api = new mxPopupMenu(); api->add( "Lipsinc Speech API", IDC_API_LIPSINC ); if ( g_viewerSettings.speechapiindex == SPEECH_API_LIPSINC ) { api->setChecked( IDC_API_LIPSINC, true ); } } pop->addSeparator(); pop->addMenu( "Change Speech API", api ); } // Import export menu if ( m_pWaveFile ) { pop->addSeparator(); if ( m_Tags.m_Words.Count() > 0 ) { pop->add( "Export word data to " WORD_DATA_EXTENSION "...", IDC_EXPORT_SENTENCE ); } pop->add( "Import word data from " WORD_DATA_EXTENSION "...", IDC_IMPORT_SENTENCE ); pop->add( va("%s Voice Duck", m_Tags.GetVoiceDuck() ? "Disable" : "Enable" ), IDC_TOGGLE_VOICEDUCK ); } pop->popup( this, mx, my ); } void PhonemeEditor::ShowContextMenu_Emphasis( int mx, int my ) { Emphasis_CountSelected(); // Construct main mxPopupMenu *pop = new mxPopupMenu(); pop->add( va( "Select All" ), IDC_EMPHASIS_SELECTALL ); if ( m_nNumSelected > 0 ) { pop->add( va( "Deselect All" ), IDC_EMPHASIS_DESELECT ); } if ( m_nUndoLevel != 0 || m_nUndoLevel != m_UndoStack.Size() ) { pop->addSeparator(); if ( m_nUndoLevel != 0 ) { pop->add( va( "Undo" ), IDC_UNDO ); } if ( m_nUndoLevel != m_UndoStack.Size() ) { pop->add( va( "Redo" ), IDC_REDO ); } pop->add( va( "Clear Undo Info" ), IDC_CLEARUNDO ); } pop->popup( this, mx, my ); } void PhonemeEditor::ShowContextMenu( int mx, int my ) { switch ( GetMode() ) { default: case MODE_PHONEMES: ShowContextMenu_Phonemes( mx, my ); break; case MODE_EMPHASIS: ShowContextMenu_Emphasis( mx, my ); break; } } void PhonemeEditor::ShiftSelectedPhoneme( int direction ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); switch ( m_nSelectedPhonemeCount ) { case 1: break; case 0: Con_Printf( "Can't shift phonemes, none selected\n" ); return; default: Con_Printf( "Can only shift one phoneme at a time via keyboard\n" ); return; } RECT rc; GetWorkspaceRect( rc ); // Determine start/stop positions float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; float timeperpixel = ( endtime - starttime ) / (float)( rc.right - rc.left ); float movetime = timeperpixel * (float)direction; float maxmove = ComputeMaxPhonemeShift( direction > 0 ? true : false, false ); if ( direction > 0 ) { if ( movetime > maxmove ) { movetime = maxmove; Con_Printf( "Further shift is blocked on right\n" ); } } else { if ( movetime < -maxmove ) { movetime = -maxmove; Con_Printf( "Further shift is blocked on left\n" ); } } if ( fabs( movetime ) < 0.0001f ) return; SetDirty( true ); PushUndo(); TraversePhonemes( &PhonemeEditor::ITER_MoveSelectedPhonemes, movetime ); PushRedo(); m_bWordsActive = false; redraw(); Con_Printf( "Shift phoneme %s\n", direction == -1 ? "left" : "right" ); } void PhonemeEditor::ExtendSelectedPhonemeEndTime( int direction ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); if ( m_nSelectedPhonemeCount != 1 ) return; RECT rc; GetWorkspaceRect( rc ); // Determine start/stop positions float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; float timeperpixel = ( endtime - starttime ) / (float)( rc.right - rc.left ); float movetime = timeperpixel * (float)direction; SetDirty( true ); PushUndo(); TraversePhonemes( &PhonemeEditor::ITER_ExtendSelectedPhonemeEndTimes, movetime ); PushRedo(); m_bWordsActive = false; redraw(); Con_Printf( "Extend phoneme end %s\n", direction == -1 ? "left" : "right" ); } void PhonemeEditor::SelectNextPhoneme( int direction ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); if ( m_nSelectedPhonemeCount != 1 ) { if ( m_nSelectedWordCount == 1 ) { CWordTag *word = GetSelectedWord(); if ( word && word->m_Phonemes.Size() > 0 ) { m_nSelectedPhonemeCount = 1; CPhonemeTag *p = word->m_Phonemes[ direction ? word->m_Phonemes.Size() - 1 : 0 ]; p->m_bSelected = true; } else { return; } } else { return; } } Con_Printf( "Move to next phoneme %s\n", direction == -1 ? "left" : "right" ); for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; for ( int j = 0; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *phoneme = word->m_Phonemes[ j ]; if ( !phoneme ) continue; if ( !phoneme->m_bSelected ) continue; // Deselect this one and move int nextindex = j + direction; if ( nextindex < 0 ) { nextindex = word->m_Phonemes.Size() - 1; } else if ( nextindex >= word->m_Phonemes.Size() ) { nextindex = 0; } phoneme->m_bSelected = false; phoneme = word->m_Phonemes[ nextindex ]; phoneme->m_bSelected = true; m_bWordsActive = false; redraw(); return; } } } bool PhonemeEditor::IsPhonemeSelected( CWordTag *word ) { for ( int i = 0 ; i < word->m_Phonemes.Size(); i++ ) { CPhonemeTag *p = word->m_Phonemes[ i ]; if ( !p || !p->m_bSelected ) continue; return true; } return false; } void PhonemeEditor::SelectNextWord( int direction ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); if ( m_nSelectedWordCount != 1 && m_nSelectedPhonemeCount != 1 ) { // Selected first word then if ( m_nSelectedWordCount == 0 && m_Tags.m_Words.Size() > 0 ) { CWordTag *word = m_Tags.m_Words[ direction ? m_Tags.m_Words.Size() - 1 : 0 ]; word->m_bSelected = true; m_nSelectedWordCount = 1; } else { return; } } Con_Printf( "Move to next word %s\n", direction == -1 ? "left" : "right" ); for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; if ( m_nSelectedWordCount == 1 ) { if ( !word->m_bSelected ) continue; } else { if ( !IsPhonemeSelected( word ) ) continue; } // Deselect word word->m_bSelected = false; for ( int j = 0; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *phoneme = word->m_Phonemes[ j ]; if ( !phoneme ) continue; if ( !phoneme->m_bSelected ) continue; phoneme->m_bSelected = false; } // Deselect this one and move int nextword = i + direction; if ( nextword < 0 ) { nextword = m_Tags.m_Words.Size() - 1; } else if ( nextword >= m_Tags.m_Words.Size() ) { nextword = 0; } word = m_Tags.m_Words[ nextword ]; word->m_bSelected = true; if ( word->m_Phonemes.Size() > 0 ) { CPhonemeTag *phoneme = NULL; if ( direction > 0 ) { phoneme = word->m_Phonemes[ 0 ]; } else { phoneme = word->m_Phonemes[ word->m_Phonemes.Size() - 1 ]; } phoneme->m_bSelected = true; } m_bWordsActive = true; redraw(); return; } } void PhonemeEditor::ShiftSelectedWord( int direction ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); switch ( m_nSelectedWordCount ) { case 1: break; case 0: Con_Printf( "Can't shift words, none selected\n" ); return; default: Con_Printf( "Can only shift one word at a time via keyboard\n" ); return; } RECT rc; GetWorkspaceRect( rc ); // Determine start/stop positions float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; float timeperpixel = ( endtime - starttime ) / (float)( rc.right - rc.left ); float movetime = timeperpixel * (float)direction; float maxmove = ComputeMaxWordShift( direction > 0 ? true : false, false ); if ( direction > 0 ) { if ( movetime > maxmove ) { movetime = maxmove; Con_Printf( "Further shift is blocked on right\n" ); } } else { if ( movetime < -maxmove ) { movetime = -maxmove; Con_Printf( "Further shift is blocked on left\n" ); } } if ( fabs( movetime ) < 0.0001f ) return; SetDirty( true ); PushUndo(); TraverseWords( &PhonemeEditor::ITER_MoveSelectedWords, movetime ); PushRedo(); m_bWordsActive = true; redraw(); Con_Printf( "Shift word %s\n", direction == -1 ? "left" : "right" ); } void PhonemeEditor::ExtendSelectedWordEndTime( int direction ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); if ( m_nSelectedWordCount != 1 ) return; RECT rc; GetWorkspaceRect( rc ); // Determine start/stop positions float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; float timeperpixel = ( endtime - starttime ) / (float)( rc.right - rc.left ); float movetime = timeperpixel * (float)direction; SetDirty( true ); PushUndo(); TraverseWords( &PhonemeEditor::ITER_ExtendSelectedWordEndTimes, movetime ); PushRedo(); m_bWordsActive = true; redraw(); Con_Printf( "Extend word end %s\n", direction == -1 ? "left" : "right" ); } //----------------------------------------------------------------------------- // Purpose: // Input : *word - // Output : int //----------------------------------------------------------------------------- int PhonemeEditor::IndexOfWord( CWordTag *word ) { for ( int i = 0 ; i < m_Tags.m_Words.Size(); i++ ) { if ( m_Tags.m_Words[ i ] == word ) return i; } return -1; } //----------------------------------------------------------------------------- // Purpose: // Input : forward - // *currentWord - // **nextWord - // Output : float //----------------------------------------------------------------------------- float PhonemeEditor::GetTimeGapToNextWord( bool forward, CWordTag *currentWord, CWordTag **ppNextWord /* = NULL */ ) { if ( ppNextWord ) { *ppNextWord = NULL; } if ( !currentWord ) return 0.0f; int wordnum = IndexOfWord( currentWord ); if ( wordnum == -1 ) return 0.0f; // Go in correct direction int newwordnum = wordnum + ( forward ? 1 : -1 ); // There is no next word if ( newwordnum >= m_Tags.m_Words.Size() ) { return PLENTY_OF_TIME; } // There is no previous word if ( newwordnum < 0 ) { return PLENTY_OF_TIME; } if ( ppNextWord ) { *ppNextWord = m_Tags.m_Words[ newwordnum ]; } // Otherwise, figure out time gap if ( forward ) { float currentEnd = currentWord->m_flEndTime; float nextStart = m_Tags.m_Words[ newwordnum ]->m_flStartTime; return ( nextStart - currentEnd ); } else { float previousEnd = m_Tags.m_Words[ newwordnum ]->m_flEndTime; float currentStart = currentWord->m_flStartTime; return ( currentStart - previousEnd ); } Assert( 0 ); return 0.0f; } //----------------------------------------------------------------------------- // Purpose: // Input : forward - // *currentPhoneme - // **word - // **phoneme - // Output : float //----------------------------------------------------------------------------- float PhonemeEditor::GetTimeGapToNextPhoneme( bool forward, CPhonemeTag *currentPhoneme, CWordTag **ppword /* = NULL */, CPhonemeTag **ppphoneme /* = NULL */ ) { if ( ppword ) { *ppword = NULL; } if ( ppphoneme ) { *ppphoneme = NULL; } if ( !currentPhoneme ) return 0.0f; CWordTag *word = m_Tags.GetWordForPhoneme( currentPhoneme ); if ( !word ) return 0.0f; int wordnum = IndexOfWord( word ); Assert( wordnum != -1 ); int phonemenum = word->IndexOfPhoneme( currentPhoneme ); if ( phonemenum < 0 ) return 0.0f; CPhonemeTag *nextPhoneme = NULL; int nextphoneme = phonemenum + ( forward ? 1 : -1 ); // Try last phoneme of previous word if ( nextphoneme < 0 ) { wordnum--; while ( wordnum >= 0 ) { if ( ppword ) { *ppword = m_Tags.m_Words[ wordnum ]; } if ( m_Tags.m_Words.Size() > 0 ) { if ( m_Tags.m_Words[ wordnum ]->m_Phonemes.Size() > 0 ) { nextPhoneme = m_Tags.m_Words[ wordnum ]->m_Phonemes[ m_Tags.m_Words[ wordnum ]->m_Phonemes.Size() - 1 ]; break; } } wordnum--; } } // Try first phoneme of next word, if there is one else if ( nextphoneme >= word->m_Phonemes.Size() ) { wordnum++; while ( wordnum < m_Tags.m_Words.Size() ) { if ( ppword ) { *ppword = m_Tags.m_Words[ wordnum ]; } // Really it can't be zero, but check anyway if ( m_Tags.m_Words.Size() > 0 ) { if ( m_Tags.m_Words[ wordnum ]->m_Phonemes.Size() > 0 ) { nextPhoneme = m_Tags.m_Words[ wordnum ]->m_Phonemes[ 0 ]; break; } } wordnum++; } } else { nextPhoneme = word->m_Phonemes[ nextphoneme ]; } if ( !nextPhoneme ) return PLENTY_OF_TIME; if ( ppphoneme ) { *ppphoneme = nextPhoneme; } // Now compute time delta float dt = 0.0f; if ( forward ) { dt = nextPhoneme->GetStartTime() - currentPhoneme->GetEndTime(); } else { dt = currentPhoneme->GetStartTime() - nextPhoneme->GetEndTime(); } return dt; } CPhonemeTag *PhonemeEditor::GetSelectedPhoneme( void ) { CountSelected(); if ( m_nSelectedPhonemeCount != 1 ) return NULL; for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *w = m_Tags.m_Words[ i ]; if ( !w ) continue; for ( int j = 0; j < w->m_Phonemes.Size() ; j++ ) { CPhonemeTag *p = w->m_Phonemes[ j ]; if ( !p || !p->m_bSelected ) continue; return p; } } return NULL; } CWordTag *PhonemeEditor::GetSelectedWord( void ) { CountSelected(); if ( m_nSelectedWordCount != 1 ) return NULL; for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *w = m_Tags.m_Words[ i ]; if ( !w || !w->m_bSelected ) continue; return w; } return NULL; } void PhonemeEditor::OnMouseMove( mxEvent *event ) { int mx = (short)event->x; LimitDrag( mx ); event->x = (short)mx; if ( m_nDragType != DRAGTYPE_NONE ) { DrawFocusRect( "moving old" ); for ( int i = 0; i < m_FocusRects.Size(); i++ ) { CFocusRect *f = &m_FocusRects[ i ]; f->m_rcFocus = f->m_rcOrig; switch ( m_nDragType ) { default: { // Only X Shifts supported OffsetRect( &f->m_rcFocus, ( (short)event->x - m_nStartX ), 0 ); } break; case DRAGTYPE_EMPHASIS_SELECT: { RECT rcWork; GetWorkspaceRect( rcWork ); RECT rcEmphasis; Emphasis_GetRect( rcWork, rcEmphasis ); RECT rcFocus; rcFocus = f->m_rcOrig; rcFocus.left = m_nStartX < (short)event->x ? m_nStartX : (short)event->x; rcFocus.right = m_nStartX < (short)event->x ? (short)event->x : m_nStartX; rcFocus.top = m_nStartY < (short)event->y ? m_nStartY : (short)event->y; rcFocus.bottom = m_nStartY < (short)event->y ? (short)event->y : m_nStartY; rcFocus.top = clamp( rcFocus.top, rcEmphasis.top, rcEmphasis.bottom ); rcFocus.bottom = clamp( rcFocus.bottom, rcEmphasis.top, rcEmphasis.bottom ); //OffsetRect( &rcFocus, 0, -rcEmphasis.top ); POINT offset; offset.x = 0; offset.y = 0; ClientToScreen( (HWND)getHandle(), &offset ); OffsetRect( &rcFocus, offset.x, offset.y ); f->m_rcFocus = rcFocus; } break; } } if ( m_nDragType == DRAGTYPE_EMPHASIS_MOVE ) { redraw(); } DrawFocusRect( "moving new" ); } else { if ( m_hPrevCursor ) { SetCursor( m_hPrevCursor ); m_hPrevCursor = NULL; } CountSelected(); int overhandle = IsMouseOverBoundary( event ); if ( overhandle == BOUNDARY_PHONEME && m_nSelectedPhonemeCount <= 1 ) { m_hPrevCursor = SetCursor( LoadCursor( NULL, IDC_SIZEWE ) ); } else if ( overhandle == BOUNDARY_WORD && m_nSelectedWordCount <= 1 ) { m_hPrevCursor = SetCursor( LoadCursor( NULL, IDC_SIZEWE ) ); } else if ( IsMouseOverSelection( (short)event->x, (short)event->y ) ) { if ( IsMouseOverSelectionStartEdge( event ) ) { m_hPrevCursor = SetCursor( LoadCursor( NULL, IDC_SIZEWE ) ); } else if ( IsMouseOverSelectionEndEdge( event ) ) { m_hPrevCursor = SetCursor( LoadCursor( NULL, IDC_SIZEWE ) ); } else { if ( event->modifiers & mxEvent::KeyShift ) { m_hPrevCursor = SetCursor( LoadCursor( NULL, IDC_SIZEALL ) ); } } } else { if ( IsMouseOverTag( (short)event->x, (short)event->y ) ) { m_hPrevCursor = SetCursor( LoadCursor( NULL, IDC_SIZEALL ) ); } else { CPhonemeTag *pt = GetPhonemeTagUnderMouse( (short)event->x, (short)event->y ); CWordTag *wt = GetWordTagUnderMouse( (short)event->x, (short)event->y ); if ( wt || pt ) { if ( pt ) { // Select it SelectExpression( pt ); } if ( event->modifiers & mxEvent::KeyShift ) { m_hPrevCursor = SetCursor( LoadCursor( NULL, IDC_SIZEALL ) ); } } } } } switch ( m_nDragType ) { default: break; case DRAGTYPE_EMPHASIS_MOVE: { Emphasis_MouseDrag( (short)event->x, (short)event->y ); m_Tags.Resort(); } break; case DRAGTYPE_SCRUBBER: { float t = GetTimeForPixel( (short)event->x ); t += m_flScrubberTimeOffset; ClampTimeToSelectionInterval( t ); float dt = t - m_flScrub; SetScrubTargetTime( t ); ScrubThink( dt, true ); SetScrubTime( t ); DrawScrubHandle(); } break; } m_nLastX = (short)event->x; m_nLastY = (short)event->y; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::EditInsertFirstPhonemeOfWord( void ) { if ( GetMode() != MODE_PHONEMES ) return; CWordTag *cw = GetSelectedWord(); if ( !cw ) return; if ( cw->m_Phonemes.Size() != 0 ) { Con_Printf( "Can't insert first phoneme into %s, already has phonemes\n", cw->GetWord() ); return; } CPhonemeParams params; memset( &params, 0, sizeof( params ) ); strcpy( params.m_szDialogTitle, "Phoneme/Viseme Properties" ); strcpy( params.m_szName, "" ); params.m_nLeft = -1; params.m_nTop = -1; params.m_bPositionDialog = true; params.m_bMultiplePhoneme = true; if ( params.m_bPositionDialog ) { RECT rcWord; GetWordRect( cw, rcWord ); // Convert to screen coords POINT pt; pt.x = rcWord.left; pt.y = rcWord.top; ClientToScreen( (HWND)getHandle(), &pt ); params.m_nLeft = pt.x; params.m_nTop = pt.y; } int iret = PhonemeProperties( &params ); SetFocus( (HWND)getHandle() ); if ( !iret ) { return; } int phonemeCount = CSentence::CountWords( params.m_szName ); if ( phonemeCount <= 0 ) { return; } float wordLength = cw->m_flEndTime - cw->m_flStartTime; float timePerPhoneme = wordLength / (float)phonemeCount; float currentTime = cw->m_flStartTime; SetDirty( true ); PushUndo(); unsigned char *in; char *out; char phonemeName[ 128 ]; in = (unsigned char *)params.m_szName; do { out = phonemeName; while ( *in > 32 ) { *out++ = *in++; } *out = 0; CPhonemeTag phoneme; phoneme.SetPhonemeCode( TextToPhoneme( phonemeName ) ); phoneme.SetTag( phonemeName ); phoneme.SetStartTime( currentTime ); phoneme.SetEndTime( currentTime + timePerPhoneme ); phoneme.m_bSelected = false; cw->m_Phonemes.AddToTail( new CPhonemeTag( phoneme ) ); currentTime += timePerPhoneme; if ( !*in ) break; // Skip whitespace in++; } while ( 1 ); cw->m_Phonemes[ 0 ]->m_bSelected = true; PushRedo(); // Add it redraw(); } void PhonemeEditor::SelectPhonemes( bool forward ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); if ( m_nSelectedPhonemeCount != 1 ) return; CPhonemeTag *phoneme = GetSelectedPhoneme(); if ( !phoneme ) return; // Figure out it's word and index CWordTag *word = m_Tags.GetWordForPhoneme( phoneme ); if ( !word ) return; int wordNum = IndexOfWord( word ); if ( wordNum == -1 ) return; // Select remaining phonemes in current word int i; i = word->IndexOfPhoneme( phoneme ); if ( i == -1 ) return; if ( forward ) { // Start at next one i++; for ( ; i < word->m_Phonemes.Size(); i++ ) { phoneme = word->m_Phonemes[ i ]; phoneme->m_bSelected = true; } // Now start at next word wordNum++; for ( ; wordNum < m_Tags.m_Words.Size(); wordNum++ ) { word = m_Tags.m_Words[ wordNum ]; for ( int j = 0; j < word->m_Phonemes.Size(); j++ ) { phoneme = word->m_Phonemes[ j ]; phoneme->m_bSelected = true; } } } else { // Start at previous i--; for ( ; i >= 0; i-- ) { phoneme = word->m_Phonemes[ i ]; phoneme->m_bSelected = true; } // Now start at previous word wordNum--; for ( ; wordNum >= 0 ; wordNum-- ) { word = m_Tags.m_Words[ wordNum ]; for ( int j = 0; j < word->m_Phonemes.Size(); j++ ) { phoneme = word->m_Phonemes[ j ]; phoneme->m_bSelected = true; } } } redraw(); } void PhonemeEditor::SelectWords( bool forward ) { if ( GetMode() != MODE_PHONEMES ) return; CountSelected(); if ( m_nSelectedWordCount != 1 ) return; // Figure out it's word and index CWordTag *word = GetSelectedWord(); if ( !word ) return; int wordNum = IndexOfWord( word ); if ( wordNum == -1 ) return; if ( forward ) { wordNum++; for ( ; wordNum < m_Tags.m_Words.Size(); wordNum++ ) { word = m_Tags.m_Words[ wordNum ]; word->m_bSelected = true; } } else { wordNum--; for ( ; wordNum >= 0; wordNum-- ) { word = m_Tags.m_Words[ wordNum ]; word->m_bSelected = true; } } redraw(); } bool PhonemeEditor::AreSelectedWordsContiguous( void ) { CountSelected(); if ( m_nSelectedWordCount < 1 ) return false; if ( m_nSelectedWordCount == 1 ) return true; // Find first selected word int runcount = 0; bool parity = false; for ( int i = 0 ; i < m_Tags.m_Words.Size() ; i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; if ( word->m_bSelected ) { if ( !parity ) { parity = true; runcount++; } } else { if ( parity ) { parity = false; } } } if ( runcount == 1 ) return true; return false; } bool PhonemeEditor::AreSelectedPhonemesContiguous( void ) { CountSelected(); if ( m_nSelectedPhonemeCount < 1 ) return false; if ( m_nSelectedPhonemeCount == 1 ) return true; // Find first selected word int runcount = 0; bool parity = false; for ( int i = 0 ; i < m_Tags.m_Words.Size() ; i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; for ( int j = 0 ; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *phoneme = word->m_Phonemes[ j ]; if ( !phoneme ) continue; if ( phoneme->m_bSelected ) { if ( !parity ) { parity = true; runcount++; } } else { if ( parity ) { parity = false; } } } } if ( runcount == 1 ) return true; return false; } void PhonemeEditor::SortWords( bool prepareundo ) { if ( prepareundo ) { SetDirty( true ); PushUndo(); } // Just bubble sort by start time int c = m_Tags.m_Words.Count(); int i; // check for start > end for ( i = 0; i < c; i++ ) { CWordTag *p1 = m_Tags.m_Words[ i ]; if (p1->m_flStartTime > p1->m_flEndTime ) { float swap = p1->m_flStartTime; p1->m_flStartTime = p1->m_flEndTime; p1->m_flEndTime = swap; } } for ( i = 0; i < c; i++ ) { for ( int j = i + 1; j < c; j++ ) { CWordTag *p1 = m_Tags.m_Words[ i ]; CWordTag *p2 = m_Tags.m_Words[ j ]; if ( p1->m_flStartTime < p2->m_flStartTime ) continue; // Swap them m_Tags.m_Words[ i ] = p2; m_Tags.m_Words[ j ] = p1; } } if ( prepareundo ) { PushRedo(); } } void PhonemeEditor::SortPhonemes( bool prepareundo ) { if ( prepareundo ) { SetDirty( true ); PushUndo(); } // Just bubble sort by start time int wc = m_Tags.m_Words.Count(); for ( int w = 0; w < wc; w++ ) { CWordTag *word = m_Tags.m_Words[ w ]; Assert( word ); int c = word->m_Phonemes.Count(); int i; // check for start > end for ( i = 0; i < c; i++ ) { CPhonemeTag *p1 = word->m_Phonemes[ i ]; if (p1->GetStartTime() > p1->GetEndTime() ) { float swap = p1->GetStartTime(); p1->SetStartTime( p1->GetEndTime() ); p1->SetEndTime( swap ); } } for ( i = 0; i < c; i++ ) { for ( int j = i + 1; j < c; j++ ) { CPhonemeTag *p1 = word->m_Phonemes[ i ]; CPhonemeTag *p2 = word->m_Phonemes[ j ]; if ( p1->GetStartTime() < p2->GetStartTime() ) continue; // Swap them word->m_Phonemes[ i ] = p2; word->m_Phonemes[ j ] = p1; } } } if ( prepareundo ) { PushRedo(); } } void PhonemeEditor::CleanupWordsAndPhonemes( bool prepareundo ) { if ( GetMode() != MODE_PHONEMES ) return; // 2 pixel gap float snap_epsilon = 2.49f / GetPixelsPerSecond(); if ( prepareundo ) { SetDirty( true ); PushUndo(); } SortWords( false ); SortPhonemes( false ); for ( int i = 0 ; i < m_Tags.m_Words.Size() ; i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; CWordTag *next = NULL; if ( i < m_Tags.m_Words.Size() - 1 ) { next = m_Tags.m_Words[ i + 1 ]; } if ( word && next ) { // Check for words close enough float eps = next->m_flStartTime - word->m_flEndTime; if ( eps && eps <= snap_epsilon ) { float t = (word->m_flEndTime + next->m_flStartTime) * 0.5; word->m_flEndTime = t; next->m_flStartTime = t; } } for ( int j = 0 ; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *phoneme = word->m_Phonemes[ j ]; if ( !phoneme ) continue; CPhonemeTag *next = NULL; if ( j < word->m_Phonemes.Size() - 1 ) { next = word->m_Phonemes[ j + 1 ]; } if ( phoneme && next ) { float eps = next->GetStartTime() - phoneme->GetEndTime(); if ( eps && eps <= snap_epsilon ) { float t = (phoneme->GetEndTime() + next->GetStartTime() ) * 0.5; phoneme->SetEndTime( t ); next->SetStartTime( t ); } } } } if ( prepareundo ) { PushRedo(); } // NOTE: Caller must call "redraw()" to get screen to update } void PhonemeEditor::RealignPhonemesToWords( bool prepareundo ) { if ( GetMode() != MODE_PHONEMES ) return; if ( prepareundo ) { SetDirty( true ); PushUndo(); } SortWords( false ); SortPhonemes( false ); for ( int i = 0 ; i < m_Tags.m_Words.Size() ; i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; CWordTag *next = NULL; if ( i < m_Tags.m_Words.Size() - 1 ) { next = m_Tags.m_Words[ i + 1 ]; } float word_dt = word->m_flEndTime - word->m_flStartTime; CPhonemeTag *FirstPhoneme = word->m_Phonemes[ 0 ]; if ( !FirstPhoneme ) continue; CPhonemeTag *LastPhoneme = word->m_Phonemes[ word->m_Phonemes.Size() - 1 ]; if ( !LastPhoneme ) continue; float phoneme_dt = LastPhoneme->GetEndTime() - FirstPhoneme->GetStartTime(); float phoneme_shift = FirstPhoneme->GetStartTime(); for ( int j = 0 ; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *phoneme = word->m_Phonemes[ j ]; if ( !phoneme ) continue; CPhonemeTag *next = NULL; if ( j < word->m_Phonemes.Size() - 1 ) { next = word->m_Phonemes[ j + 1 ]; } if (j == 0) { float t = (phoneme->GetStartTime() - phoneme_shift ) * (word_dt / phoneme_dt) + word->m_flStartTime; phoneme->SetStartTime( t ); } float t = (phoneme->GetEndTime() - phoneme_shift ) * (word_dt / phoneme_dt) + word->m_flStartTime; phoneme->SetEndTime( t ); if (next) { next->SetStartTime( t ); } } } if ( prepareundo ) { PushRedo(); } // NOTE: Caller must call "redraw()" to get screen to update } void PhonemeEditor::RealignWordsToPhonemes( bool prepareundo ) { if ( GetMode() != MODE_PHONEMES ) return; if ( prepareundo ) { SetDirty( true ); PushUndo(); } SortWords( false ); SortPhonemes( false ); for ( int i = 0 ; i < m_Tags.m_Words.Size() ; i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; CPhonemeTag *FirstPhoneme = word->m_Phonemes[ 0 ]; if ( !FirstPhoneme ) continue; CPhonemeTag *LastPhoneme = word->m_Phonemes[ word->m_Phonemes.Size() - 1 ]; if ( !LastPhoneme ) continue; word->m_flStartTime = FirstPhoneme->GetStartTime(); word->m_flEndTime = LastPhoneme->GetEndTime(); } if ( prepareundo ) { PushRedo(); } // NOTE: Caller must call "redraw()" to get screen to update } float PhonemeEditor::ComputeMaxWordShift( bool forward, bool allowcrop ) { // skipping selected words, figure out max time shift of words before they selection touches any // unselected words // if allowcrop is true, then the maximum extends up to end of next word float maxshift = PLENTY_OF_TIME; if ( forward ) { for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *w1 = m_Tags.m_Words[ i ]; if ( !w1 || !w1->m_bSelected ) continue; CWordTag *w2 = NULL; for ( int search = i + 1; search < m_Tags.m_Words.Size() ; search++ ) { CWordTag *check = m_Tags.m_Words[ search ]; if ( !check || check->m_bSelected ) continue; w2 = check; break; } if ( w2 ) { float shift; if ( allowcrop ) { shift = w2->m_flEndTime - w1->m_flEndTime; } else { shift = w2->m_flStartTime - w1->m_flEndTime; } if ( shift < maxshift ) { maxshift = shift; } } } } else { for ( int i = m_Tags.m_Words.Size() -1; i >= 0; i-- ) { CWordTag *w1 = m_Tags.m_Words[ i ]; if ( !w1 || !w1->m_bSelected ) continue; CWordTag *w2 = NULL; for ( int search = i - 1; search >= 0 ; search-- ) { CWordTag *check = m_Tags.m_Words[ search ]; if ( !check || check->m_bSelected ) continue; w2 = check; break; } if ( w2 ) { float shift; if ( allowcrop ) { shift = w1->m_flStartTime - w2->m_flStartTime; } else { shift = w1->m_flStartTime - w2->m_flEndTime; } if ( shift < maxshift ) { maxshift = shift; } } } } return maxshift; } float PhonemeEditor::ComputeMaxPhonemeShift( bool forward, bool allowcrop ) { // skipping selected phonemes, figure out max time shift of phonemes before they selection touches any // unselected words // if allowcrop is true, then the maximum extends up to end of next word float maxshift = PLENTY_OF_TIME; if ( forward ) { for ( int i = 0; i < m_Tags.m_Words.Size(); i++ ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; for ( int j = 0; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *p1 = word->m_Phonemes[ j ]; if ( !p1 || !p1->m_bSelected ) continue; // Find next unselected phoneme CPhonemeTag *p2 = NULL; CPhonemeTag *start = p1; do { CPhonemeTag *test = NULL; GetTimeGapToNextPhoneme( forward, start, NULL, &test ); if ( !test ) break; if ( test->m_bSelected ) { start = test; continue; } p2 = test; break; } while ( 1 ); if ( p2 ) { float shift; if ( allowcrop ) { shift = p2->GetEndTime() - p1->GetEndTime(); } else { shift = p2->GetStartTime() - p1->GetEndTime(); } if ( shift < maxshift ) { maxshift = shift; } } } } } else { for ( int i = m_Tags.m_Words.Size() -1; i >= 0; i-- ) { CWordTag *word = m_Tags.m_Words[ i ]; if ( !word ) continue; for ( int j = word->m_Phonemes.Size() - 1; j >= 0; j-- ) { CPhonemeTag *p1 = word->m_Phonemes[ j ]; if ( !p1 || !p1->m_bSelected ) continue; // Find previous unselected phoneme CPhonemeTag *p2 = NULL; CPhonemeTag *start = p1; do { CPhonemeTag *test = NULL; GetTimeGapToNextPhoneme( forward, start, NULL, &test ); if ( !test ) break; if ( test->m_bSelected ) { start = test; continue; } p2 = test; break; } while ( 1 ); if ( p2 ) { float shift; if ( allowcrop ) { shift = p1->GetStartTime() - p2->GetStartTime(); } else { shift = p1->GetStartTime() - p2->GetEndTime(); } if ( shift < maxshift ) { maxshift = shift; } } } } } return maxshift; } int PhonemeEditor::PixelsForDeltaTime( float dt ) { if ( !dt ) return 0; RECT rc; GetWorkspaceRect( rc ); float starttime = m_nLeftOffset / GetPixelsPerSecond(); float endtime = w2() / GetPixelsPerSecond() + starttime; float timeperpixel = ( endtime - starttime ) / (float)( rc.right - rc.left ); float pixels = dt / timeperpixel; return abs( (int)pixels ); } void PhonemeEditor::ClearDragLimit( void ) { m_bLimitDrag = false; m_nLeftLimit = -1; m_nRightLimit = -1; } void PhonemeEditor::SetDragLimit( int dragtype ) { ClearDragLimit(); float nextW, nextP; float prevW, prevP; nextW = ComputeMaxWordShift( true, false ); prevW = ComputeMaxWordShift( false, false ); nextP = ComputeMaxPhonemeShift( true, false ); prevP = ComputeMaxPhonemeShift( false, false ); /* Con_Printf( "+w %f -w %f +p %f -p %f\n", 1000.0f * nextW, 1000.0f * prevW, 1000.0f * nextP, 1000.0f * prevP ); */ switch ( dragtype ) { case DRAGTYPE_MOVEWORD: m_bLimitDrag = true; m_nLeftLimit = PixelsForDeltaTime( prevW ); m_nRightLimit = PixelsForDeltaTime( nextW ); break; case DRAGTYPE_MOVEPHONEME: m_bLimitDrag = true; m_nLeftLimit = PixelsForDeltaTime( prevP ); m_nRightLimit = PixelsForDeltaTime( nextP ); break; default: ClearDragLimit(); break; } } void PhonemeEditor::LimitDrag( int& mousex ) { if ( m_nDragType == DRAGTYPE_NONE ) return; if ( !m_bLimitDrag ) return; int delta = mousex - m_nStartX; if ( delta > 0 ) { if ( m_nRightLimit >= 0 ) { if ( delta > m_nRightLimit ) { mousex = m_nStartX + m_nRightLimit; } } } else if ( delta < 0 ) { if ( m_nLeftLimit >= 0 ) { if ( abs( delta ) > abs( m_nLeftLimit ) ) { mousex = m_nStartX - m_nLeftLimit; } } } } //----------------------------------------------------------------------------- // Purpose: Wipe undo/redo data //----------------------------------------------------------------------------- void PhonemeEditor::ClearUndo( void ) { WipeUndo(); WipeRedo(); SetDirty( false ); } //----------------------------------------------------------------------------- // Purpose: // Input : *tag - //----------------------------------------------------------------------------- void PhonemeEditor::SelectExpression( CPhonemeTag *tag ) { if ( !models->GetActiveStudioModel() ) return; CStudioHdr *hdr = models->GetActiveStudioModel()->GetStudioHdr(); if ( !hdr ) return; // Make sure phonemes are loaded FacePoser_EnsurePhonemesLoaded(); CExpClass *cl = expressions->FindClass( "phonemes", true ); if ( !cl ) { Con_Printf( "Couldn't load expressions/phonemes.txt!\n" ); return; } if ( expressions->GetActiveClass() != cl ) { expressions->ActivateExpressionClass( cl ); } CExpression *exp = cl->FindExpression( ConvertPhoneme( tag->GetPhonemeCode() ) ); if ( !exp ) { Con_Printf( "Couldn't find phoneme '%s'\n", ConvertPhoneme( tag->GetPhonemeCode() ) ); return; } float *settings = exp->GetSettings(); for (LocalFlexController_t i = LocalFlexController_t(0); i < hdr->numflexcontrollers(); i++) { int j = hdr->pFlexcontroller( i )->localToGlobal; models->GetActiveStudioModel()->SetFlexController( i, settings[j] ); } } void PhonemeEditor::OnSAPI( void ) { if ( GetMode() != MODE_PHONEMES ) return; g_viewerSettings.speechapiindex = SPEECH_API_SAPI; m_pPhonemeExtractor = NULL; CheckSpeechAPI(); redraw(); } void PhonemeEditor::OnLipSinc( void ) { if ( GetMode() != MODE_PHONEMES ) return; g_viewerSettings.speechapiindex = SPEECH_API_LIPSINC; m_pPhonemeExtractor = NULL; CheckSpeechAPI(); redraw(); } void PhonemeEditor::LoadPhonemeConverters() { m_pPhonemeExtractor = NULL; // Enumerate modules under bin folder of exe FileFindHandle_t findHandle; const char *pFilename = filesystem->FindFirstEx( "phonemeextractors/*.dll", "EXECUTABLE_PATH", &findHandle ); while( pFilename ) { char fullpath[ 512 ]; Q_snprintf( fullpath, sizeof( fullpath ), "phonemeextractors/%s", pFilename ); Con_Printf( "Loading extractor from %s\n", fullpath ); Extractor e; e.module = Sys_LoadModule( fullpath ); if ( !e.module ) { pFilename = filesystem->FindNext( findHandle ); continue; } CreateInterfaceFn factory = Sys_GetFactory( e.module ); if ( !factory ) { pFilename = filesystem->FindNext( findHandle ); continue; } e.extractor = ( IPhonemeExtractor * )factory( VPHONEME_EXTRACTOR_INTERFACE, NULL ); if ( !e.extractor ) { Warning( "Unable to get IPhonemeExtractor interface version %s from %s\n", VPHONEME_EXTRACTOR_INTERFACE, fullpath ); pFilename = filesystem->FindNext( findHandle ); continue; } e.apitype = e.extractor->GetAPIType(); g_Extractors.AddToTail( e ); pFilename = filesystem->FindNext( findHandle ); } filesystem->FindClose( findHandle ); } void PhonemeEditor::ValidateSpeechAPIIndex() { if ( !DoesExtractorExistFor( (PE_APITYPE)g_viewerSettings.speechapiindex ) ) { if ( g_Extractors.Count() > 0 ) g_viewerSettings.speechapiindex = g_Extractors[0].apitype; } } void PhonemeEditor::UnloadPhonemeConverters() { int c = g_Extractors.Count(); for ( int i = c - 1; i >= 0; i-- ) { Extractor *e = &g_Extractors[ i ]; Sys_UnloadModule( e->module ); } g_Extractors.RemoveAll(); m_pPhonemeExtractor = NULL; } bool PhonemeEditor::CheckSpeechAPI( void ) { if ( GetMode() != MODE_PHONEMES ) { return false; } if ( !m_pPhonemeExtractor ) { int c = g_Extractors.Count(); for ( int i = 0; i < c; i++ ) { Extractor *e = &g_Extractors[ i ]; if ( e->apitype == (PE_APITYPE)g_viewerSettings.speechapiindex ) { m_pPhonemeExtractor = e->extractor; break; } } if ( !m_pPhonemeExtractor ) { Con_ErrorPrintf( "Couldn't find phoneme extractor %i\n", g_viewerSettings.speechapiindex ); } } return m_pPhonemeExtractor != NULL; } //----------------------------------------------------------------------------- // Purpose: // Output : char const //----------------------------------------------------------------------------- char const *PhonemeEditor::GetSpeechAPIName( void ) { CheckSpeechAPI(); if ( m_pPhonemeExtractor ) { return m_pPhonemeExtractor->GetName(); } return "Unknown Speech API"; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::PaintBackground( void ) { redraw(); return false; } //----------------------------------------------------------------------------- // Purpose: // Output : PhonemeEditor::EditorMode //----------------------------------------------------------------------------- PhonemeEditor::EditorMode PhonemeEditor::GetMode( void ) const { return m_CurrentMode; } //----------------------------------------------------------------------------- // Purpose: // Input : rcWorkSpace - // rcEmphasis - //----------------------------------------------------------------------------- void PhonemeEditor::Emphasis_GetRect( RECT const & rcWorkSpace, RECT& rcEmphasis ) { rcEmphasis = rcWorkSpace; int ybottom = rcWorkSpace.bottom - 2 * m_nTickHeight - 2; int workspaceheight = rcWorkSpace.bottom - rcWorkSpace.top; // Just past midpoint rcEmphasis.top = rcWorkSpace.top + workspaceheight / 2 + 2; // 60 units or rcEmphasis.bottom = clamp( rcEmphasis.top + 60, rcEmphasis.top + 20, ybottom ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::OnModeChanged( void ) { // Show/hide controls as necessary } //----------------------------------------------------------------------------- // Purpose: // Input : *parent - //----------------------------------------------------------------------------- void PhonemeEditor::Emphasis_Init( void ) { m_nNumSelected = 0; } CEmphasisSample *PhonemeEditor::Emphasis_GetSampleUnderMouse( mxEvent *event ) { if ( GetMode() != MODE_EMPHASIS ) return NULL; if ( !m_pWaveFile ) return NULL; if ( w2() <= 0 ) return NULL; if ( GetPixelsPerSecond() <= 0 ) return NULL; float timeperpixel = 1.0f / GetPixelsPerSecond(); float closest_dist = 999999.0f; CEmphasisSample *bestsample = NULL; int samples = m_Tags.GetNumSamples(); float clickTime = GetTimeForPixel( (short)event->x ); for ( int i = 0; i < samples; i++ ) { CEmphasisSample *sample = m_Tags.GetSample( i ); float dist = fabs( sample->time - clickTime ); if ( dist < closest_dist ) { bestsample = sample; closest_dist = dist; } } // Not close to any of them!!! if ( closest_dist > ( 5.0f * timeperpixel ) ) { return NULL; } return bestsample; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::Emphasis_DeselectAll( void ) { if ( GetMode() != MODE_EMPHASIS ) return; for ( int i = 0; i < m_Tags.GetNumSamples(); i++ ) { CEmphasisSample *sample = m_Tags.GetSample( i ); sample->selected = false; } redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::Emphasis_SelectAll( void ) { if ( GetMode() != MODE_EMPHASIS ) return; for ( int i = 0; i < m_Tags.GetNumSamples(); i++ ) { CEmphasisSample *sample = m_Tags.GetSample( i ); sample->selected = true; } redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::Emphasis_Delete( void ) { if ( GetMode() != MODE_EMPHASIS ) return; SetDirty( true ); PushUndo(); for ( int i = m_Tags.GetNumSamples() - 1; i >= 0 ; i-- ) { CEmphasisSample *sample = m_Tags.GetSample( i ); if ( !sample->selected ) continue; m_Tags.m_EmphasisSamples.Remove( i ); SetDirty( true ); } PushRedo(); redraw(); } //----------------------------------------------------------------------------- // Purpose: // Input : sample - //----------------------------------------------------------------------------- void PhonemeEditor::Emphasis_AddSample( CEmphasisSample const& sample ) { if ( GetMode() != MODE_EMPHASIS ) return; SetDirty( true ); PushUndo(); m_Tags.m_EmphasisSamples.AddToTail( sample ); m_Tags.Resort(); PushRedo(); redraw(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::Emphasis_CountSelected( void ) { m_nNumSelected = 0; for ( int i = 0; i < m_Tags.GetNumSamples(); i++ ) { CEmphasisSample *sample = m_Tags.GetSample( i ); if ( !sample || !sample->selected ) continue; m_nNumSelected++; } } void PhonemeEditor::Emphasis_ShowContextMenu( mxEvent *event ) { if ( GetMode() != MODE_EMPHASIS ) return; CountSelected(); // Construct main menu mxPopupMenu *pop = new mxPopupMenu(); if ( m_nNumSelected > 0 ) { pop->add( va( "Delete" ), IDC_EMPHASIS_DELETE ); pop->add( "Deselect all", IDC_EMPHASIS_DESELECT ); } pop->add( "Select all", IDC_EMPHASIS_SELECTALL ); pop->popup( this, (short)event->x, (short)event->y ); } void PhonemeEditor::Emphasis_MouseDrag( int x, int y ) { if ( m_nDragType != DRAGTYPE_EMPHASIS_MOVE ) return; RECT rcWork; GetWorkspaceRect( rcWork ); RECT rc; Emphasis_GetRect( rcWork, rc ); int height = rc.bottom - rc.top; int dx = x - m_nLastX; int dy = y - m_nLastY; float dfdx = (float)dx * GetTimePerPixel(); float dfdy = (float)dy / (float)height; for ( int i = 0; i < m_Tags.GetNumSamples(); i++ ) { CEmphasisSample *sample = m_Tags.GetSample( i ); if ( !sample || !sample->selected ) continue; sample->time += dfdx; //sample->time = clamp( sample->time, 0.0f, 1.0f ); sample->value -= dfdy; sample->value = clamp( sample->value, 0.0f, 1.0f ); } } void PhonemeEditor::Emphasis_Redraw( CChoreoWidgetDrawHelper& drawHelper, RECT& rcWorkSpace ) { if ( GetMode() != MODE_EMPHASIS && GetMode() != MODE_PHONEMES ) return; bool fullmode = GetMode() == MODE_EMPHASIS; RECT rcClient; Emphasis_GetRect( rcWorkSpace, rcClient ); RECT rcText; rcText = rcClient; InflateRect( &rcText, -15, 0 ); OffsetRect( &rcText, 0, -20 ); rcText.bottom = rcText.top + 20; if ( fullmode ) { drawHelper.DrawColoredText( "Arial", 15, FW_BOLD, PEColor( COLOR_PHONEME_EMPHASIS_TEXT ), rcText, "Emphasis..." ); } { int h = rcClient.bottom - rcClient.top; int offset = h/3; RECT rcSpot = rcClient; rcSpot.bottom = rcSpot.top + offset; drawHelper.DrawGradientFilledRect( rcSpot, PEColor( COLOR_PHONEME_EMPHASIS_BG_STRONG ), PEColor( COLOR_PHONEME_EMPHASIS_BG ), true ); OffsetRect( &rcSpot, 0, offset ); drawHelper.DrawFilledRect( PEColor( COLOR_PHONEME_EMPHASIS_BG ), rcSpot ); OffsetRect( &rcSpot, 0, offset ); drawHelper.DrawGradientFilledRect( rcSpot, PEColor( COLOR_PHONEME_EMPHASIS_BG ), PEColor( COLOR_PHONEME_EMPHASIS_BG_WEAK ), true ); } COLORREF gray = PEColor( COLOR_PHONEME_EMPHASIS_MIDLINE ); drawHelper.DrawOutlinedRect( PEColor( COLOR_PHONEME_EMPHASIS_BORDER ), PS_SOLID, 1, rcClient ); COLORREF lineColor = PEColor( COLOR_PHONEME_EMPHASIS_LINECOLOR ); COLORREF dotColor = PEColor( COLOR_PHONEME_EMPHASIS_DOTCOLOR ); COLORREF dotColorSelected = PEColor( COLOR_PHONEME_EMPHASIS_DOTCOLOR_SELECTED ); int midy = ( rcClient.bottom + rcClient.top ) / 2; drawHelper.DrawColoredLine( gray, PS_SOLID, 1, rcClient.left, midy, rcClient.right, midy ); int height = rcClient.bottom - rcClient.top; int bottom = rcClient.bottom - 1; if ( !m_pWaveFile ) return; float running_length = m_pWaveFile->GetRunningLength(); // FIXME: adjust this based on framerate.... float timeperpixel = GetTimePerPixel(); float starttime, endtime; GetScreenStartAndEndTime( starttime, endtime ); int prevx = 0; float prev_t = starttime; float prev_value = m_Tags.GetIntensity( prev_t, running_length ); int dx = 5; for ( int x = 0; x < ( w2() + dx ); x += dx ) { float t = GetTimeForPixel( x ); float value = m_Tags.GetIntensity( t, running_length ); // Draw segment drawHelper.DrawColoredLine( lineColor, PS_SOLID, 1, prevx, bottom - prev_value * height, x, bottom - value * height ); prev_t = t; prev_value = value; prevx = x; } int numsamples = m_Tags.GetNumSamples(); for ( int sample = 0; sample < numsamples; sample++ ) { CEmphasisSample *start = m_Tags.GetSample( sample ); int x = ( start->time - starttime ) / timeperpixel; float value = m_Tags.GetIntensity( start->time, running_length ); int y = bottom - value * height; int dotsize = 4; int dotSizeSelected = 5; COLORREF clr = dotColor; COLORREF clrSelected = dotColorSelected; drawHelper.DrawCircle( start->selected ? clrSelected : clr, x, y, start->selected ? dotSizeSelected : dotsize, true ); } } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::Emphasis_IsValid( void ) { if ( m_Tags.GetNumSamples() > 0 ) return true; return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PhonemeEditor::Emphasis_SelectPoints( void ) { if ( GetMode() != MODE_EMPHASIS ) return; RECT rcWork, rcEmphasis; GetWorkspaceRect( rcWork ); Emphasis_GetRect( rcWork, rcEmphasis ); RECT rcSelection; rcSelection.left = m_nStartX < m_nLastX ? m_nStartX : m_nLastX; rcSelection.right = m_nStartX < m_nLastX ? m_nLastX : m_nStartX; rcSelection.top = m_nStartY < m_nLastY ? m_nStartY : m_nLastY; rcSelection.bottom = m_nStartY < m_nLastY ? m_nLastY : m_nStartY; rcSelection.top = max( rcSelection.top, rcEmphasis.top ); rcSelection.bottom = min( rcSelection.bottom, rcEmphasis.bottom ); int eh, ew; eh = rcEmphasis.bottom - rcEmphasis.top; ew = rcEmphasis.right - rcEmphasis.left; InflateRect( &rcSelection, 5, 5 ); if ( !w2() || !h2() ) return; float fleft = GetTimeForPixel( rcSelection.left ); float fright = GetTimeForPixel( rcSelection.right ); float ftop = (float)( rcSelection.top - rcEmphasis.top ) / (float)eh; float fbottom = (float)( rcSelection.bottom- rcEmphasis.top ) / (float)eh; //fleft = clamp( fleft, 0.0f, 1.0f ); //fright = clamp( fright, 0.0f, 1.0f ); ftop = clamp( ftop, 0.0f, 1.0f ); fbottom = clamp( fbottom, 0.0f, 1.0f ); float eps = 0.005; for ( int i = 0; i < m_Tags.GetNumSamples(); i++ ) { CEmphasisSample *sample = m_Tags.GetSample( i ); if ( sample->time + eps < fleft ) continue; if ( sample->time - eps > fright ) continue; if ( (1.0f - sample->value ) + eps < ftop ) continue; if ( (1.0f - sample->value ) - eps > fbottom ) continue; sample->selected = true; } redraw(); } //----------------------------------------------------------------------------- // Purpose: // Input : rcHandle - //----------------------------------------------------------------------------- void PhonemeEditor::GetScrubHandleRect( RECT& rcHandle, bool clipped ) { float pixel = 0.0f; if ( m_pWaveFile ) { float currenttime = m_flScrub; float starttime, endtime; GetScreenStartAndEndTime( starttime, endtime ); float screenfrac = ( currenttime - starttime ) / ( endtime - starttime ); pixel = screenfrac * w2(); if ( clipped ) { pixel = clamp( pixel, SCRUBBER_HANDLE_WIDTH/2, w2() - SCRUBBER_HANDLE_WIDTH/2 ); } } rcHandle.left = pixel-SCRUBBER_HANDLE_WIDTH/2; rcHandle.right = pixel + SCRUBBER_HANDLE_WIDTH/2; rcHandle.top = 2 + GetCaptionHeight() + 12; rcHandle.bottom = rcHandle.top + SCRUBBER_HANDLE_HEIGHT; } //----------------------------------------------------------------------------- // Purpose: // Input : rcArea - //----------------------------------------------------------------------------- void PhonemeEditor::GetScrubAreaRect( RECT& rcArea ) { rcArea.left = 0; rcArea.right = w2(); rcArea.top = 2 + GetCaptionHeight() + 12; rcArea.bottom = rcArea.top + SCRUBBER_HEIGHT - 4; } void PhonemeEditor::DrawScrubHandle() { RECT rcHandle; GetScrubHandleRect( rcHandle, true ); rcHandle.left = 0; rcHandle.right = w2(); CChoreoWidgetDrawHelper drawHelper( this, rcHandle ); DrawScrubHandle( drawHelper ); } //----------------------------------------------------------------------------- // Purpose: // Input : drawHelper - // rcHandle - //----------------------------------------------------------------------------- void PhonemeEditor::DrawScrubHandle( CChoreoWidgetDrawHelper& drawHelper ) { RECT rcHandle; GetScrubHandleRect( rcHandle, true ); HBRUSH br = CreateSolidBrush( RGB( 0, 150, 100 ) ); COLORREF areaBorder = RGB( 230, 230, 220 ); drawHelper.DrawColoredLine( areaBorder, PS_SOLID, 1, 0, rcHandle.top, w2(), rcHandle.top ); drawHelper.DrawColoredLine( areaBorder, PS_SOLID, 1, 0, rcHandle.bottom, w2(), rcHandle.bottom ); drawHelper.DrawFilledRect( br, rcHandle ); // char sz[ 32 ]; sprintf( sz, "%.3f", m_flScrub ); int len = drawHelper.CalcTextWidth( "Arial", 9, 500, sz ); RECT rcText = rcHandle; int textw = rcText.right - rcText.left; rcText.left += ( textw - len ) / 2; drawHelper.DrawColoredText( "Arial", 9, 500, RGB( 255, 255, 255 ), rcText, sz ); DeleteObject( br ); } //----------------------------------------------------------------------------- // Purpose: // Input : *event - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PhonemeEditor::IsMouseOverScrubHandle( mxEvent *event ) { RECT rcHandle; GetScrubHandleRect( rcHandle, true ); InflateRect( &rcHandle, 2, 2 ); POINT pt; pt.x = (short)event->x; pt.y = (short)event->y; if ( PtInRect( &rcHandle, pt ) ) { return true; } return false; } bool PhonemeEditor::IsMouseOverScrubArea( mxEvent *event ) { RECT rcArea; rcArea.left = 0; rcArea.right = w2(); rcArea.top = 2 + GetCaptionHeight() + 12; rcArea.bottom = rcArea.top + 10; InflateRect( &rcArea, 2, 2 ); POINT pt; pt.x = (short)event->x; pt.y = (short)event->y; if ( PtInRect( &rcArea, pt ) ) { return true; } return false; } float PhonemeEditor::GetTimeForSample( int sample ) { if ( !m_pWaveFile ) { return 0.0f; } float duration = m_pWaveFile->GetRunningLength(); int sampleCount = m_pWaveFile->SampleCount(); if ( sampleCount <= 0 ) return 0.0f; float frac = (float)sample / (float)sampleCount; return frac * duration; } void PhonemeEditor::ClampTimeToSelectionInterval( float& timeval ) { if ( !m_pWaveFile ) { return; } if ( !m_pMixer || !sound->IsSoundPlaying( m_pMixer ) ) { return; } if ( !m_bSelectionActive ) return; float starttime = GetTimeForSample( m_nSelection[ 0 ] ); float endtime = GetTimeForSample( m_nSelection[ 1 ] ); Assert( starttime <= endtime ); timeval = clamp( timeval, starttime, endtime ); } void PhonemeEditor::ScrubThink( float dt, bool scrubbing ) { ClampTimeToSelectionInterval( m_flScrub ); ClampTimeToSelectionInterval( m_flScrubTarget ); if ( m_flScrubTarget == m_flScrub && !scrubbing ) { if ( sound->IsSoundPlaying( m_pMixer ) ) { sound->StopSound( m_pMixer ); } return; } if ( !m_pWaveFile ) return; bool newmixer = false; if ( !m_pMixer || !sound->IsSoundPlaying( m_pMixer ) ) { m_pMixer = NULL; SaveLinguisticData(); StudioModel *model = NULL;//models->GetActiveStudioModel(); sound->PlaySound( model, VOL_NORM, m_WorkFile.m_szWorkingFile, &m_pMixer ); newmixer = true; } if ( !m_pMixer ) { return; } if ( m_flScrub > m_flScrubTarget ) { m_pMixer->SetDirection( false ); } else { m_pMixer->SetDirection( true ); } float duration = m_pWaveFile->GetRunningLength(); if ( !duration ) return; float d = m_flScrubTarget - m_flScrub; int sign = d > 0.0f ? 1 : -1; float maxmove = dt * m_flPlaybackRate; if ( sign > 0 ) { if ( d < maxmove ) { m_flScrub = m_flScrubTarget; } else { m_flScrub += maxmove; } } else { if ( -d < maxmove ) { m_flScrub = m_flScrubTarget; } else { m_flScrub -= maxmove; } } int sampleCount = m_pMixer->GetSource()->SampleCount(); int cursample = sampleCount * ( m_flScrub / duration ); int realsample = m_pMixer->GetSamplePosition(); int dsample = cursample - realsample; int onehundredth = m_pMixer->GetSource()->SampleRate() * 0.01f; if ( abs( dsample ) > onehundredth ) { m_pMixer->SetSamplePosition( cursample, true ); } m_pMixer->SetActive( true ); RECT rcArea; GetScrubAreaRect( rcArea ); CChoreoWidgetDrawHelper drawHelper( this, rcArea ); DrawScrubHandle( drawHelper ); if ( scrubbing ) { g_pMatSysWindow->Frame(); } } void PhonemeEditor::SetScrubTime( float t ) { m_flScrub = t; ClampTimeToSelectionInterval( m_flScrub ); } void PhonemeEditor::SetScrubTargetTime( float t ) { m_flScrubTarget = t; ClampTimeToSelectionInterval( m_flScrubTarget ); } void PhonemeEditor::OnToggleVoiceDuck() { SetDirty( true ); PushUndo(); m_Tags.SetVoiceDuck( !m_Tags.GetVoiceDuck() ); PushRedo(); redraw(); } void PhonemeEditor::Play() { PlayEditedWave( m_bSelectionActive ); }
22.114659
244
0.589844
[ "model" ]
e349cd422e2d5776c24af65efb52a1ede131fd9c
756
cpp
C++
LeetCode/ThousandOne/0066-plus_1.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0066-plus_1.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0066-plus_1.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 66. 加一 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 你可以假设除了整数 0 之外,这个整数不会以零开头。 示例 1: 输入: [1,2,3] 输出: [1,2,4] 解释: 输入数组表示数字 123。 示例 2: 输入: [4,3,2,1] 输出: [4,3,2,2] 解释: 输入数组表示数字 4321。 */ vector<int> plusOne(vector<int>& A) { int len = static_cast<int>(A.size()); div_t q = { 0, 0 }; q.quot = 1; reverse(A.begin(), A.end()); for (int i = 0; i < len; ++i) { q.quot += A[i]; q = div(q.quot, 10); A[i] = q.rem; if (q.quot == 0) break; } if (q.quot) A.push_back(1); reverse(A.begin(), A.end()); vector<int> B; B.swap(A); return B; } int main() { vector<int> a = { 1, 2, 3 }, b = { 4, 3, 2, 1 }, c = { 9, 9, 9 }; output(plusOne(a)); output(plusOne(b)); output(plusOne(c)); }
14
38
0.55291
[ "vector" ]
e3558c50a88323da6f8b8b356cc1715a472e0477
7,366
cpp
C++
src/core/scene.cpp
PtCu/Platinum
2cb30fb8b988ed3cb5efeef4e05c1f6f6c892856
[ "MIT" ]
null
null
null
src/core/scene.cpp
PtCu/Platinum
2cb30fb8b988ed3cb5efeef4e05c1f6f6c892856
[ "MIT" ]
null
null
null
src/core/scene.cpp
PtCu/Platinum
2cb30fb8b988ed3cb5efeef4e05c1f6f6c892856
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2021 PtCU // 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 <core/scene.h> namespace platinum { Scene::~Scene() { destroyAll(); } void Scene::destroyAll() { objects_.clear(); } bool Scene::Hit(const Ray& ray, SurfaceInteraction& inter)const { return _aggres->Hit(ray, inter); } bool Scene::Hit(const Ray& ray)const { return _aggres->Hit(ray); } void Scene::BuildBVH() { this->bvh_accel_ = std::unique_ptr<BVHAccel>(new BVHAccel(objects_)); } void Scene::AddObject(const std::shared_ptr<Object>& obj) { this->objects_.push_back(obj); } void Scene::AddObject(const std::vector<std::shared_ptr<Object>>& obj) { this->objects_.insert(objects_.end(), obj.begin(), obj.end()); } void Scene::AddObject(const std::vector<std::shared_ptr<Object>>::iterator& begin, const std::vector<std::shared_ptr<Object>>::iterator& end) { this->objects_.insert(objects_.end(), begin, end); } void Scene::Reset() { this->bvh_accel_.reset(); this->destroyAll(); } HitRst Scene::RayIn(const Ray& r) const { return this->bvh_accel_->RayCast(r); } void Scene::sampleLight(HitRst& inter, float& pdf) const { float emit_area_sum = 0; for (uint32_t k = 0; k < objects_.size(); ++k) { //计算发光物体的总面积 if (objects_[k]->GetMaterial()->IsEmit()) { emit_area_sum += objects_[k]->GetArea(); } } float p = Random::UniformFloat() * emit_area_sum; emit_area_sum = 0; for (uint32_t k = 0; k < objects_.size(); ++k) { //找到光源 if (objects_[k]->GetMaterial()->IsEmit()) { emit_area_sum += objects_[k]->GetArea(); if (p <= emit_area_sum) { //按概率选取一条光线 objects_[k]->Sample(inter, pdf); break; } } } } glm::vec3 Scene::CastRay(const Ray& r) const { if (mode == 0) return castRay(r, max_depth_); else if (mode == 1) return castRayPdf(r); } glm::vec3 Scene::castRay(const Ray& ray, int dep) const { if (dep == 0) return glm::vec3(1.0001f / 255.0f); auto rst = RayIn(ray); if (rst.is_hit) { if (rst.material == NULL) return glm::vec3(0, 1, 0); //正常情况下,对于漫反射物质继续反射追踪,直到遇到光源则更新颜色并返回 if (rst.material->ComputeScatteringFunctions(rst)) return castRay(ray, dep - 1); else return ray.GetColor(); } else { if (!default_light) return glm::vec3(1.0001f / 255.0f); // //TODO: Make it configurable // environmental light // glm::vec3 unit_direction = glm::normalize(ray->GetDirection()); // float t = 0.5f * (unit_direction.y + 1.0f); // return ray->GetColor() * ((1.0f - t) * glm::vec3(1.0, 1.0, 1.0) + t * glm::vec3(0.75, 0.85, 1.0)); } } glm::vec3 Scene::castRayPdf(const Ray& ray) const { //求一条光线与场景的交点 HitRst obj_rst = RayIn(ray); if (!obj_rst.is_hit) return glm::vec3(0.f); glm::vec3 hit_color(0.f); if (obj_rst.material->IsEmit()) return obj_rst.material->Emit(); //采样光源点 float light_pdf = 1; HitRst light_rst; sampleLight(light_rst, light_pdf); glm::vec3 obj2light = light_rst.record.vert.position_ - obj_rst.record.vert.position_; glm::vec3 obj2light_dir = glm::normalize(obj2light); //确定一条从物体到光源的射线 Ray to_light_ray{ obj_rst.record.vert.position_, obj2light_dir }; glm::vec3 Lo_dir(0.f), Lo_indir(0.f); glm::vec3 w_o = -glm::normalize(ray.GetDirection()); glm::vec3 obj_n = glm::normalize(obj_rst.record.vert.normal_); glm::vec3 light_n = normalize(light_rst.record.vert.normal_); //测试是否有遮挡.向光源打出一条射线 auto bounce_back = RayIn(to_light_ray); if (bounce_back.is_hit && glm::length(bounce_back.record.vert.position_ - light_rst.record.vert.position_) < EPSILON) { //直接光照 //入射方向为光源射向物体,出射方向(所求的方向)为参数ray的方向 glm::vec3 f_r = obj_rst.material->ScatterPdf(obj2light_dir, w_o, obj_rst); //对光源采样 float r2 = glm::dot(obj2light, obj2light); float cosA = std::max(.0f, glm::dot(obj_n, obj2light_dir)); float cosB = std::max(.0f, glm::dot(light_n, -obj2light_dir)); Lo_dir = light_rst.emit * f_r * cosA * cosB / r2 / light_pdf; } hit_color += Lo_dir; if (Random::UniformFloat() > RussianRoulette) return hit_color; //间接光照 //按材质采样一条射线 glm::vec3 w_i = glm::normalize(obj_rst.material->Sample(w_o, obj_rst)); Ray next_ray(obj_rst.record.vert.position_, w_i); auto next_inter = RayIn(next_ray); //下一个物体不发光 if (next_inter.is_hit && !next_inter.material->IsEmit()) { float cos = std::max(.0f, glm::dot(w_i, obj_n)); glm::vec3 f_r = obj_rst.material->ScatterPdf(w_o, w_i, obj_rst); float pdf = obj_rst.material->Pdf(w_o, w_i, obj_rst); Lo_indir = castRayPdf(next_ray) * f_r * cos / pdf / RussianRoulette; } hit_color += Lo_indir; return hit_color; } // bool Scene::IntersectAll(const Ray& &r, HitRst &rst) const // { // HitRst temp_rec; // bool hit_anything = false; // float closest_so_far = std::numeric_limits<float>::max(); // for (int i = 0; i < objects.size(); i++) // { // temp_rec = objects[i]->Intersect(r); // if (temp_rec.isHit && temp_rec.record.ray->GetMaxTime() < closest_so_far) // { // hit_anything = true; // closest_so_far = temp_rec.record.ray->GetMaxTime(); // rst = temp_rec; // } // } // return hit_anything; // } } // namespace platinum
35.584541
145
0.568151
[ "object", "vector" ]
e359cbd72c67da209f6d05fdd9492a9b7ca2e227
3,343
hpp
C++
include/GlobalNamespace/IBeatmapLevelPack.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/IBeatmapLevelPack.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/IBeatmapLevelPack.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: IAnnotatedBeatmapLevelCollection #include "GlobalNamespace/IAnnotatedBeatmapLevelCollection.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Type namespace: namespace GlobalNamespace { // Forward declaring type: IBeatmapLevelPack class IBeatmapLevelPack; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::IBeatmapLevelPack); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::IBeatmapLevelPack*, "", "IBeatmapLevelPack"); // Type namespace: namespace GlobalNamespace { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: IBeatmapLevelPack // [TokenAttribute] Offset: FFFFFFFF class IBeatmapLevelPack/*, public ::GlobalNamespace::IAnnotatedBeatmapLevelCollection*/ { public: // Creating interface conversion operator: operator ::GlobalNamespace::IAnnotatedBeatmapLevelCollection operator ::GlobalNamespace::IAnnotatedBeatmapLevelCollection() noexcept { return *reinterpret_cast<::GlobalNamespace::IAnnotatedBeatmapLevelCollection*>(this); } // public System.String get_packID() // Offset: 0xFFFFFFFFFFFFFFFF ::StringW get_packID(); // public System.String get_packName() // Offset: 0xFFFFFFFFFFFFFFFF ::StringW get_packName(); // public System.String get_shortPackName() // Offset: 0xFFFFFFFFFFFFFFFF ::StringW get_shortPackName(); }; // IBeatmapLevelPack #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::IBeatmapLevelPack::get_packID // Il2CppName: get_packID template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (GlobalNamespace::IBeatmapLevelPack::*)()>(&GlobalNamespace::IBeatmapLevelPack::get_packID)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IBeatmapLevelPack*), "get_packID", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::IBeatmapLevelPack::get_packName // Il2CppName: get_packName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (GlobalNamespace::IBeatmapLevelPack::*)()>(&GlobalNamespace::IBeatmapLevelPack::get_packName)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IBeatmapLevelPack*), "get_packName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::IBeatmapLevelPack::get_shortPackName // Il2CppName: get_shortPackName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (GlobalNamespace::IBeatmapLevelPack::*)()>(&GlobalNamespace::IBeatmapLevelPack::get_shortPackName)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::IBeatmapLevelPack*), "get_shortPackName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
49.161765
181
0.737362
[ "vector" ]
e35a2547903e9504b6da97c5770f1131b9ab65b2
5,747
cpp
C++
insertInterval/insert_interval.cpp
pitanyc/toy-problems
502ef2d2774373349aae7cffdaf287e5ca8613f9
[ "MIT" ]
null
null
null
insertInterval/insert_interval.cpp
pitanyc/toy-problems
502ef2d2774373349aae7cffdaf287e5ca8613f9
[ "MIT" ]
null
null
null
insertInterval/insert_interval.cpp
pitanyc/toy-problems
502ef2d2774373349aae7cffdaf287e5ca8613f9
[ "MIT" ]
null
null
null
/** * LEETCODE 57. Insert Interval * * https://leetcode.com/problems/insert-interval/ * * You are given an array of non-overlapping intervals intervals where * intervals[i] = [starti, endi] represent the start and the end of the * ith interval and intervals is sorted in ascending order by starti. * You are also given an interval newInterval = [start, end] that * represents the start and end of another interval. * * Insert newInterval into intervals such that intervals is still sorted * in ascending order by starti and intervals still does not have any * overlapping intervals (merge overlapping intervals if necessary). * * Return intervals after the insertion. * * Example 1: * * Input: intervals = [[1,3],[6,9]], newInterval = [2,5] * Output: [[1,5],[6,9]] * * Example 2: * * Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] * Output: [[1,2],[3,10],[12,16]] */ #include <algorithm> #include <iostream> #include <vector> using namespace std; // STREAM OPERATOR ==> vector of int ostream& operator<<(ostream& os, const vector<int>& arr) { os << "["; for ( vector<int>::const_iterator it = arr.begin(); it != arr.end(); it++ ) { os << *it; if ( it + 1 != arr.end() ) { os << " "; } } os << "]"; return os; } // STREAM OPERATOR ==> vector of vector of int ostream& operator<<(ostream &os, const vector<vector<int>>& arr) { os << endl; for ( vector<vector<int>>::const_iterator it = arr.begin(); it != arr.end(); it++ ) { os << " " << *it; if (it + 1 != arr.end()) os << endl; } return os; } // SOLUTION 1: Since intervals is sorted by start time: use binary search // to find where the new interval's start time fits in. // There can be edge cases: // * intervals is empty // * new interval is the first (earliest start time) // * new interval is the last (last start time) // // The new interval will either be inserted AFTER an existing // interval IF new interval start time > existing interval end time, // OR it will be merged into the previous interval IF new interval // start time <= existing interval end time. // // After finding the insert location: starting at the insert // location, iterate thru all existing intervals and compare the // end times. If new interval end time > existing interval // end time, then we need to merge this subsequent interval // into the newly inserted interval. Do this until we either // run out of intervals, or find an interval whose start time // is after our end time. // // Time: O(logn) + O(N) = O(N) // Space: vector<vector<int>> insert( vector<vector<int>>& intervals, vector<int>& newInterval) { // locals int count = intervals.size(); int newStart = newInterval.at(0); int newEnd = newInterval.at(1); // binary search intervals until we find the insert location int start = 0; int end = count - 1; int middle = 0; bool found = false; do { middle = (start + end) / 2; int after = min(middle + 1, count - 1); // cout << "start: " << start << ", end: " << end << ", middle: " << middle << ", after: " << after << endl; if (intervals[middle][0] <= newStart && newStart <= intervals[after][0]) { // found it found = true; } else if (newStart > intervals[after][0]) { // go right start = middle; } else { // go left end = middle; } } while (!found && start < end); // at this point, we know the new interval will be inserted between middle and after cout << "found: " << found << ", middle: " << middle << endl; // check if we need to merge new interval with the previous interval if (intervals[middle][1] >= newStart) { // need to merge into previous intervals[middle][1] = max(intervals[middle][1], newEnd); } else { // insert after previous count++; intervals.resize(count); for (int i = count - 1; i > middle; i--) { intervals.at(i) = intervals.at(i-1); } intervals.at(middle + 1) = newInterval; } // ensure all later intervals are non-overlapping bool allGood = false; int curr = middle; int next = min(middle + 1, count - 1); while (!allGood && next < count) { if (intervals[curr][1] >= intervals[next][0]) { // merge intervals[curr][1] = max(intervals[curr][1], intervals[next][1]); intervals.erase(intervals.begin() + next); count--; } else { // all good allGood = true; } } return intervals; } int main(int argc, const char** argv) { // test case 1 vector<vector<int>> intervals = {{1,3},{6,9}}; vector<int> newInterval = {2,5}; cout << "intervals: " << intervals << endl; cout << "newInterval: " << newInterval << endl; vector<vector<int>> output = insert(intervals, newInterval); cout << "output: " << output << endl; // test case 2 cout << "====" << endl; intervals = {{1,2},{3,5},{6,7},{8,10},{12,16}}; newInterval = {4,8}; cout << "intervals: " << intervals << endl; cout << "newInterval: " << newInterval << endl; output = insert(intervals, newInterval); cout << "output: " << output << endl; return 0; }
30.407407
116
0.553854
[ "vector" ]
e35da5db9f72161630c74251a2941e3343bc36e3
43,003
cpp
C++
B2G/gecko/accessible/src/atk/AccessibleWrap.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/accessible/src/atk/AccessibleWrap.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/accessible/src/atk/AccessibleWrap.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "AccessibleWrap.h" #include "Accessible-inl.h" #include "ApplicationAccessibleWrap.h" #include "InterfaceInitFuncs.h" #include "nsAccUtils.h" #include "nsIAccessibleRelation.h" #include "nsIAccessibleTable.h" #include "RootAccessible.h" #include "nsIAccessibleValue.h" #include "nsMai.h" #include "nsMaiHyperlink.h" #include "nsString.h" #include "nsAutoPtr.h" #include "prprf.h" #include "nsStateMap.h" #include "Relation.h" #include "RootAccessible.h" #include "States.h" #include "mozilla/Util.h" #include "nsXPCOMStrings.h" #include "nsComponentManagerUtils.h" using namespace mozilla; using namespace mozilla::a11y; AccessibleWrap::EAvailableAtkSignals AccessibleWrap::gAvailableAtkSignals = eUnknown; //defined in ApplicationAccessibleWrap.cpp extern "C" GType g_atk_hyperlink_impl_type; /* MaiAtkObject */ enum { ACTIVATE, CREATE, DEACTIVATE, DESTROY, MAXIMIZE, MINIMIZE, RESIZE, RESTORE, LAST_SIGNAL }; enum MaiInterfaceType { MAI_INTERFACE_COMPONENT, /* 0 */ MAI_INTERFACE_ACTION, MAI_INTERFACE_VALUE, MAI_INTERFACE_EDITABLE_TEXT, MAI_INTERFACE_HYPERTEXT, MAI_INTERFACE_HYPERLINK_IMPL, MAI_INTERFACE_SELECTION, MAI_INTERFACE_TABLE, MAI_INTERFACE_TEXT, MAI_INTERFACE_DOCUMENT, MAI_INTERFACE_IMAGE /* 10 */ }; static GType GetAtkTypeForMai(MaiInterfaceType type) { switch (type) { case MAI_INTERFACE_COMPONENT: return ATK_TYPE_COMPONENT; case MAI_INTERFACE_ACTION: return ATK_TYPE_ACTION; case MAI_INTERFACE_VALUE: return ATK_TYPE_VALUE; case MAI_INTERFACE_EDITABLE_TEXT: return ATK_TYPE_EDITABLE_TEXT; case MAI_INTERFACE_HYPERTEXT: return ATK_TYPE_HYPERTEXT; case MAI_INTERFACE_HYPERLINK_IMPL: return g_atk_hyperlink_impl_type; case MAI_INTERFACE_SELECTION: return ATK_TYPE_SELECTION; case MAI_INTERFACE_TABLE: return ATK_TYPE_TABLE; case MAI_INTERFACE_TEXT: return ATK_TYPE_TEXT; case MAI_INTERFACE_DOCUMENT: return ATK_TYPE_DOCUMENT; case MAI_INTERFACE_IMAGE: return ATK_TYPE_IMAGE; } return G_TYPE_INVALID; } static const char* kNonUserInputEvent = ":system"; static const GInterfaceInfo atk_if_infos[] = { {(GInterfaceInitFunc)componentInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)actionInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)valueInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)editableTextInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)hypertextInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)hyperlinkImplInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)selectionInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)tableInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)textInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)documentInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL}, {(GInterfaceInitFunc)imageInterfaceInitCB, (GInterfaceFinalizeFunc) NULL, NULL} }; /** * This MaiAtkObject is a thin wrapper, in the MAI namespace, for AtkObject */ struct MaiAtkObject { AtkObject parent; /* * The AccessibleWrap whose properties and features are exported * via this object instance. */ AccessibleWrap* accWrap; }; struct MaiAtkObjectClass { AtkObjectClass parent_class; }; static guint mai_atk_object_signals [LAST_SIGNAL] = { 0, }; #ifdef MAI_LOGGING int32_t sMaiAtkObjCreated = 0; int32_t sMaiAtkObjDeleted = 0; #endif G_BEGIN_DECLS /* callbacks for MaiAtkObject */ static void classInitCB(AtkObjectClass *aClass); static void initializeCB(AtkObject *aAtkObj, gpointer aData); static void finalizeCB(GObject *aObj); /* callbacks for AtkObject virtual functions */ static const gchar* getNameCB (AtkObject *aAtkObj); /* getDescriptionCB is also used by image interface */ const gchar* getDescriptionCB (AtkObject *aAtkObj); static AtkRole getRoleCB(AtkObject *aAtkObj); static AtkAttributeSet* getAttributesCB(AtkObject *aAtkObj); static AtkObject* getParentCB(AtkObject *aAtkObj); static gint getChildCountCB(AtkObject *aAtkObj); static AtkObject* refChildCB(AtkObject *aAtkObj, gint aChildIndex); static gint getIndexInParentCB(AtkObject *aAtkObj); static AtkStateSet* refStateSetCB(AtkObject *aAtkObj); static AtkRelationSet* refRelationSetCB(AtkObject *aAtkObj); /* the missing atkobject virtual functions */ /* static AtkLayer getLayerCB(AtkObject *aAtkObj); static gint getMdiZorderCB(AtkObject *aAtkObj); static void SetNameCB(AtkObject *aAtkObj, const gchar *name); static void SetDescriptionCB(AtkObject *aAtkObj, const gchar *description); static void SetParentCB(AtkObject *aAtkObj, AtkObject *parent); static void SetRoleCB(AtkObject *aAtkObj, AtkRole role); static guint ConnectPropertyChangeHandlerCB( AtkObject *aObj, AtkPropertyChangeHandler *handler); static void RemovePropertyChangeHandlerCB( AtkObject *aAtkObj, guint handler_id); static void InitializeCB(AtkObject *aAtkObj, gpointer data); static void ChildrenChangedCB(AtkObject *aAtkObj, guint change_index, gpointer changed_child); static void FocusEventCB(AtkObject *aAtkObj, gboolean focus_in); static void PropertyChangeCB(AtkObject *aAtkObj, AtkPropertyValues *values); static void StateChangeCB(AtkObject *aAtkObj, const gchar *name, gboolean state_set); static void VisibleDataChangedCB(AtkObject *aAtkObj); */ G_END_DECLS static GType GetMaiAtkType(uint16_t interfacesBits); static const char * GetUniqueMaiAtkTypeName(uint16_t interfacesBits); static gpointer parent_class = NULL; static GQuark quark_mai_hyperlink = 0; GType mai_atk_object_get_type(void) { static GType type = 0; if (!type) { static const GTypeInfo tinfo = { sizeof(MaiAtkObjectClass), (GBaseInitFunc)NULL, (GBaseFinalizeFunc)NULL, (GClassInitFunc)classInitCB, (GClassFinalizeFunc)NULL, NULL, /* class data */ sizeof(MaiAtkObject), /* instance size */ 0, /* nb preallocs */ (GInstanceInitFunc)NULL, NULL /* value table */ }; type = g_type_register_static(ATK_TYPE_OBJECT, "MaiAtkObject", &tinfo, GTypeFlags(0)); quark_mai_hyperlink = g_quark_from_static_string("MaiHyperlink"); } return type; } #ifdef MAI_LOGGING int32_t AccessibleWrap::mAccWrapCreated = 0; int32_t AccessibleWrap::mAccWrapDeleted = 0; #endif AccessibleWrap:: AccessibleWrap(nsIContent* aContent, DocAccessible* aDoc) : Accessible(aContent, aDoc), mAtkObject(nullptr) { #ifdef MAI_LOGGING ++mAccWrapCreated; #endif MAI_LOG_DEBUG(("==AccessibleWrap creating: this=%p,total=%d left=%d\n", (void*)this, mAccWrapCreated, (mAccWrapCreated-mAccWrapDeleted))); } AccessibleWrap::~AccessibleWrap() { NS_ASSERTION(!mAtkObject, "ShutdownAtkObject() is not called"); #ifdef MAI_LOGGING ++mAccWrapDeleted; #endif MAI_LOG_DEBUG(("==AccessibleWrap deleting: this=%p,total=%d left=%d\n", (void*)this, mAccWrapDeleted, (mAccWrapCreated-mAccWrapDeleted))); } void AccessibleWrap::ShutdownAtkObject() { if (mAtkObject) { if (IS_MAI_OBJECT(mAtkObject)) { MAI_ATK_OBJECT(mAtkObject)->accWrap = nullptr; } SetMaiHyperlink(nullptr); g_object_unref(mAtkObject); mAtkObject = nullptr; } } void AccessibleWrap::Shutdown() { ShutdownAtkObject(); Accessible::Shutdown(); } MaiHyperlink* AccessibleWrap::GetMaiHyperlink(bool aCreate /* = true */) { // make sure mAtkObject is created GetAtkObject(); NS_ASSERTION(quark_mai_hyperlink, "quark_mai_hyperlink not initialized"); NS_ASSERTION(IS_MAI_OBJECT(mAtkObject), "Invalid AtkObject"); MaiHyperlink* maiHyperlink = nullptr; if (quark_mai_hyperlink && IS_MAI_OBJECT(mAtkObject)) { maiHyperlink = (MaiHyperlink*)g_object_get_qdata(G_OBJECT(mAtkObject), quark_mai_hyperlink); if (!maiHyperlink && aCreate) { maiHyperlink = new MaiHyperlink(this); SetMaiHyperlink(maiHyperlink); } } return maiHyperlink; } void AccessibleWrap::SetMaiHyperlink(MaiHyperlink* aMaiHyperlink) { NS_ASSERTION(quark_mai_hyperlink, "quark_mai_hyperlink not initialized"); NS_ASSERTION(IS_MAI_OBJECT(mAtkObject), "Invalid AtkObject"); if (quark_mai_hyperlink && IS_MAI_OBJECT(mAtkObject)) { MaiHyperlink* maiHyperlink = GetMaiHyperlink(false); if (!maiHyperlink && !aMaiHyperlink) { return; // Never set and we're shutting down } delete maiHyperlink; g_object_set_qdata(G_OBJECT(mAtkObject), quark_mai_hyperlink, aMaiHyperlink); } } NS_IMETHODIMP AccessibleWrap::GetNativeInterface(void** aOutAccessible) { *aOutAccessible = nullptr; if (!mAtkObject) { if (IsDefunct() || !nsAccUtils::IsEmbeddedObject(this)) { // We don't create ATK objects for node which has been shutdown, or // nsIAccessible plain text leaves return NS_ERROR_FAILURE; } GType type = GetMaiAtkType(CreateMaiInterfaces()); NS_ENSURE_TRUE(type, NS_ERROR_FAILURE); mAtkObject = reinterpret_cast<AtkObject *> (g_object_new(type, NULL)); NS_ENSURE_TRUE(mAtkObject, NS_ERROR_OUT_OF_MEMORY); atk_object_initialize(mAtkObject, this); mAtkObject->role = ATK_ROLE_INVALID; mAtkObject->layer = ATK_LAYER_INVALID; } *aOutAccessible = mAtkObject; return NS_OK; } AtkObject * AccessibleWrap::GetAtkObject(void) { void *atkObj = nullptr; GetNativeInterface(&atkObj); return static_cast<AtkObject *>(atkObj); } // Get AtkObject from nsIAccessible interface /* static */ AtkObject * AccessibleWrap::GetAtkObject(nsIAccessible* acc) { void *atkObjPtr = nullptr; acc->GetNativeInterface(&atkObjPtr); return atkObjPtr ? ATK_OBJECT(atkObjPtr) : nullptr; } /* private */ uint16_t AccessibleWrap::CreateMaiInterfaces(void) { uint16_t interfacesBits = 0; // The Component interface is supported by all accessibles. interfacesBits |= 1 << MAI_INTERFACE_COMPONENT; // Add Action interface if the action count is more than zero. if (ActionCount() > 0) interfacesBits |= 1 << MAI_INTERFACE_ACTION; // Text, Editabletext, and Hypertext interface. HyperTextAccessible* hyperText = AsHyperText(); if (hyperText && hyperText->IsTextRole()) { interfacesBits |= 1 << MAI_INTERFACE_TEXT; interfacesBits |= 1 << MAI_INTERFACE_EDITABLE_TEXT; if (!nsAccUtils::MustPrune(this)) interfacesBits |= 1 << MAI_INTERFACE_HYPERTEXT; } // Value interface. nsCOMPtr<nsIAccessibleValue> accessInterfaceValue; QueryInterface(NS_GET_IID(nsIAccessibleValue), getter_AddRefs(accessInterfaceValue)); if (accessInterfaceValue) { interfacesBits |= 1 << MAI_INTERFACE_VALUE; } // Document interface. if (IsDoc()) interfacesBits |= 1 << MAI_INTERFACE_DOCUMENT; if (IsImage()) interfacesBits |= 1 << MAI_INTERFACE_IMAGE; // HyperLink interface. if (IsLink()) interfacesBits |= 1 << MAI_INTERFACE_HYPERLINK_IMPL; if (!nsAccUtils::MustPrune(this)) { // These interfaces require children // Table interface. if (AsTable()) interfacesBits |= 1 << MAI_INTERFACE_TABLE; // Selection interface. if (IsSelect()) { interfacesBits |= 1 << MAI_INTERFACE_SELECTION; } } return interfacesBits; } static GType GetMaiAtkType(uint16_t interfacesBits) { GType type; static const GTypeInfo tinfo = { sizeof(MaiAtkObjectClass), (GBaseInitFunc) NULL, (GBaseFinalizeFunc) NULL, (GClassInitFunc) NULL, (GClassFinalizeFunc) NULL, NULL, /* class data */ sizeof(MaiAtkObject), /* instance size */ 0, /* nb preallocs */ (GInstanceInitFunc) NULL, NULL /* value table */ }; /* * The members we use to register GTypes are GetAtkTypeForMai * and atk_if_infos, which are constant values to each MaiInterface * So we can reuse the registered GType when having * the same MaiInterface types. */ const char *atkTypeName = GetUniqueMaiAtkTypeName(interfacesBits); type = g_type_from_name(atkTypeName); if (type) { return type; } /* * gobject limits the number of types that can directly derive from any * given object type to 4095. */ static uint16_t typeRegCount = 0; if (typeRegCount++ >= 4095) { return G_TYPE_INVALID; } type = g_type_register_static(MAI_TYPE_ATK_OBJECT, atkTypeName, &tinfo, GTypeFlags(0)); for (uint32_t index = 0; index < ArrayLength(atk_if_infos); index++) { if (interfacesBits & (1 << index)) { g_type_add_interface_static(type, GetAtkTypeForMai((MaiInterfaceType)index), &atk_if_infos[index]); } } return type; } static const char* GetUniqueMaiAtkTypeName(uint16_t interfacesBits) { #define MAI_ATK_TYPE_NAME_LEN (30) /* 10+sizeof(uint16_t)*8/4+1 < 30 */ static gchar namePrefix[] = "MaiAtkType"; /* size = 10 */ static gchar name[MAI_ATK_TYPE_NAME_LEN + 1]; PR_snprintf(name, MAI_ATK_TYPE_NAME_LEN, "%s%x", namePrefix, interfacesBits); name[MAI_ATK_TYPE_NAME_LEN] = '\0'; MAI_LOG_DEBUG(("MaiWidget::LastedTypeName=%s\n", name)); return name; } bool AccessibleWrap::IsValidObject() { // to ensure we are not shut down return !IsDefunct(); } /* static functions for ATK callbacks */ void classInitCB(AtkObjectClass *aClass) { GObjectClass *gobject_class = G_OBJECT_CLASS(aClass); parent_class = g_type_class_peek_parent(aClass); aClass->get_name = getNameCB; aClass->get_description = getDescriptionCB; aClass->get_parent = getParentCB; aClass->get_n_children = getChildCountCB; aClass->ref_child = refChildCB; aClass->get_index_in_parent = getIndexInParentCB; aClass->get_role = getRoleCB; aClass->get_attributes = getAttributesCB; aClass->ref_state_set = refStateSetCB; aClass->ref_relation_set = refRelationSetCB; aClass->initialize = initializeCB; gobject_class->finalize = finalizeCB; mai_atk_object_signals [ACTIVATE] = g_signal_new ("activate", MAI_TYPE_ATK_OBJECT, G_SIGNAL_RUN_LAST, 0, /* default signal handler */ NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); mai_atk_object_signals [CREATE] = g_signal_new ("create", MAI_TYPE_ATK_OBJECT, G_SIGNAL_RUN_LAST, 0, /* default signal handler */ NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); mai_atk_object_signals [DEACTIVATE] = g_signal_new ("deactivate", MAI_TYPE_ATK_OBJECT, G_SIGNAL_RUN_LAST, 0, /* default signal handler */ NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); mai_atk_object_signals [DESTROY] = g_signal_new ("destroy", MAI_TYPE_ATK_OBJECT, G_SIGNAL_RUN_LAST, 0, /* default signal handler */ NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); mai_atk_object_signals [MAXIMIZE] = g_signal_new ("maximize", MAI_TYPE_ATK_OBJECT, G_SIGNAL_RUN_LAST, 0, /* default signal handler */ NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); mai_atk_object_signals [MINIMIZE] = g_signal_new ("minimize", MAI_TYPE_ATK_OBJECT, G_SIGNAL_RUN_LAST, 0, /* default signal handler */ NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); mai_atk_object_signals [RESIZE] = g_signal_new ("resize", MAI_TYPE_ATK_OBJECT, G_SIGNAL_RUN_LAST, 0, /* default signal handler */ NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); mai_atk_object_signals [RESTORE] = g_signal_new ("restore", MAI_TYPE_ATK_OBJECT, G_SIGNAL_RUN_LAST, 0, /* default signal handler */ NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); } void initializeCB(AtkObject *aAtkObj, gpointer aData) { NS_ASSERTION((IS_MAI_OBJECT(aAtkObj)), "Invalid AtkObject"); NS_ASSERTION(aData, "Invalid Data to init AtkObject"); if (!aAtkObj || !aData) return; /* call parent init function */ /* AtkObjectClass has not a "initialize" function now, * maybe it has later */ if (ATK_OBJECT_CLASS(parent_class)->initialize) ATK_OBJECT_CLASS(parent_class)->initialize(aAtkObj, aData); /* initialize object */ MAI_ATK_OBJECT(aAtkObj)->accWrap = static_cast<AccessibleWrap*>(aData); #ifdef MAI_LOGGING ++sMaiAtkObjCreated; #endif MAI_LOG_DEBUG(("MaiAtkObj Create obj=%p for AccWrap=%p, all=%d, left=%d\n", (void*)aAtkObj, (void*)aData, sMaiAtkObjCreated, (sMaiAtkObjCreated-sMaiAtkObjDeleted))); } void finalizeCB(GObject *aObj) { if (!IS_MAI_OBJECT(aObj)) return; NS_ASSERTION(MAI_ATK_OBJECT(aObj)->accWrap == nullptr, "AccWrap NOT null"); #ifdef MAI_LOGGING ++sMaiAtkObjDeleted; #endif MAI_LOG_DEBUG(("MaiAtkObj Delete obj=%p, all=%d, left=%d\n", (void*)aObj, sMaiAtkObjCreated, (sMaiAtkObjCreated-sMaiAtkObjDeleted))); // call parent finalize function // finalize of GObjectClass will unref the accessible parent if has if (G_OBJECT_CLASS (parent_class)->finalize) G_OBJECT_CLASS (parent_class)->finalize(aObj); } const gchar* getNameCB(AtkObject* aAtkObj) { AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap) return nullptr; nsAutoString uniName; accWrap->Name(uniName); NS_ConvertUTF8toUTF16 objName(aAtkObj->name); if (!uniName.Equals(objName)) atk_object_set_name(aAtkObj, NS_ConvertUTF16toUTF8(uniName).get()); return aAtkObj->name; } const gchar * getDescriptionCB(AtkObject *aAtkObj) { AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap || accWrap->IsDefunct()) return nullptr; /* nsIAccessible is responsible for the non-NULL description */ nsAutoString uniDesc; accWrap->Description(uniDesc); NS_ConvertUTF8toUTF16 objDesc(aAtkObj->description); if (!uniDesc.Equals(objDesc)) atk_object_set_description(aAtkObj, NS_ConvertUTF16toUTF8(uniDesc).get()); return aAtkObj->description; } AtkRole getRoleCB(AtkObject *aAtkObj) { AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap) return ATK_ROLE_INVALID; #ifdef DEBUG NS_ASSERTION(nsAccUtils::IsTextInterfaceSupportCorrect(accWrap), "Does not support nsIAccessibleText when it should"); #endif if (aAtkObj->role != ATK_ROLE_INVALID) return aAtkObj->role; #define ROLE(geckoRole, stringRole, atkRole, macRole, \ msaaRole, ia2Role, nameRule) \ case roles::geckoRole: \ aAtkObj->role = atkRole; \ break; switch (accWrap->Role()) { #include "RoleMap.h" default: MOZ_NOT_REACHED("Unknown role."); aAtkObj->role = ATK_ROLE_UNKNOWN; }; #undef ROLE return aAtkObj->role; } AtkAttributeSet* ConvertToAtkAttributeSet(nsIPersistentProperties* aAttributes) { if (!aAttributes) return nullptr; AtkAttributeSet *objAttributeSet = nullptr; nsCOMPtr<nsISimpleEnumerator> propEnum; nsresult rv = aAttributes->Enumerate(getter_AddRefs(propEnum)); NS_ENSURE_SUCCESS(rv, nullptr); bool hasMore; while (NS_SUCCEEDED(propEnum->HasMoreElements(&hasMore)) && hasMore) { nsCOMPtr<nsISupports> sup; rv = propEnum->GetNext(getter_AddRefs(sup)); NS_ENSURE_SUCCESS(rv, objAttributeSet); nsCOMPtr<nsIPropertyElement> propElem(do_QueryInterface(sup)); NS_ENSURE_TRUE(propElem, objAttributeSet); nsAutoCString name; rv = propElem->GetKey(name); NS_ENSURE_SUCCESS(rv, objAttributeSet); nsAutoString value; rv = propElem->GetValue(value); NS_ENSURE_SUCCESS(rv, objAttributeSet); AtkAttribute *objAttr = (AtkAttribute *)g_malloc(sizeof(AtkAttribute)); objAttr->name = g_strdup(name.get()); objAttr->value = g_strdup(NS_ConvertUTF16toUTF8(value).get()); objAttributeSet = g_slist_prepend(objAttributeSet, objAttr); } //libspi will free it return objAttributeSet; } AtkAttributeSet* GetAttributeSet(Accessible* aAccessible) { nsCOMPtr<nsIPersistentProperties> attributes; aAccessible->GetAttributes(getter_AddRefs(attributes)); if (attributes) { // Deal with attributes that we only need to expose in ATK if (aAccessible->State() & states::HASPOPUP) { // There is no ATK state for haspopup, must use object attribute to expose the same info nsAutoString oldValueUnused; attributes->SetStringProperty(NS_LITERAL_CSTRING("haspopup"), NS_LITERAL_STRING("true"), oldValueUnused); } return ConvertToAtkAttributeSet(attributes); } return nullptr; } AtkAttributeSet * getAttributesCB(AtkObject *aAtkObj) { AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); return accWrap ? GetAttributeSet(accWrap) : nullptr; } AtkObject * getParentCB(AtkObject *aAtkObj) { if (!aAtkObj->accessible_parent) { AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap) return nullptr; Accessible* accParent = accWrap->Parent(); if (!accParent) return nullptr; AtkObject* parent = AccessibleWrap::GetAtkObject(accParent); if (parent) atk_object_set_parent(aAtkObj, parent); } return aAtkObj->accessible_parent; } gint getChildCountCB(AtkObject *aAtkObj) { AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap || nsAccUtils::MustPrune(accWrap)) { return 0; } return static_cast<gint>(accWrap->EmbeddedChildCount()); } AtkObject * refChildCB(AtkObject *aAtkObj, gint aChildIndex) { // aChildIndex should not be less than zero if (aChildIndex < 0) { return nullptr; } AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap || nsAccUtils::MustPrune(accWrap)) { return nullptr; } Accessible* accChild = accWrap->GetEmbeddedChildAt(aChildIndex); if (!accChild) return nullptr; AtkObject* childAtkObj = AccessibleWrap::GetAtkObject(accChild); NS_ASSERTION(childAtkObj, "Fail to get AtkObj"); if (!childAtkObj) return nullptr; g_object_ref(childAtkObj); if (aAtkObj != childAtkObj->accessible_parent) atk_object_set_parent(childAtkObj, aAtkObj); return childAtkObj; } gint getIndexInParentCB(AtkObject *aAtkObj) { // We don't use nsIAccessible::GetIndexInParent() because // for ATK we don't want to include text leaf nodes as children AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap) { return -1; } Accessible* parent = accWrap->Parent(); if (!parent) return -1; // No parent return parent->GetIndexOfEmbeddedChild(accWrap); } static void TranslateStates(uint64_t aState, AtkStateSet* aStateSet) { // Convert every state to an entry in AtkStateMap uint32_t stateIndex = 0; uint64_t bitMask = 1; while (gAtkStateMap[stateIndex].stateMapEntryType != kNoSuchState) { if (gAtkStateMap[stateIndex].atkState) { // There's potentially an ATK state for this bool isStateOn = (aState & bitMask) != 0; if (gAtkStateMap[stateIndex].stateMapEntryType == kMapOpposite) { isStateOn = !isStateOn; } if (isStateOn) { atk_state_set_add_state(aStateSet, gAtkStateMap[stateIndex].atkState); } } bitMask <<= 1; ++ stateIndex; } } AtkStateSet * refStateSetCB(AtkObject *aAtkObj) { AtkStateSet *state_set = nullptr; state_set = ATK_OBJECT_CLASS(parent_class)->ref_state_set(aAtkObj); AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap) { TranslateStates(states::DEFUNCT, state_set); return state_set; } // Map states TranslateStates(accWrap->State(), state_set); return state_set; } AtkRelationSet * refRelationSetCB(AtkObject *aAtkObj) { AtkRelationSet* relation_set = ATK_OBJECT_CLASS(parent_class)->ref_relation_set(aAtkObj); AccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj); if (!accWrap) return relation_set; uint32_t relationTypes[] = { nsIAccessibleRelation::RELATION_LABELLED_BY, nsIAccessibleRelation::RELATION_LABEL_FOR, nsIAccessibleRelation::RELATION_NODE_CHILD_OF, nsIAccessibleRelation::RELATION_CONTROLLED_BY, nsIAccessibleRelation::RELATION_CONTROLLER_FOR, nsIAccessibleRelation::RELATION_EMBEDS, nsIAccessibleRelation::RELATION_FLOWS_TO, nsIAccessibleRelation::RELATION_FLOWS_FROM, nsIAccessibleRelation::RELATION_DESCRIBED_BY, nsIAccessibleRelation::RELATION_DESCRIPTION_FOR, }; for (uint32_t i = 0; i < ArrayLength(relationTypes); i++) { AtkRelationType atkType = static_cast<AtkRelationType>(relationTypes[i]); AtkRelation* atkRelation = atk_relation_set_get_relation_by_type(relation_set, atkType); if (atkRelation) atk_relation_set_remove(relation_set, atkRelation); Relation rel(accWrap->RelationByType(relationTypes[i])); nsTArray<AtkObject*> targets; Accessible* tempAcc = nullptr; while ((tempAcc = rel.Next())) targets.AppendElement(AccessibleWrap::GetAtkObject(tempAcc)); if (targets.Length()) { atkRelation = atk_relation_new(targets.Elements(), targets.Length(), atkType); atk_relation_set_add(relation_set, atkRelation); g_object_unref(atkRelation); } } return relation_set; } // Check if aAtkObj is a valid MaiAtkObject, and return the AccessibleWrap // for it. AccessibleWrap* GetAccessibleWrap(AtkObject* aAtkObj) { NS_ENSURE_TRUE(IS_MAI_OBJECT(aAtkObj), nullptr); AccessibleWrap* accWrap = MAI_ATK_OBJECT(aAtkObj)->accWrap; // Check if the accessible was deconstructed. if (!accWrap) return nullptr; NS_ENSURE_TRUE(accWrap->GetAtkObject() == aAtkObj, nullptr); AccessibleWrap* appAccWrap = ApplicationAcc(); if (appAccWrap != accWrap && !accWrap->IsValidObject()) return nullptr; return accWrap; } nsresult AccessibleWrap::HandleAccEvent(AccEvent* aEvent) { nsresult rv = Accessible::HandleAccEvent(aEvent); NS_ENSURE_SUCCESS(rv, rv); return FirePlatformEvent(aEvent); } nsresult AccessibleWrap::FirePlatformEvent(AccEvent* aEvent) { Accessible* accessible = aEvent->GetAccessible(); NS_ENSURE_TRUE(accessible, NS_ERROR_FAILURE); uint32_t type = aEvent->GetEventType(); AtkObject* atkObj = AccessibleWrap::GetAtkObject(accessible); // We don't create ATK objects for nsIAccessible plain text leaves, // just return NS_OK in such case if (!atkObj) { NS_ASSERTION(type == nsIAccessibleEvent::EVENT_SHOW || type == nsIAccessibleEvent::EVENT_HIDE, "Event other than SHOW and HIDE fired for plain text leaves"); return NS_OK; } AccessibleWrap* accWrap = GetAccessibleWrap(atkObj); if (!accWrap) { return NS_OK; // Node is shut down } switch (type) { case nsIAccessibleEvent::EVENT_STATE_CHANGE: return FireAtkStateChangeEvent(aEvent, atkObj); case nsIAccessibleEvent::EVENT_TEXT_REMOVED: case nsIAccessibleEvent::EVENT_TEXT_INSERTED: return FireAtkTextChangedEvent(aEvent, atkObj); case nsIAccessibleEvent::EVENT_FOCUS: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_FOCUS\n")); a11y::RootAccessible* rootAccWrap = accWrap->RootAccessible(); if (rootAccWrap && rootAccWrap->mActivated) { atk_focus_tracker_notify(atkObj); // Fire state change event for focus nsRefPtr<AccEvent> stateChangeEvent = new AccStateChangeEvent(accessible, states::FOCUSED, true); return FireAtkStateChangeEvent(stateChangeEvent, atkObj); } } break; case nsIAccessibleEvent::EVENT_NAME_CHANGE: { nsAutoString newName; accessible->Name(newName); NS_ConvertUTF16toUTF8 utf8Name(newName); if (!atkObj->name || !utf8Name.Equals(atkObj->name)) atk_object_set_name(atkObj, utf8Name.get()); break; } case nsIAccessibleEvent::EVENT_VALUE_CHANGE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_VALUE_CHANGE\n")); nsCOMPtr<nsIAccessibleValue> value(do_QueryObject(accessible)); if (value) { // Make sure this is a numeric value // Don't fire for MSAA string value changes (e.g. text editing) // ATK values are always numeric g_object_notify( (GObject*)atkObj, "accessible-value" ); } } break; case nsIAccessibleEvent::EVENT_SELECTION: case nsIAccessibleEvent::EVENT_SELECTION_ADD: case nsIAccessibleEvent::EVENT_SELECTION_REMOVE: { // XXX: dupe events may be fired MAI_LOG_DEBUG(("\n\nReceived: EVENT_SELECTION_CHANGED\n")); AccSelChangeEvent* selChangeEvent = downcast_accEvent(aEvent); g_signal_emit_by_name(AccessibleWrap::GetAtkObject(selChangeEvent->Widget()), "selection_changed"); break; } case nsIAccessibleEvent::EVENT_SELECTION_WITHIN: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_SELECTION_CHANGED\n")); g_signal_emit_by_name(atkObj, "selection_changed"); break; } case nsIAccessibleEvent::EVENT_TEXT_SELECTION_CHANGED: MAI_LOG_DEBUG(("\n\nReceived: EVENT_TEXT_SELECTION_CHANGED\n")); g_signal_emit_by_name(atkObj, "text_selection_changed"); break; case nsIAccessibleEvent::EVENT_TEXT_CARET_MOVED: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_TEXT_CARET_MOVED\n")); AccCaretMoveEvent* caretMoveEvent = downcast_accEvent(aEvent); NS_ASSERTION(caretMoveEvent, "Event needs event data"); if (!caretMoveEvent) break; int32_t caretOffset = caretMoveEvent->GetCaretOffset(); MAI_LOG_DEBUG(("\n\nCaret postion: %d", caretOffset)); g_signal_emit_by_name(atkObj, "text_caret_moved", // Curent caret position caretOffset); } break; case nsIAccessibleEvent::EVENT_TEXT_ATTRIBUTE_CHANGED: MAI_LOG_DEBUG(("\n\nReceived: EVENT_TEXT_ATTRIBUTE_CHANGED\n")); g_signal_emit_by_name(atkObj, "text-attributes-changed"); break; case nsIAccessibleEvent::EVENT_TABLE_MODEL_CHANGED: MAI_LOG_DEBUG(("\n\nReceived: EVENT_TABLE_MODEL_CHANGED\n")); g_signal_emit_by_name(atkObj, "model_changed"); break; case nsIAccessibleEvent::EVENT_TABLE_ROW_INSERT: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_TABLE_ROW_INSERT\n")); AccTableChangeEvent* tableEvent = downcast_accEvent(aEvent); NS_ENSURE_TRUE(tableEvent, NS_ERROR_FAILURE); int32_t rowIndex = tableEvent->GetIndex(); int32_t numRows = tableEvent->GetCount(); g_signal_emit_by_name(atkObj, "row_inserted", // After which the rows are inserted rowIndex, // The number of the inserted numRows); } break; case nsIAccessibleEvent::EVENT_TABLE_ROW_DELETE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_TABLE_ROW_DELETE\n")); AccTableChangeEvent* tableEvent = downcast_accEvent(aEvent); NS_ENSURE_TRUE(tableEvent, NS_ERROR_FAILURE); int32_t rowIndex = tableEvent->GetIndex(); int32_t numRows = tableEvent->GetCount(); g_signal_emit_by_name(atkObj, "row_deleted", // After which the rows are deleted rowIndex, // The number of the deleted numRows); } break; case nsIAccessibleEvent::EVENT_TABLE_ROW_REORDER: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_TABLE_ROW_REORDER\n")); g_signal_emit_by_name(atkObj, "row_reordered"); break; } case nsIAccessibleEvent::EVENT_TABLE_COLUMN_INSERT: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_TABLE_COLUMN_INSERT\n")); AccTableChangeEvent* tableEvent = downcast_accEvent(aEvent); NS_ENSURE_TRUE(tableEvent, NS_ERROR_FAILURE); int32_t colIndex = tableEvent->GetIndex(); int32_t numCols = tableEvent->GetCount(); g_signal_emit_by_name(atkObj, "column_inserted", // After which the columns are inserted colIndex, // The number of the inserted numCols); } break; case nsIAccessibleEvent::EVENT_TABLE_COLUMN_DELETE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_TABLE_COLUMN_DELETE\n")); AccTableChangeEvent* tableEvent = downcast_accEvent(aEvent); NS_ENSURE_TRUE(tableEvent, NS_ERROR_FAILURE); int32_t colIndex = tableEvent->GetIndex(); int32_t numCols = tableEvent->GetCount(); g_signal_emit_by_name(atkObj, "column_deleted", // After which the columns are deleted colIndex, // The number of the deleted numCols); } break; case nsIAccessibleEvent::EVENT_TABLE_COLUMN_REORDER: MAI_LOG_DEBUG(("\n\nReceived: EVENT_TABLE_COLUMN_REORDER\n")); g_signal_emit_by_name(atkObj, "column_reordered"); break; case nsIAccessibleEvent::EVENT_SECTION_CHANGED: MAI_LOG_DEBUG(("\n\nReceived: EVENT_SECTION_CHANGED\n")); g_signal_emit_by_name(atkObj, "visible_data_changed"); break; case nsIAccessibleEvent::EVENT_SHOW: return FireAtkShowHideEvent(aEvent, atkObj, true); case nsIAccessibleEvent::EVENT_HIDE: return FireAtkShowHideEvent(aEvent, atkObj, false); /* * Because dealing with menu is very different between nsIAccessible * and ATK, and the menu activity is important, specially transfer the * following two event. * Need more verification by AT test. */ case nsIAccessibleEvent::EVENT_MENU_START: MAI_LOG_DEBUG(("\n\nReceived: EVENT_MENU_START\n")); break; case nsIAccessibleEvent::EVENT_MENU_END: MAI_LOG_DEBUG(("\n\nReceived: EVENT_MENU_END\n")); break; case nsIAccessibleEvent::EVENT_WINDOW_ACTIVATE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_WINDOW_ACTIVATED\n")); accessible->AsRoot()->mActivated = true; guint id = g_signal_lookup ("activate", MAI_TYPE_ATK_OBJECT); g_signal_emit(atkObj, id, 0); // Always fire a current focus event after activation. FocusMgr()->ForceFocusEvent(); } break; case nsIAccessibleEvent::EVENT_WINDOW_DEACTIVATE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_WINDOW_DEACTIVATED\n")); accessible->AsRoot()->mActivated = false; guint id = g_signal_lookup ("deactivate", MAI_TYPE_ATK_OBJECT); g_signal_emit(atkObj, id, 0); } break; case nsIAccessibleEvent::EVENT_WINDOW_MAXIMIZE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_WINDOW_MAXIMIZE\n")); guint id = g_signal_lookup ("maximize", MAI_TYPE_ATK_OBJECT); g_signal_emit(atkObj, id, 0); } break; case nsIAccessibleEvent::EVENT_WINDOW_MINIMIZE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_WINDOW_MINIMIZE\n")); guint id = g_signal_lookup ("minimize", MAI_TYPE_ATK_OBJECT); g_signal_emit(atkObj, id, 0); } break; case nsIAccessibleEvent::EVENT_WINDOW_RESTORE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_WINDOW_RESTORE\n")); guint id = g_signal_lookup ("restore", MAI_TYPE_ATK_OBJECT); g_signal_emit(atkObj, id, 0); } break; case nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_COMPLETE: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_DOCUMENT_LOAD_COMPLETE\n")); g_signal_emit_by_name (atkObj, "load_complete"); } break; case nsIAccessibleEvent::EVENT_DOCUMENT_RELOAD: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_DOCUMENT_RELOAD\n")); g_signal_emit_by_name (atkObj, "reload"); } break; case nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_STOPPED: { MAI_LOG_DEBUG(("\n\nReceived: EVENT_DOCUMENT_LOAD_STOPPED\n")); g_signal_emit_by_name (atkObj, "load_stopped"); } break; case nsIAccessibleEvent::EVENT_MENUPOPUP_START: MAI_LOG_DEBUG(("\n\nReceived: EVENT_MENUPOPUP_START\n")); atk_focus_tracker_notify(atkObj); // fire extra focus event atk_object_notify_state_change(atkObj, ATK_STATE_VISIBLE, true); atk_object_notify_state_change(atkObj, ATK_STATE_SHOWING, true); break; case nsIAccessibleEvent::EVENT_MENUPOPUP_END: MAI_LOG_DEBUG(("\n\nReceived: EVENT_MENUPOPUP_END\n")); atk_object_notify_state_change(atkObj, ATK_STATE_VISIBLE, false); atk_object_notify_state_change(atkObj, ATK_STATE_SHOWING, false); break; } return NS_OK; } nsresult AccessibleWrap::FireAtkStateChangeEvent(AccEvent* aEvent, AtkObject* aObject) { MAI_LOG_DEBUG(("\n\nReceived: EVENT_STATE_CHANGE\n")); AccStateChangeEvent* event = downcast_accEvent(aEvent); NS_ENSURE_TRUE(event, NS_ERROR_FAILURE); bool isEnabled = event->IsStateEnabled(); int32_t stateIndex = AtkStateMap::GetStateIndexFor(event->GetState()); if (stateIndex >= 0) { NS_ASSERTION(gAtkStateMap[stateIndex].stateMapEntryType != kNoSuchState, "No such state"); if (gAtkStateMap[stateIndex].atkState != kNone) { NS_ASSERTION(gAtkStateMap[stateIndex].stateMapEntryType != kNoStateChange, "State changes should not fired for this state"); if (gAtkStateMap[stateIndex].stateMapEntryType == kMapOpposite) isEnabled = !isEnabled; // Fire state change for first state if there is one to map atk_object_notify_state_change(aObject, gAtkStateMap[stateIndex].atkState, isEnabled); } } return NS_OK; } nsresult AccessibleWrap::FireAtkTextChangedEvent(AccEvent* aEvent, AtkObject* aObject) { MAI_LOG_DEBUG(("\n\nReceived: EVENT_TEXT_REMOVED/INSERTED\n")); AccTextChangeEvent* event = downcast_accEvent(aEvent); NS_ENSURE_TRUE(event, NS_ERROR_FAILURE); int32_t start = event->GetStartOffset(); uint32_t length = event->GetLength(); bool isInserted = event->IsTextInserted(); bool isFromUserInput = aEvent->IsFromUserInput(); char* signal_name = nullptr; if (gAvailableAtkSignals == eUnknown) gAvailableAtkSignals = g_signal_lookup("text-insert", G_OBJECT_TYPE(aObject)) ? eHaveNewAtkTextSignals : eNoNewAtkSignals; if (gAvailableAtkSignals == eNoNewAtkSignals) { // XXX remove this code and the gHaveNewTextSignals check when we can // stop supporting old atk since it doesn't really work anyway // see bug 619002 signal_name = g_strconcat(isInserted ? "text_changed::insert" : "text_changed::delete", isFromUserInput ? "" : kNonUserInputEvent, NULL); g_signal_emit_by_name(aObject, signal_name, start, length); } else { nsAutoString text; event->GetModifiedText(text); signal_name = g_strconcat(isInserted ? "text-insert" : "text-remove", isFromUserInput ? "" : "::system", NULL); g_signal_emit_by_name(aObject, signal_name, start, length, NS_ConvertUTF16toUTF8(text).get()); } g_free(signal_name); return NS_OK; } nsresult AccessibleWrap::FireAtkShowHideEvent(AccEvent* aEvent, AtkObject* aObject, bool aIsAdded) { if (aIsAdded) { MAI_LOG_DEBUG(("\n\nReceived: Show event\n")); } else { MAI_LOG_DEBUG(("\n\nReceived: Hide event\n")); } int32_t indexInParent = getIndexInParentCB(aObject); AtkObject *parentObject = getParentCB(aObject); NS_ENSURE_STATE(parentObject); bool isFromUserInput = aEvent->IsFromUserInput(); char *signal_name = g_strconcat(aIsAdded ? "children_changed::add" : "children_changed::remove", isFromUserInput ? "" : kNonUserInputEvent, NULL); g_signal_emit_by_name(parentObject, signal_name, indexInParent, aObject, NULL); g_free(signal_name); return NS_OK; }
31.666421
101
0.661117
[ "object" ]
e37045fc6859168be6d56c3702bc2824551c2d06
3,571
cc
C++
folding_libs/MELIBS/arpack++/examples/reverse/complex/rcompshf.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
1
2016-05-16T02:27:46.000Z
2016-05-16T02:27:46.000Z
arpack++/examples/reverse/complex/rcompshf.cc
red2901/sandbox
fae6c1624cc9957593d030f3b0306dbded29f0a2
[ "MIT" ]
null
null
null
arpack++/examples/reverse/complex/rcompshf.cc
red2901/sandbox
fae6c1624cc9957593d030f3b0306dbded29f0a2
[ "MIT" ]
null
null
null
/* ARPACK++ v1.2 2/18/2000 c++ interface to ARPACK code. MODULE RCompShf.cc. Example program that illustrates how to solve a complex standard eigenvalue problem in shift and invert mode using the ARrcCompStdEig class. 1) Problem description: In this example we try to solve A*x = x*lambda in shift and invert mode, where A is derived from the central difference discretization of the 1-dimensional convection-diffusion operator (d^2u/dx^2) + rho*(du/dx) on the interval [0,1] with zero Dirichlet boundary conditions. 2) Data structure used to represent matrix A: class ARrcCompStdEig requires the user to provide a way to perform the matrix-vector product w = OPv, where OP = inv[A - sigma*I]. In this example a class called CompMatrixB was created with this purpose. CompMatrixB contains a member function, MultOPv, that takes a vector v and returns the product OPv in w. 3) The reverse communication interface: This example uses the reverse communication interface, which means that the desired eigenvalues cannot be obtained directly from an ARPACK++ class. Here, the overall process of finding eigenvalues by using the Arnoldi method is splitted into two parts. In the first, a sequence of calls to a function called TakeStep is combined with matrix-vector products in order to find an Arnoldi basis. In the second part, an ARPACK++ function like FindEigenvectors (or EigenValVectors) is used to extract eigenvalues and eigenvectors. 4) Included header files: File Contents ----------- ------------------------------------------- cmatrixb.h The CompMatrixB class definition. arrscomp.h The ARrcCompStdEig class definition. rcompsol.h The Solution function. arcomp.h The "arcomplex" (complex) type definition. 5) ARPACK Authors: Richard Lehoucq Kristyn Maschhoff Danny Sorensen Chao Yang Dept. of Computational & Applied Mathematics Rice University Houston, Texas */ #include "arcomp.h" #include "arrscomp.h" #include "cmatrixb.h" #include "rcompsol.h" template<class T> void Test(T type) { // Creating a complex matrix (n = 100, shift = 0, rho = 10). CompMatrixB<T> A(100, arcomplex<T>(0.0,0.0), arcomplex<T>(10.0,0.0)); // Creating a complex eigenvalue problem and defining what we need: // the four eigenvectors of A nearest to 0.0. ARrcCompStdEig<T> prob(A.ncols(), 4, arcomplex<T>(0.0, 0.0)); // Finding an Arnoldi basis. while (!prob.ArnoldiBasisFound()) { // Calling ARPACK FORTRAN code. Almost all work needed to // find an Arnoldi basis is performed by TakeStep. prob.TakeStep(); if ((prob.GetIdo() == 1)||(prob.GetIdo() == -1)) { // Performing matrix-vector multiplication. // In shift and invert mode, w = OPv must be performed // whenever GetIdo is equal to 1 or -1. GetVector supplies // a pointer to the input vector, v, and PutVector a pointer // to the output vector, w. A.MultOPv(prob.GetVector(), prob.PutVector()); } } // Finding eigenvalues and eigenvectors. prob.FindEigenvectors(); // Printing solution. Solution(prob); } // Test. int main() { // Solving a single precision problem with n = 100. #ifndef __SUNPRO_CC Test((float)0.0); #endif // Solving a double precision problem with n = 100. Test((double)0.0); } // main
27.898438
72
0.659199
[ "vector" ]
e372a84395527cf00745a138c917ab1e91c8dc65
8,713
cpp
C++
podi_navigation_helpers/src/grid.cpp
CMU-TBD/IROS19-Human-Robot-Coupling
403137fad1f5f8c2d0291939cfa99594c8fbb70c
[ "MIT" ]
5
2019-12-02T14:43:14.000Z
2021-11-09T14:51:20.000Z
podi_navigation_helpers/src/grid.cpp
CMU-TBD/IROS19-Human-Robot-Coupling
403137fad1f5f8c2d0291939cfa99594c8fbb70c
[ "MIT" ]
null
null
null
podi_navigation_helpers/src/grid.cpp
CMU-TBD/IROS19-Human-Robot-Coupling
403137fad1f5f8c2d0291939cfa99594c8fbb70c
[ "MIT" ]
null
null
null
#include <podi_navigation_helpers/grid.h> #include <cmath> #include <tuple> #include <vector> #include <ros/console.h> namespace podi_navigation_helpers { // Initialize the grid Grid::Grid(std::vector<std::vector<unsigned int> > gridSizes, std::vector<unsigned int> distanceThresholds, std::vector<int> gridOrigin) { gridSizes_ = gridSizes; distanceThresholds_ = distanceThresholds; gridOrigin_ = gridOrigin; // Get the min dimensionality of elements of gridSize for (int i = 0; i < gridSizes_.size(); ++i) { if (i == 0) n_ = gridSizes_[i].size(); if (gridSizes_[i].size() < n_) n_ = gridSizes_[i].size(); } checkGridSizesAndDistanceThresholds(); } // Perform multiple checks to ensure that gridSizes_ and distanceThresholds_ // are valid, and notify the user if not void Grid::checkGridSizesAndDistanceThresholds() { // Must have at least one gridSize if (gridSizes_.size() < 1) { ROS_ERROR("Grid requires at least one grid size"); ROS_ERROR("This grid will always return the same point it is given"); return; } // gridSizes_ must have exactly one more element that distanceThresholds if (gridSizes_.size()-1 > distanceThresholds_.size()) { ROS_ERROR("Grid requires that gridSizes_.size()-1 == distanceThresholds_.size()"); ROS_ERROR("Truncating gridSizes_"); gridSizes_.resize(distanceThresholds_.size() + 1); } if (gridSizes_.size()-1 < distanceThresholds_.size()) { ROS_ERROR("Grid requires that gridSizes_.size()-1 == distanceThresholds_.size()"); ROS_ERROR("Truncating distanceThresholds_"); distanceThresholds_.resize(gridSizes_.size() - 1); } if (gridOrigin_.size() < n_) { ROS_ERROR("Grid requires that gridOrigin_.size()-1 == n_"); ROS_ERROR("Filling gridOirigin_ in with 0s"); for (int i = gridOrigin_.size(); i < n_; ++i) gridOrigin_.push_back(0); } if (gridOrigin_.size() > n_) { ROS_ERROR("Grid requires that gridOrigin_.size()-1 == n_"); ROS_ERROR("Truncating gridOirigin_"); gridOrigin_.resize(n_); } for (int i = 0; i < gridSizes_.size(); ++i) { // Every gridSize must have the same number of dimensions // Note that we define n as the min dimension of all gridSizes_ if (gridSizes_[i].size() > n_) { ROS_ERROR("Grid requires that every gridSize has the same dimensionality"); ROS_ERROR("Truncating gridSize[%d]", i); gridSizes_[i].resize(n_); } for (int k = 0; k < n_; ++k) { // If the first two elements of gridSize are <= 1, then we won't be able to properly subdivide if (k <= 1 && gridSizes_[i][k] <= 1) { ROS_ERROR("Grid requires that the first two elements of gridSize is > 1"); ROS_ERROR("Grid will have undefined and potentially error-inducing behavior"); } // Every element in a single gridSize must be positive if (gridSizes_[i][k] <= 0) { ROS_ERROR("Grid requires that every element of gridSize is positive"); ROS_ERROR("Grid will have undefined and potentially error-inducing behavior"); } // For only the first two elements of each gridSize: if (k < 2 && i > 0) { // Subsequent grid sizes of the same axis must not be larger than earlier ones if (gridSizes_[i-1][k] < gridSizes_[i][k]) { ROS_ERROR("Grid requires that for the first two dimensions, gridSizes_ along a single dimension be non-increasing"); ROS_ERROR("Grid will have undefined and potentially error-inducing behavior"); } // Subsequent grid sizes of the same axis must be factors of earlier ones if (gridSizes_[i-1][k] % gridSizes_[i][k] != 0) { ROS_ERROR("Grid requires that for the first two dimensions, gridSizes_ along a single dimension be factors of earlier ones"); ROS_ERROR("Grid will have undefined and potentially error-inducing behavior"); } } } if (i > 0) { // Every distanceThreshold must be > 0 if (distanceThresholds_[i-1] <= 1) { ROS_ERROR("Grid requires that every distanceThresholds_ is > 1"); ROS_ERROR("Grid will have undefined and potentially error-inducing behavior"); } // distanceThresholds_ must be non-increasing if (i < distanceThresholds_.size() && distanceThresholds_[i-1] < distanceThresholds_[i]) { ROS_ERROR("Grid requires the distanceThresholds_ be non-increasing"); ROS_ERROR("Grid will have undefined and potentially error-inducing behavior"); } // The distanceThreshold at index i-1 must be > the diameter of the gridSize // at index i-1. This guarentees that if the goal is in a cell, then // regardless of what the representative element of the cell is, // we will always subdivide that cell to the next level if possible. unsigned int diameter = distance(gridSizes_[i-1][0], gridSizes_[i-1][1]); if (distanceThresholds_[i-1] <= diameter) { ROS_ERROR("Grid requires every distanceThreshold is > the diameter of the gridSize at the same index"); ROS_ERROR("Grid will have undefined and potentially error-inducing behavior"); } } } } // Get goals, convert them to representative elements in the finest gridSize, // and store those as goals. Notw that although the goal can have more than two dimensions, // we only ever use the first two dimensions std::vector<std::vector<int> > Grid::setGoals(std::vector<std::vector<int> > goals) { if (gridSizes_.size() == 0) return goals; goalsRepresentativeElements_.clear(); for (int i = 0; i < goals.size(); ++i) { goalsRepresentativeElements_.push_back(getGridCellHelper(goals[i], gridSizes_[gridSizes_.size()-1])); } return goalsRepresentativeElements_; } // Get the minDist between a cell and the representative elements for goal(s) unsigned int Grid::distanceToGoal_(std::vector<int> cell) const { bool isMinDistSet = false; unsigned int minDist; for (int i = 0; i < goalsRepresentativeElements_.size(); ++i) { unsigned int dist = distance(goalsRepresentativeElements_[i][0]-cell[0], goalsRepresentativeElements_[i][1]-cell[1]); if (!isMinDistSet || dist < minDist) { minDist = dist; isMinDistSet = true; } } return minDist; } // Return approximately the middle element of the roundTo range that n is in. // Inclusivity/exclusiuvity it determined towards 0. i.e. if n < 0, the range // is inclusive of the upper bound, is n > 0 inclusive of lower bound, // exclusive of the other. The reason it is approximately the middle element // is due to int rounding errors. // NOTE: For 0, we arbitrarily choose to round up instead of down. int Grid::representativeValue(int val, int roundTo) const { // Round towards 0 int towardsZeroVal = (val/roundTo)*roundTo; // Round away from 0 int awayFromZeroVal = (val >= 0) ? towardsZeroVal + roundTo : towardsZeroVal - roundTo; // Average them to get the middle value return (towardsZeroVal+awayFromZeroVal)/2; } // Get the Euclidean distance from (0, 0) to (x, y), casting to an int unsigned int Grid::distance(int x, int y) const { return static_cast<unsigned int>(std::pow(std::pow(x, 2.0)+std::pow(y, 2.0), 0.5)); } // Returns the representative element of the cell of size cellSize that pos is // in (gridded with respect to the origin). Note that we only get up to n // dimensions, where n = pos.size(). Although ideally n = n_, users may desire // to call getGridCellHelper with a pos of less dimensions std::vector<int> Grid::getGridCellHelper(std::vector<int> pos, std::vector<unsigned int> cellSize) const { std::vector<int> retVal; unsigned int n = pos.size(); for (unsigned int i = 0; i < n; i++) { retVal.push_back(representativeValue(pos[i]-gridOrigin_[i], cellSize[i])+gridOrigin_[i]); } return retVal; } // Gets the representative element of the gridCell that pos is in, along with // the size of the grid it is in. Note that pos.size() can be < n_, but must // be >= 2 (in order to calculate Euclidean distance). std::tuple<std::vector<int>, std::vector<unsigned int> > Grid::getGridCell(std::vector<int> pos) const { if (gridSizes_.size() == 0) { std::vector<unsigned int> gridCell; return std::make_tuple(pos, gridCell); } unsigned int dist = 0; unsigned int currGridSizeIndex = 0; std::vector<int> cell; while (currGridSizeIndex == 0 || (currGridSizeIndex < gridSizes_.size() && dist < distanceThresholds_[currGridSizeIndex-1])) { cell = getGridCellHelper(pos, gridSizes_[currGridSizeIndex]); dist = distanceToGoal_(cell); currGridSizeIndex++; } return std::make_tuple(cell, gridSizes_[currGridSizeIndex-1]); } } //end namespace podi_navigation_helpers
45.145078
135
0.688511
[ "vector" ]
be77e53f3ac4d157195f598afc008bceeb5660b3
1,964
cpp
C++
Sandbox/src/Example2DLayer.cpp
Ali-Elganzory/Cajo
bfeac89f076f3ba4a7e8f6fa2b5ebefd5804ca2f
[ "MIT" ]
2
2020-06-28T02:16:54.000Z
2020-08-25T23:49:50.000Z
Sandbox/src/Example2DLayer.cpp
Ali-Elganzory/Cajo
bfeac89f076f3ba4a7e8f6fa2b5ebefd5804ca2f
[ "MIT" ]
null
null
null
Sandbox/src/Example2DLayer.cpp
Ali-Elganzory/Cajo
bfeac89f076f3ba4a7e8f6fa2b5ebefd5804ca2f
[ "MIT" ]
null
null
null
#include "Example2DLayer.h" #include <ImGui/imgui.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> Example2DLayer::Example2DLayer(const std::string& name) : Layer(name), m_CameraController((float)(1280.0 / 720.0), true) { } void Example2DLayer::OnAttach() { m_CheckboardTexture = Cajo::Texture2D::Create("assets/textures/checker_board.png"); m_AvarisLogoTexture = Cajo::Texture2D::Create("assets/textures/avaris_logo.png"); } void Example2DLayer::OnDetach() { } void Example2DLayer::OnUpdate(Cajo::Timestep ts) { CAJO_PROFILE_FUNCTION(); // OnUpdate { CAJO_PROFILE_SCOPE("Camera Update"); m_CameraController.OnUpdate(ts); } // Render { CAJO_PROFILE_SCOPE("Renderer Prep"); Cajo::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1 }); Cajo::RenderCommand::Clear(); } int i = 0; { CAJO_PROFILE_SCOPE("Renderer Draw 20 x 20 Quads"); Cajo::Renderer2D::BeginScene(m_CameraController.GetCamera()); for ( ; i < 5; ++i) for (int j = 0; j < 20; ++j) Cajo::Renderer2D::DrawQuad({ 1.5f * j, 1.5f * i, 0.0f }, { 1.0f, 1.0f }, { 0.8f, 0.2f, 0.4f, 1.0f }); for ( ; i < 10; ++i) for (int j = 0; j < 20; ++j) Cajo::Renderer2D::DrawQuad({ 1.5f * j, 1.5f * i, 0.0f }, { 1.0f, 1.0f }, m_CheckboardTexture); /*for (; i < 15; ++i) for (int j = 0; j < 20; ++j) Cajo::Renderer2D::DrawRotatedQuad({ 1.5f * j, 1.5f * i, 0.0f }, { 1.0f, 1.0f }, 0.785398f, { 0.8f, 0.2f, 0.4f, 1.0f }); for (; i < 20; ++i) for (int j = 0; j < 20; ++j) Cajo::Renderer2D::DrawRotatedQuad({ 1.5f * j, 1.5f * i, 0.0f }, { 1.0f, 1.0f }, 0.785398f, m_CheckboardTexture);*/ Cajo::Renderer2D::EndScene(); } } void Example2DLayer::OnImGuiRender() { { CAJO_PROFILE_SCOPE("OnImGuiRender"); ImGui::Begin("Checker Board Settings"); ImGui::ColorEdit4("Square Color", glm::value_ptr(m_SquareColor)); ImGui::End(); } } void Example2DLayer::OnEvent(Cajo::Event& event) { m_CameraController.OnEvent(event); }
25.179487
123
0.641039
[ "render" ]
be8fb7fce72f4d6551e70e470c43f40a0e418fd7
5,797
cpp
C++
salmon/vm/function.cpp
sdilts/Salmon
e378475a4093525425760bb15f4486e02a6f34ba
[ "MIT" ]
5
2020-02-10T10:28:51.000Z
2021-03-12T20:40:03.000Z
salmon/vm/function.cpp
sdilts/Salmon
e378475a4093525425760bb15f4486e02a6f34ba
[ "MIT" ]
null
null
null
salmon/vm/function.cpp
sdilts/Salmon
e378475a4093525425760bb15f4486e02a6f34ba
[ "MIT" ]
null
null
null
#include <sstream> #include <vm/function.hpp> #include <vm/vm.hpp> namespace salmon::vm { static std::vector<Symbol*> convert(const std::vector<vm_ptr<Symbol>> &list) { std::vector<Symbol*> arr; arr.reserve(list.size()); for(auto &item : list) { arr.push_back(item.get()); } return arr; } static std::optional<List*> convert(const std::optional<vm_ptr<List>> &source) { if(source) { return std::make_optional(source->get()); } else { return std::nullopt; } } VmFunction::VmFunction(const vm_ptr<Type> &type, const std::vector<vm_ptr<Symbol>> &lambda_list) : VmFunction(type, lambda_list, std::nullopt, std::nullopt, std::nullopt) {} VmFunction::VmFunction(const vm_ptr<Type> &type, const std::vector<vm_ptr<Symbol>> &lambda_list, std::optional<std::string> doc, std::optional<std::string> file, const std::optional<vm_ptr<List>> &source) : _lambda_list(convert(lambda_list)), fn_type{type.get()}, _documentation{doc}, _source_file{file}, _source_form{convert(source)} { salmon_check(std::holds_alternative<FunctionType>(type->type), "type must be a function type"); } VmFunction::~VmFunction() {} void VmFunction::get_roots(const std::function<void(AllocatedItem*)> &fn) const { fn(fn_type); for(Symbol *item : _lambda_list) { fn(item); } if(_source_form) { fn(_source_form.value()); } } const Type* VmFunction::type() const { return fn_type; } const std::optional<std::string> &VmFunction::documentation() const { return _documentation; } const std::optional<std::string> &VmFunction::source_file() const { return _source_file; } const std::optional<List*> &VmFunction::source_form() const { return _source_form; } InterfaceFunction::InterfaceFunction(const vm_ptr<Type> &type, const std::vector<vm_ptr<Symbol>> &lambda_list, std::optional<std::string> doc, std::optional<std::string> file) : VmFunction(type, lambda_list, doc, file, std::nullopt) { } InterfaceFunction::InterfaceFunction(const vm_ptr<Type> &type, const std::vector<vm_ptr<Symbol>> &lambda_list) : InterfaceFunction(type,lambda_list, std::nullopt, std::nullopt) { } static std::vector<Type*> get_signature(std::span<InternalBox> &args) { std::vector<Type*> ret; ret.reserve(args.size()); for(const auto &item : args) { ret.push_back(item.type); } return ret; } static std::vector<vm_ptr<Type>> vm_ptr_signature(VirtualMachine *vm, std::span<InternalBox> &args) { std::vector<vm_ptr<Type>> ret; ret.reserve(args.size()); for(const auto &item : args) { vm_ptr<Type> t = vm->mem_manager.make_vm_ptr(item.type); ret.push_back(t); } return ret; } Box InterfaceFunction::operator()(VirtualMachine *vm, std::span<InternalBox> args) { const std::vector<Type*> arg_types = get_signature(args); try { // TODO: fix this to not throw an exception if a value isn't found: VmFunction *actual = functions.at(arg_types); return (*actual)(vm, args); } catch(std::out_of_range *ex) { std::vector<vm_ptr<Type>> sig = vm_ptr_signature(vm, args); throw NoSuchFunction(sig); } } bool InterfaceFunction::add_impl(const vm_ptr<VmFunction> &fn) { auto other_fn_type = std::get<FunctionType>(fn->type()->type); if(fn->type()->concrete() && std::get<FunctionType>(fn_type->type).match(other_fn_type)) { const std::vector<Type*> arg_types = other_fn_type.arg_types(); functions.insert_or_assign(arg_types, fn.get()); return true; } else { return false; } } void InterfaceFunction::get_roots(const std::function<void(AllocatedItem*)> &inserter) const { functions.all_values([&inserter](Type* const&item) { inserter(item); }, [&inserter](VmFunction* const&item) { inserter(item); }); VmFunction::get_roots(inserter); } void InterfaceFunction::print_debug_info() const { std::cerr << "Interface function" << std::endl; } size_t InterfaceFunction::allocated_size() const { return sizeof(InterfaceFunction); } FunctionTable::FunctionTable() {} bool FunctionTable::add_function(const vm_ptr<Symbol> &name, const vm_ptr<VmFunction> &fn) { vm_ptr<VmFunction> fn_copy = fn; return add_function(name, std::move(fn_copy)); } bool FunctionTable::add_function(const vm_ptr<Symbol> &name, vm_ptr<VmFunction> &&fn) { auto interface_place = interfaces.find(name); if(interface_place != interfaces.end()) { return interface_place->second->add_impl(fn); } else { auto place = functions.lower_bound(name); if(place == functions.end() || *place->first != *name) { functions.emplace_hint(place,name, fn); return true; } else if(place->second->type()->equivalent_to(*fn->type())) { functions.insert_or_assign(name, fn); return true; } else { return false; } } } bool FunctionTable::new_interface(const vm_ptr<Symbol> &name, const vm_ptr<InterfaceFunction> &fn_type) { auto place = interfaces.lower_bound(name); if(place == interfaces.end() || *(place->first) != *name) { interfaces.emplace(name, fn_type); return true; } else if(place->second->type()->equivalent_to(*fn_type->type())) { // TODO: update the interface's documenation and other non-important fields return true; } else return false; } std::optional<vm_ptr<VmFunction>> FunctionTable::get_fn(const vm_ptr<Symbol> &name) const { auto interface_place = interfaces.find(name); if(interface_place != interfaces.end()) { return std::make_optional(static_cast<vm_ptr<VmFunction>>(interface_place->second)); } else if(auto fn_place = functions.find(name); fn_place != functions.end()) { return std::make_optional(static_cast<vm_ptr<VmFunction>>(fn_place->second)); } else return std::nullopt; } }
31
97
0.685527
[ "vector" ]
be900d14e6607708803c68e8b21447c071dea813
11,293
cpp
C++
src/caffe/SSD/rdetection_output_layer.cpp
xyt2008/frcnn
32a559e881cceeba09a90ff45ad4aae1dabf92a1
[ "BSD-2-Clause" ]
198
2018-01-07T13:44:29.000Z
2022-03-21T12:06:16.000Z
src/caffe/SSD/rdetection_output_layer.cpp
xyt2008/frcnn
32a559e881cceeba09a90ff45ad4aae1dabf92a1
[ "BSD-2-Clause" ]
18
2018-02-01T13:24:53.000Z
2021-04-26T10:51:47.000Z
src/caffe/SSD/rdetection_output_layer.cpp
xyt2008/frcnn
32a559e881cceeba09a90ff45ad4aae1dabf92a1
[ "BSD-2-Clause" ]
82
2018-01-06T14:21:43.000Z
2022-02-16T09:39:58.000Z
#include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <map> #include <string> #include <utility> #include <vector> #include "boost/filesystem.hpp" #include "boost/foreach.hpp" #include "rdetection_output_layer.hpp" //#include "caffe/layers/rdetection_output_layer.hpp" namespace caffe { template <typename Dtype> void RDetectionOutputLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const RDetectionOutputParameter& rdetection_output_param = this->layer_param_.rdetection_output_param(); CHECK(rdetection_output_param.has_num_classes()) << "Must specify num_classes"; CHECK(rdetection_output_param.has_prior_width()) << "Must specify prior_width"; CHECK(rdetection_output_param.has_prior_height()) << "Must specify prior_height"; regress_size_ = rdetection_output_param.regress_size(); regress_angle_ = rdetection_output_param.regress_angle(); if (!regress_size_) { prior_width_ = rdetection_output_param.prior_width(); prior_height_ = rdetection_output_param.prior_height(); } else { prior_width_ = -1; prior_height_ = -1; } num_param_ = 2; if(regress_size_) num_param_ += 2; if(regress_angle_) num_param_ ++; num_classes_ = rdetection_output_param.num_classes(); share_location_ = rdetection_output_param.share_location(); num_loc_classes_ = share_location_ ? 1 : num_classes_; background_label_id_ = rdetection_output_param.background_label_id(); code_type_ = rdetection_output_param.code_type(); variance_encoded_in_target_ = rdetection_output_param.variance_encoded_in_target(); keep_top_k_ = rdetection_output_param.keep_top_k(); confidence_threshold_ = rdetection_output_param.has_confidence_threshold() ? rdetection_output_param.confidence_threshold() : -FLT_MAX; // Parameters used in nms. nms_threshold_ = rdetection_output_param.nms_param().nms_threshold(); CHECK_GE(nms_threshold_, 0.) << "nms_threshold must be non negative."; eta_ = rdetection_output_param.nms_param().eta(); CHECK_GT(eta_, 0.); CHECK_LE(eta_, 1.); top_k_ = -1; if (rdetection_output_param.nms_param().has_top_k()) { top_k_ = rdetection_output_param.nms_param().top_k(); } const SaveOutputParameter& save_output_param = rdetection_output_param.save_output_param(); output_directory_ = save_output_param.output_directory(); if (!output_directory_.empty()) { if (boost::filesystem::is_directory(output_directory_)) { //boost::filesystem::remove_all(output_directory_); } if (!boost::filesystem::create_directories(output_directory_)) { LOG(WARNING) << "Failed to create directory: " << output_directory_; } } output_name_prefix_ = save_output_param.output_name_prefix(); need_save_ = output_directory_ == "" ? false : true; output_format_ = save_output_param.output_format(); name_count_ = 0; rbox_preds_.ReshapeLike(*(bottom[0])); if (!share_location_) { rbox_permute_.ReshapeLike(*(bottom[0])); } conf_permute_.ReshapeLike(*(bottom[1])); time0 = 0; time1 = 0; time2 = 0; time3 = 0; time4 = 0; time5 = 0; time6 = 0; } template <typename Dtype> void RDetectionOutputLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CHECK_EQ(bottom[0]->num(), bottom[1]->num()); if (rbox_preds_.num() != bottom[0]->num() || rbox_preds_.count(1) != bottom[0]->count(1)) { rbox_preds_.ReshapeLike(*(bottom[0])); } if (!share_location_ && (rbox_permute_.num() != bottom[0]->num() || rbox_permute_.count(1) != bottom[0]->count(1))) { rbox_permute_.ReshapeLike(*(bottom[0])); } if (conf_permute_.num() != bottom[1]->num() || conf_permute_.count(1) != bottom[1]->count(1)) { conf_permute_.ReshapeLike(*(bottom[1])); } num_priors_ = bottom[2]->height() / num_param_; CHECK_EQ(num_priors_ * num_loc_classes_ * num_param_, bottom[0]->channels()) << "Number of priors must match number of location predictions."; CHECK_EQ(num_priors_ * num_classes_, bottom[1]->channels()) << "Number of priors must match number of confidence predictions."; // num() and channels() are 1. vector<int> top_shape(2, 1); // Since the number of rboxes to be kept is unknown before nms, we manually // set it to (fake) 1. top_shape.push_back(1); // Each row is a 8 dimension vector, which stores // [image_id, label, confidence, xcenter, ycenter, angle, width, height] top_shape.push_back(1); top[0]->Reshape(top_shape); } template <typename Dtype> void RDetectionOutputLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* loc_data = bottom[0]->cpu_data(); const Dtype* conf_data = bottom[1]->cpu_data(); const Dtype* prior_data = bottom[2]->cpu_data(); const int num = bottom[0]->num(); // Retrieve all location predictions. vector<LabelRBox> all_loc_preds; GetLocPredictionsR(loc_data, num, num_priors_, num_loc_classes_, share_location_, regress_angle_, regress_size_, &all_loc_preds); // Retrieve all confidences. vector<map<int, vector<float> > > all_conf_scores; GetConfidenceScoresR(conf_data, num, num_priors_, num_classes_, &all_conf_scores); // Retrieve all prior rboxes. It is same within a batch since we assume all // images in a batch are of same dimension. vector<NormalizedRBox> prior_rboxes; vector<vector<float> > prior_variances; GetPriorRBoxes(prior_data, num_priors_, regress_angle_, regress_size_, prior_width_, prior_height_, &prior_rboxes, &prior_variances); // Decode all loc predictions to rboxes. vector<LabelRBox> all_decode_rboxes; const bool clip_rbox = false; DecodeRBoxesAll(all_loc_preds, prior_rboxes, prior_variances, num, share_location_, num_loc_classes_, background_label_id_, code_type_, variance_encoded_in_target_, clip_rbox, regress_size_, regress_angle_, &all_decode_rboxes); int num_kept = 0; vector<map<int, vector<int> > > all_indices; for (int i = 0; i < num; ++i) { const LabelRBox& decode_rboxes = all_decode_rboxes[i]; const map<int, vector<float> >& conf_scores = all_conf_scores[i]; map<int, vector<int> > indices; int num_det = 0; for (int c = 0; c < num_classes_; ++c) { if (c == background_label_id_) { // Ignore background class. continue; } if (conf_scores.find(c) == conf_scores.end()) { // Something bad happened if there are no predictions for current label. LOG(FATAL) << "Could not find confidence predictions for label " << c; } const vector<float>& scores = conf_scores.find(c)->second; int label = share_location_ ? -1 : c; if (decode_rboxes.find(label) == decode_rboxes.end()) { // Something bad happened if there are no predictions for current label. LOG(FATAL) << "Could not find location predictions for label " << label; continue; } const vector<NormalizedRBox>& rboxes = decode_rboxes.find(label)->second; ApplyNMSFastR(rboxes, scores, confidence_threshold_, nms_threshold_, eta_, top_k_, &(indices[c])); num_det += indices[c].size(); } if (keep_top_k_ > -1 && num_det > keep_top_k_) { vector<pair<float, pair<int, int> > > score_index_pairs; for (map<int, vector<int> >::iterator it = indices.begin(); it != indices.end(); ++it) { int label = it->first; const vector<int>& label_indices = it->second; if (conf_scores.find(label) == conf_scores.end()) { // Something bad happened for current label. LOG(FATAL) << "Could not find location predictions for " << label; continue; } const vector<float>& scores = conf_scores.find(label)->second; for (int j = 0; j < label_indices.size(); ++j) { int idx = label_indices[j]; CHECK_LT(idx, scores.size()); score_index_pairs.push_back(std::make_pair( scores[idx], std::make_pair(label, idx))); } } // Keep top k results per image. std::sort(score_index_pairs.begin(), score_index_pairs.end(), SortScorePairDescend<pair<int, int> >); score_index_pairs.resize(keep_top_k_); // Store the new indices. map<int, vector<int> > new_indices; for (int j = 0; j < score_index_pairs.size(); ++j) { int label = score_index_pairs[j].second.first; int idx = score_index_pairs[j].second.second; new_indices[label].push_back(idx); } all_indices.push_back(new_indices); num_kept += keep_top_k_; } else { all_indices.push_back(indices); num_kept += num_det; } } vector<int> top_shape(2, 1); top_shape.push_back(1); top_shape.push_back(1); Dtype* top_data; if (num_kept == 0) { LOG(INFO) << "Couldn't find any detections"; top[0]->Reshape(top_shape); top_data = top[0]->mutable_cpu_data(); //caffe_set<Dtype>(top[0]->count(), -1, top_data); // Generate fake results per image. top_data[0]=-1; } else { top[0]->Reshape(top_shape); top_data = top[0]->mutable_cpu_data(); top_data[0] = 0; } //int count = 0; boost::filesystem::path output_directory(output_directory_); for (int i = 0; i < num; ++i) { //OG(INFO) << "Num=" <<num; const map<int, vector<float> >& conf_scores = all_conf_scores[i]; const LabelRBox& decode_rboxes = all_decode_rboxes[i]; if (need_save_) ++name_count_; boost::filesystem::path file(output_name_prefix_ + boost::lexical_cast<string>(name_count_) + ".txt"); boost::filesystem::path out_file_name = output_directory / file; std::ofstream outfile; if (need_save_) { outfile.open(out_file_name.string().c_str(),std::ofstream::out); } for (map<int, vector<int> >::iterator it = all_indices[i].begin(); it != all_indices[i].end(); ++it) { int label = it->first; if (conf_scores.find(label) == conf_scores.end()) { // Something bad happened if there are no predictions for current label. LOG(FATAL) << "Could not find confidence predictions for " << label; continue; } //const vector<float>& scores = conf_scores.find(label)->second; int loc_label = share_location_ ? -1 : label; if (decode_rboxes.find(loc_label) == decode_rboxes.end()) { // Something bad happened if there are no predictions for current label. LOG(FATAL) << "Could not find location predictions for " << loc_label; continue; } const vector<NormalizedRBox>& rboxes = decode_rboxes.find(loc_label)->second; vector<int>& indices = it->second; for (int j = 0; j < indices.size(); ++j) { int idx = indices[j]; //top_data[count * 8] = i; //top_data[count * 8 + 1] = label; //top_data[count * 8 + 2] = scores[idx]; const NormalizedRBox& rbox = rboxes[idx]; //top_data[count * 8 + 3] = rbox.xcenter(); //top_data[count * 8 + 4] = rbox.ycenter(); //top_data[count * 8 + 5] = rbox.angle(); //top_data[count * 8 + 6] = rbox.width(); //top_data[count * 8 + 7] = rbox.height(); //++count; if (need_save_) { outfile << rbox.xcenter()*300 << " "<< rbox.ycenter()*300 << " " << rbox.width()*300 << " " << rbox.height()*300 << " " " " << label << " " << rbox.angle() << std::endl; } } } if (need_save_) { outfile.flush(); outfile.close(); } } } #ifdef CPU_ONLY STUB_GPU_FORWARD(RDetectionOutputLayer, Forward); #endif INSTANTIATE_CLASS(RDetectionOutputLayer); REGISTER_LAYER_CLASS(RDetectionOutput); } // namespace caffe
34.535168
104
0.693527
[ "vector" ]
be9ec3936d29aec238b8cfdb4f57c6c3f814845d
1,600
cpp
C++
src/question312.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
src/question312.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
src/question312.cpp
lxb1226/leetcode_cpp
554280de6be2a77e2fe41a5e77cdd0f884ac2e20
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int>> rec; vector<int> val; int solve(int left, int right){ if(left >= right - 1){ return 0; } if(rec[left][right] != -1){ return rec[left][right]; } for(int i = left + 1; i < right; i++){ int sum = val[left] * val[i] * val[right]; sum += solve(left, i) + solve(i, right); rec[left][right] = max(rec[left][right], sum); } return rec[left][right]; } int maxCoins(vector<int>& nums) { int n = nums.size(); val.resize(n + 2); for(int i = 1; i <= n; i++){ val[i] = nums[i - 1]; } val[0] = val[n - 1] = 1; rec.resize(n + 2, vector<int>(n + 2, -1)); return solve(0, n + 1); } // 法二:动态规划 // 令dp[i][j]表示填满区间(i, j)能得到的最多硬币数 int maxCoins(vector<int>& nums){ int n = nums.size(); vector<vector<int>> rec(n + 2, vector<int>(n + 2)); vector<int> val(n + 2); val[0] = val[n + 1] = 1; for(int i = 1; i <= n; i++){ val[i] = nums[i - 1]; } for(int i = n - 1; i >= 0; i--){ for(int j = i + 2; j <= n + 1; j++){ for(int k = i + 1; k < j; k++){ int sum = val[i] * val[k] * val[j]; sum += rec[i][k] + rec[k][j]; rec[i][j] = max(rec[i][j], sum); } } } return rec[0][n + 1]; } }; int main(){ }
25.396825
59
0.401875
[ "vector" ]
bea3b4f85ffce0b160eac46476528ff051d7c3ce
4,722
cpp
C++
src/openxc/message_set.cpp
redpesk-common/canbus-generator
b0b520e15d105f363ac66e471c9128b8f4b1f17f
[ "Apache-2.0" ]
null
null
null
src/openxc/message_set.cpp
redpesk-common/canbus-generator
b0b520e15d105f363ac66e471c9128b8f4b1f17f
[ "Apache-2.0" ]
null
null
null
src/openxc/message_set.cpp
redpesk-common/canbus-generator
b0b520e15d105f363ac66e471c9128b8f4b1f17f
[ "Apache-2.0" ]
1
2021-08-08T17:55:46.000Z
2021-08-08T17:55:46.000Z
#include <sstream> #include "message_set.hpp" namespace openxc { message_set::message_set() : name_{""} , version_{"1.0"} , bit_numbering_inverted_{false} , max_message_frequency_{0} , raw_can_mode_{can_bus_mode::off} , parents_{} , initializers_{} , loopers_{} , buses_{} , messages_{} , diagnostic_messages_{} , mappings_{} , extra_sources_{} , commands_{} { } std::string message_set::name() const { return name_; } std::string message_set::version() const { return version_; } bool message_set::bit_numbering_inverted() const { return bit_numbering_inverted_; } float message_set::max_message_frequency() const { return max_message_frequency_; } can_bus_mode message_set::raw_can_mode() const { return raw_can_mode_; } const std::vector<std::string>& message_set::parents() const { return parents_; } const std::vector<std::string>& message_set::initializers() const { return initializers_; } const std::vector<std::string>& message_set::loopers() const { return loopers_; } const std::map<std::string, can_bus>& message_set::buses() const { return buses_; } const std::vector<can_message>& message_set::messages() const { return messages_; } const std::vector<diagnostic_message>& message_set::diagnostic_messages() const { return diagnostic_messages_; } const std::vector<mapping>& message_set::mappings() const { return mappings_; } const std::vector<std::string>& message_set::extra_sources() const { return extra_sources_; } const std::vector<command>& message_set::commands() const { return commands_; } void message_set::from_json(const nlohmann::json& j) { if(!j.count("name")){ throw std::runtime_error("No name set in json file."); } name_ = j["name"].get<std::string>(); if(!j.count("version")){ throw std::runtime_error("No version set in json file."); } version_ = j["version"].get<std::string>(); bit_numbering_inverted_ = j.count("bit_numbering_inverted") ? j["bit_numbering_inverted"].get<bool>() : false; // TODO: should be true by default if database-backed. max_message_frequency_ = j.count("max_message_frequency") ? j["max_message_frequency"].get<float>() : 0.0f; raw_can_mode_ = j.count("raw_can_mode") ? j["raw_can_mode"].get<can_bus_mode>() : can_bus_mode::off; parents_ = j.count("parents") ? j["parents"].get<std::vector<std::string>>() : std::vector<std::string>(); initializers_ = j.count("initializers") ? j["initializers"].get<std::vector<std::string>>() : std::vector<std::string>(); loopers_ = j.count("loopers") ? j["loopers"].get<std::vector<std::string>>() : std::vector<std::string>(); buses_ = j.count("buses") ? j["buses"].get<std::map<std::string, can_bus>>() : std::map<std::string, can_bus>(); //messages_ = j.count("messages") ? j["messages"].get<std::map<std::string, can_message>>() : std::map<std::string, can_message>(); diagnostic_messages_ = j.count("diagnostic_messages") ? j["diagnostic_messages"].get<std::vector<diagnostic_message>>() : std::vector<diagnostic_message>(); mappings_ = j.count("mappings") ? j["mappings"].get<std::vector<mapping>>() : std::vector<mapping>(); extra_sources_ = j.count("extra_sources") ? j["extra_sources"].get<std::vector<std::string>>() : std::vector<std::string>(); commands_ = j.count("commands") ? j["commands"].get<std::vector<command>>() : std::vector<command>(); if (j.count("messages")) { std::map<std::string, nlohmann::json> messages = j["messages"]; for(const std::map<std::string, nlohmann::json>::value_type& m : messages) { can_message cm = m.second.get<can_message>(); std::string id = m.first; id = id.substr(0,id.find("#")); cm.id(id); messages_.push_back(cm); } } } nlohmann::json message_set::to_json() const { nlohmann::json j; j["name"] = name_; j["version"] = version_; j["bit_numbering_inverted"] = bit_numbering_inverted_; j["max_message_frequency"] = max_message_frequency_; j["raw_can_mode"] = raw_can_mode_; j["parents"] = parents_; j["initializers"] = initializers_; j["loopers"] = loopers_; j["buses"] = buses_; j["messages"] = messages_; j["diagnostic_messages"] = diagnostic_messages_; j["mappings"] = mappings_; j["extra_sources"] = extra_sources_; j["commands"] = commands_; return j; } void to_json(nlohmann::json& j, const message_set& p) { j = p.to_json(); } void from_json(const nlohmann::json& j, message_set& p) { p.from_json(j); } }
28.792683
168
0.646125
[ "vector" ]
bea5f834bc79137454c5a9493a24486e5af5d20c
2,517
cpp
C++
src/plugins/orbbec_skeleton/orbbec_skeleton_plugin.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
170
2015-10-20T08:31:16.000Z
2021-12-01T01:47:32.000Z
src/plugins/orbbec_skeleton/orbbec_skeleton_plugin.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
42
2015-10-20T23:20:17.000Z
2022-03-18T05:47:08.000Z
src/plugins/orbbec_skeleton/orbbec_skeleton_plugin.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
83
2015-10-22T14:53:00.000Z
2021-11-04T03:09:48.000Z
// This file is part of the Orbbec Astra SDK [https://orbbec3d.com] // Copyright (c) 2015 Orbbec 3D // // 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. // // Be excellent to each other. #include "orbbec_skeleton_plugin.hpp" #include <astra/astra.hpp> EXPORT_PLUGIN(orbbec::skeleton::skeleton_plugin); namespace orbbec { namespace skeleton { void skeleton_plugin::on_stream_added(astra_streamset_t setHandle, astra_stream_t streamHandle, astra_stream_desc_t desc) { if (desc.type != ASTRA_STREAM_DEPTH) return; // if new stream is not depth, we don't care. LOG_DEBUG("orbbec.skeleton.skeleton_plugin", "creating skeleton tracker for %p", streamHandle); skeletonTrackers_.push_back(astra::make_unique<skeleton_tracker>(pluginService(), setHandle, streamHandle)); } void skeleton_plugin::on_stream_removed(astra_streamset_t setHandle, astra_stream_t streamHandle, astra_stream_desc_t desc) { if (desc.type != ASTRA_STREAM_DEPTH) return; LOG_DEBUG("orbbec.skeleton.skeleton_plugin", "looking for skeleton tracker for %p", streamHandle); auto it = std::find_if(skeletonTrackers_.cbegin(), skeletonTrackers_.cend(), [&streamHandle] (const skeleton_trackerPtr& trackerPtr) { return trackerPtr->sourceStream() == streamHandle; }); LOG_DEBUG("orbbec.skeleton.skeleton_plugin", "destroying skeleton tracker for %p", streamHandle); if (it != skeletonTrackers_.cend()) { skeletonTrackers_.erase(it); } } }}
42.661017
106
0.586412
[ "3d" ]
beb1a5eef710686abe9bf82926652074e45a3aba
938
cpp
C++
src/dale/Operation/CloseScope/CloseScope.cpp
ChengCat/dale
4a764895611679cd1670d9a43ffdbee136661759
[ "BSD-3-Clause" ]
1,083
2015-03-18T09:42:49.000Z
2022-03-29T03:17:47.000Z
src/dale/Operation/CloseScope/CloseScope.cpp
ChengCat/dale
4a764895611679cd1670d9a43ffdbee136661759
[ "BSD-3-Clause" ]
195
2015-01-04T03:06:41.000Z
2022-03-18T18:16:27.000Z
src/dale/Operation/CloseScope/CloseScope.cpp
ChengCat/dale
4a764895611679cd1670d9a43ffdbee136661759
[ "BSD-3-Clause" ]
56
2015-03-18T20:02:13.000Z
2022-01-22T19:35:27.000Z
#include "CloseScope.h" #include <vector> #include "../Destruct/Destruct.h" namespace dale { namespace Operation { bool CloseScope(Context *ctx, Function *fn, llvm::BasicBlock *block, llvm::Value *skip_value, bool entire) { std::vector<Variable *> stack_vars; if (entire && fn->index) { ctx->ns()->getVarsAfterIndex(fn->index, &stack_vars); } else { ctx->ns()->getVariables(&stack_vars); } ParseResult element; element.block = block; for (std::vector<Variable *>::iterator b = stack_vars.begin(), e = stack_vars.end(); b != e; ++b) { if (skip_value && ((*b)->value == skip_value)) { continue; } element.set(element.block, (*b)->type, (*b)->value); element.do_not_destruct = false; Operation::Destruct(ctx, &element, &element, NULL, true); } return true; } } }
26.055556
68
0.558635
[ "vector" ]
beb2d371de1c6690aab51d6da8192a19083f3a5e
12,182
cc
C++
mysql-server/sql/dd/impl/types/foreign_key_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/sql/dd/impl/types/foreign_key_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/sql/dd/impl/types/foreign_key_impl.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2014, 2020, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sql/dd/impl/types/foreign_key_impl.h" #include <stddef.h> #include <sstream> #include <string> #include "my_rapidjson_size_t.h" // IWYU pragma: keep #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include "m_string.h" #include "my_inttypes.h" #include "my_sys.h" #include "mysqld_error.h" // ER_* #include "sql/dd/impl/raw/raw_record.h" // Raw_record #include "sql/dd/impl/sdi_impl.h" // sdi read/write functions #include "sql/dd/impl/tables/foreign_key_column_usage.h" // Foreign_key_column_usage #include "sql/dd/impl/tables/foreign_keys.h" // Foreign_keys #include "sql/dd/impl/transaction_impl.h" // Open_dictionary_tables_ctx #include "sql/dd/impl/types/foreign_key_element_impl.h" // Foreign_key_element_impl #include "sql/dd/impl/types/table_impl.h" // Table_impl #include "sql/dd/impl/types/weak_object_impl.h" #include "sql/dd/string_type.h" // dd::String_type #include "sql/dd/types/foreign_key_element.h" #include "sql/dd/types/index.h" // Index #include "sql/dd/types/object_table.h" #include "sql/dd/types/weak_object.h" #include "sql/error_handler.h" // Internal_error_handler #include "sql/sql_class.h" #include "sql/sql_error.h" using dd::tables::Foreign_key_column_usage; using dd::tables::Foreign_keys; namespace dd { class Sdi_rcontext; class Sdi_wcontext; /////////////////////////////////////////////////////////////////////////// // Foreign_key_impl implementation. /////////////////////////////////////////////////////////////////////////// Foreign_key_impl::Foreign_key_impl() : m_match_option(OPTION_NONE), m_update_rule(RULE_NO_ACTION), m_delete_rule(RULE_NO_ACTION), m_table(nullptr), m_elements() {} Foreign_key_impl::Foreign_key_impl(Table_impl *table) : m_match_option(OPTION_NONE), m_update_rule(RULE_NO_ACTION), m_delete_rule(RULE_NO_ACTION), m_table(table), m_elements() {} /////////////////////////////////////////////////////////////////////////// const Table &Foreign_key_impl::table() const { return *m_table; } Table &Foreign_key_impl::table() { return *m_table; } /////////////////////////////////////////////////////////////////////////// class Foreign_key_name_error_handler : public Internal_error_handler { const char *name; public: Foreign_key_name_error_handler(const char *name_arg) : name(name_arg) {} bool handle_condition(THD *, uint sql_errno, const char *, Sql_condition::enum_severity_level *, const char *) override { if (sql_errno == ER_DUP_ENTRY) { my_error(ER_FK_DUP_NAME, MYF(0), name); return true; } return false; } }; bool Foreign_key_impl::store(Open_dictionary_tables_ctx *otx) { /* Translate ER_DUP_ENTRY errors to the more user-friendly ER_FK_DUP_NAME. We should not report ER_DUP_ENTRY in any other cases (that would be a code bug). */ Foreign_key_name_error_handler error_handler(name().c_str()); otx->get_thd()->push_internal_handler(&error_handler); bool error = Weak_object_impl::store(otx); otx->get_thd()->pop_internal_handler(); return error; } /////////////////////////////////////////////////////////////////////////// bool Foreign_key_impl::validate() const { if (!m_table) { my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(), "No table object associated with this foreign key."); return true; } if (m_referenced_table_catalog_name.empty()) { my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(), "Referenced table catalog name is not set."); return true; } if (m_referenced_table_schema_name.empty()) { my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(), "Referenced table schema name is not set."); return true; } if (m_referenced_table_name.empty()) { my_error(ER_INVALID_DD_OBJECT, MYF(0), DD_table::instance().name().c_str(), "Referenced table name is not set."); return true; } return false; } /////////////////////////////////////////////////////////////////////////// bool Foreign_key_impl::restore_children(Open_dictionary_tables_ctx *otx) { return m_elements.restore_items( this, otx, otx->get_table<Foreign_key_element>(), Foreign_key_column_usage::create_key_by_foreign_key_id(this->id())); } /////////////////////////////////////////////////////////////////////////// bool Foreign_key_impl::store_children(Open_dictionary_tables_ctx *otx) { return m_elements.store_items(otx); } /////////////////////////////////////////////////////////////////////////// bool Foreign_key_impl::drop_children(Open_dictionary_tables_ctx *otx) const { return m_elements.drop_items( otx, otx->get_table<Foreign_key_element>(), Foreign_key_column_usage::create_key_by_foreign_key_id(this->id())); } /////////////////////////////////////////////////////////////////////////// bool Foreign_key_impl::restore_attributes(const Raw_record &r) { if (check_parent_consistency(m_table, r.read_ref_id(Foreign_keys::FIELD_TABLE_ID))) return true; restore_id(r, Foreign_keys::FIELD_ID); restore_name(r, Foreign_keys::FIELD_NAME); m_unique_constraint_name = r.read_str(Foreign_keys::FIELD_UNIQUE_CONSTRAINT_NAME, ""); m_match_option = (enum_match_option)r.read_int(Foreign_keys::FIELD_MATCH_OPTION); m_update_rule = (enum_rule)r.read_int(Foreign_keys::FIELD_UPDATE_RULE); m_delete_rule = (enum_rule)r.read_int(Foreign_keys::FIELD_DELETE_RULE); m_referenced_table_catalog_name = r.read_str(Foreign_keys::FIELD_REFERENCED_TABLE_CATALOG); m_referenced_table_schema_name = r.read_str(Foreign_keys::FIELD_REFERENCED_TABLE_SCHEMA); m_referenced_table_name = r.read_str(Foreign_keys::FIELD_REFERENCED_TABLE); return false; } /////////////////////////////////////////////////////////////////////////// bool Foreign_key_impl::store_attributes(Raw_record *r) { return store_id(r, Foreign_keys::FIELD_ID) || r->store(Foreign_keys::FIELD_SCHEMA_ID, m_table->schema_id()) || r->store(Foreign_keys::FIELD_TABLE_ID, m_table->id()) || store_name(r, Foreign_keys::FIELD_NAME) || r->store(Foreign_keys::FIELD_UNIQUE_CONSTRAINT_NAME, m_unique_constraint_name, m_unique_constraint_name.empty()) || r->store(Foreign_keys::FIELD_MATCH_OPTION, m_match_option) || r->store(Foreign_keys::FIELD_UPDATE_RULE, m_update_rule) || r->store(Foreign_keys::FIELD_DELETE_RULE, m_delete_rule) || r->store(Foreign_keys::FIELD_REFERENCED_TABLE_CATALOG, m_referenced_table_catalog_name) || r->store(Foreign_keys::FIELD_REFERENCED_TABLE_SCHEMA, m_referenced_table_schema_name) || r->store(Foreign_keys::FIELD_REFERENCED_TABLE, m_referenced_table_name); } /////////////////////////////////////////////////////////////////////////// static_assert(Foreign_keys::NUMBER_OF_FIELDS == 12, "Foreign_keys definition has changed, check if serialize() and " "deserialize() need to be updated!"); void Foreign_key_impl::serialize(Sdi_wcontext *wctx, Sdi_writer *w) const { w->StartObject(); Entity_object_impl::serialize(wctx, w); write_enum(w, m_match_option, STRING_WITH_LEN("match_option")); write_enum(w, m_update_rule, STRING_WITH_LEN("update_rule")); write_enum(w, m_delete_rule, STRING_WITH_LEN("delete_rule")); write(w, m_unique_constraint_name, STRING_WITH_LEN("unique_constraint_name")); write(w, m_referenced_table_catalog_name, STRING_WITH_LEN("referenced_table_catalog_name")); write(w, m_referenced_table_schema_name, STRING_WITH_LEN("referenced_table_schema_name")); write(w, m_referenced_table_name, STRING_WITH_LEN("referenced_table_name")); serialize_each(wctx, w, m_elements, STRING_WITH_LEN("elements")); w->EndObject(); } /////////////////////////////////////////////////////////////////////////// bool Foreign_key_impl::deserialize(Sdi_rcontext *rctx, const RJ_Value &val) { Entity_object_impl::deserialize(rctx, val); read_enum(&m_match_option, val, "match_option"); read_enum(&m_update_rule, val, "update_rule"); read_enum(&m_delete_rule, val, "delete_rule"); read(&m_unique_constraint_name, val, "unique_constraint_name"); read(&m_referenced_table_catalog_name, val, "referenced_table_catalog_name"); read(&m_referenced_table_schema_name, val, "referenced_table_schema_name"); read(&m_referenced_table_name, val, "referenced_table_name"); deserialize_each( rctx, [this]() { return add_element(); }, val, "elements"); return false; } /////////////////////////////////////////////////////////////////////////// /* purecov: begin inspected */ void Foreign_key_impl::debug_print(String_type &outb) const { dd::Stringstream_type ss; ss << "FOREIGN_KEY OBJECT: { " << "m_id: {OID: " << id() << "}; " << "m_name: " << name() << "; " << "m_unique_constraint_name: " << m_unique_constraint_name << "; " << "m_match_option: " << m_match_option << "; " << "m_update_rule: " << m_update_rule << "; " << "m_delete_rule: " << m_delete_rule << "; "; { for (const Foreign_key_element *e : elements()) { String_type ob; e->debug_print(ob); ss << ob; } } ss << " }"; outb = ss.str(); } /* purecov: end */ ///////////////////////////////////////////////////////////////////////// Foreign_key_element *Foreign_key_impl::add_element() { Foreign_key_element_impl *e = new (std::nothrow) Foreign_key_element_impl(this); m_elements.push_back(e); return e; } ///////////////////////////////////////////////////////////////////////// Foreign_key_impl::Foreign_key_impl(const Foreign_key_impl &src, Table_impl *parent) : Weak_object(src), Entity_object_impl(src), m_match_option(src.m_match_option), m_update_rule(src.m_update_rule), m_delete_rule(src.m_delete_rule), m_unique_constraint_name(src.m_unique_constraint_name), m_referenced_table_catalog_name(src.m_referenced_table_catalog_name), m_referenced_table_schema_name(src.m_referenced_table_schema_name), m_referenced_table_name(src.m_referenced_table_name), m_table(parent), m_elements() { m_elements.deep_copy(src.m_elements, this); } /////////////////////////////////////////////////////////////////////////// const Object_table &Foreign_key_impl::object_table() const { return DD_table::instance(); } /////////////////////////////////////////////////////////////////////////// void Foreign_key_impl::register_tables(Open_dictionary_tables_ctx *otx) { otx->add_table<Foreign_keys>(); otx->register_tables<Foreign_key_element>(); } /////////////////////////////////////////////////////////////////////////// } // namespace dd
36.473054
85
0.637662
[ "object" ]
bebe75de268b82493a5b4dbd9fa0f7aab42fcbc3
3,765
hpp
C++
framework/core/include/cnstream_common.hpp
chenxy1988/CNStream
cf2564b0fed892c62213a335c01559d3da18d91b
[ "Apache-2.0" ]
null
null
null
framework/core/include/cnstream_common.hpp
chenxy1988/CNStream
cf2564b0fed892c62213a335c01559d3da18d91b
[ "Apache-2.0" ]
null
null
null
framework/core/include/cnstream_common.hpp
chenxy1988/CNStream
cf2564b0fed892c62213a335c01559d3da18d91b
[ "Apache-2.0" ]
null
null
null
/************************************************************************* * Copyright (C) [2019] by Cambricon, Inc. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *************************************************************************/ #ifndef CNSTREAM_COMMON_HPP_ #define CNSTREAM_COMMON_HPP_ #include <limits.h> #include <pthread.h> #include <sys/prctl.h> #include <unistd.h> #include <atomic> #include <iomanip> #include <mutex> #include <sstream> #include <string> #include <vector> namespace cnstream { /** * @brief Flag to specify how bus watcher handle a single event. */ enum EventType { EVENT_INVALID, ///< An invalid event type. EVENT_ERROR, ///< An error event. EVENT_WARNING, ///< A warning event. EVENT_EOS, ///< An EOS event. EVENT_STOP, ///< Stops an event that is called by application layer usually. EVENT_STREAM_ERROR, ///< A stream error event. EVENT_TYPE_END ///< Reserved for your custom events. }; class NonCopyable { protected: NonCopyable() = default; ~NonCopyable() = default; private: NonCopyable(const NonCopyable& ) = delete; NonCopyable(NonCopyable&& ) = delete; NonCopyable& operator=(const NonCopyable& ) = delete; NonCopyable& operator=(NonCopyable&& ) = delete; }; /*helper functions */ static const pthread_t invalid_pthread_tid = static_cast<pthread_t>(-1); inline void SetThreadName(const std::string& name, pthread_t thread = invalid_pthread_tid) { /*name length should be less than 16 bytes */ if (name.empty() || name.size() >= 16) { return; } if (thread == invalid_pthread_tid) { prctl(PR_SET_NAME, name.c_str()); return; } pthread_setname_np(thread, name.c_str()); } inline std::string GetThreadName(pthread_t thread = invalid_pthread_tid) { char name[80]; if (thread == invalid_pthread_tid) { prctl(PR_GET_NAME, name); return name; } pthread_getname_np(thread, name, 80); return name; } /*pipeline capacities*/ constexpr size_t INVALID_MODULE_ID = (size_t)(-1); uint32_t GetMaxModuleNumber(); constexpr uint32_t INVALID_STREAM_IDX = (uint32_t)(-1); uint32_t GetMaxStreamNumber(); /** * Limit the resource for each stream, * there will be no more than "flow_depth" frames simultaneously. * Disabled by default. */ void SetFlowDepth(int flow_depth); int GetFlowDepth(); /*for force-remove-source*/ bool CheckStreamEosReached(const std::string &stream_id, bool sync = true); void SetStreamRemoved(const std::string &stream_id, bool value = true); bool IsStreamRemoved(const std::string &stream_id); /** * @brief Converts number to string * * @param number the number * @param width Padding with zero * @return Returns string */ template <typename T> std::string NumToFormatStr(const T &number, uint32_t width) { std::stringstream ss; ss << std::setw(width) << std::setfill('0') << number; return ss.str(); } } // namespace cnstream #endif // CNSTREAM_COMMON_HPP_
29.880952
92
0.689243
[ "vector" ]
bed611a71f0874b5a5f8dae39104312f0cef1372
808
hpp
C++
src/cppio/impl/basic_reactor.hpp
yamashi/cppio
a6fa39ccfd72361d0a8b11948a30db030de2ac33
[ "MIT" ]
4
2021-08-29T13:46:22.000Z
2021-11-14T20:27:30.000Z
src/cppio/impl/basic_reactor.hpp
yamashi/cppio
a6fa39ccfd72361d0a8b11948a30db030de2ac33
[ "MIT" ]
null
null
null
src/cppio/impl/basic_reactor.hpp
yamashi/cppio
a6fa39ccfd72361d0a8b11948a30db030de2ac33
[ "MIT" ]
null
null
null
#pragma once #include <cppio/impl/abstract_reactor.hpp> namespace cppio::impl { template<class T> struct basic_reactor : abstract_reactor { basic_reactor(size_t worker_count = 1); ~basic_reactor(); void run(); static basic_task* get_current_task(); static basic_reactor* get_current(); T& get_completion_port() { return m_completion_object; } private: void process_tasks(); T m_completion_object; std::atomic<bool> m_running; std::vector<std::jthread> m_runners; inline static thread_local basic_reactor* s_current_reactor; inline static thread_local basic_task* s_current_task; }; } #define BASIC_REACTOR_INL_DO #include <cppio/impl/basic_reactor.inl> #undef BASIC_REACTOR_INL_DO
23.085714
68
0.680693
[ "vector" ]
bee0b6a2e6149c98563e692e042e1c00d387ef90
10,833
cpp
C++
ext/tiny_gltf/rb_tiny_gltf_types.cpp
marnad7/tiny_gltf-ruby
cbb58dd3273a2fb3d5e561267074c0771e60e64c
[ "MIT" ]
1
2021-02-12T09:31:05.000Z
2021-02-12T09:31:05.000Z
ext/tiny_gltf/rb_tiny_gltf_types.cpp
marnad7/tiny_gltf-ruby
cbb58dd3273a2fb3d5e561267074c0771e60e64c
[ "MIT" ]
2
2022-03-15T21:21:09.000Z
2022-03-16T20:51:28.000Z
ext/tiny_gltf/rb_tiny_gltf_types.cpp
marnad7/tiny_gltf-ruby
cbb58dd3273a2fb3d5e561267074c0771e60e64c
[ "MIT" ]
3
2021-06-25T06:04:51.000Z
2021-08-13T19:42:22.000Z
#include "rb_tiny_gltf.h" /* void Model_free(void* data) { Model *obj = (Model *) data; delete obj; } size_t Model_size(const void* data) { return sizeof(Model); } static const rb_data_type_t T_Model = { .wrap_struct_name = "TinyGLTFModel", .function = { .dmark = NULL, .dfree = Model_free, .dsize = Model_size }, .parent = NULL, .data = NULL, .flags = RUBY_TYPED_FREE_IMMEDIATELY }; VALUE Model_alloc(VALUE klass) { return TypedData_Wrap_Struct(klass, &T_Model, new Model()); } VALUE Model_is_equal(VALUE self, VALUE other) { Model *a, *b; TypedData_Get_Struct(self, Model, &T_Model, a); TypedData_Get_Struct(other, Model, &T_Model, b); return (*a) == (*b) ? Qtrue : Qfalse; } */ #define DEFN_GLTF_TYPE(klass) \ void klass ## _free(void* data) { \ klass *obj = (klass *) data; \ delete obj; \ } \ \ size_t klass ## _size(const void* data) { \ return sizeof(klass); \ } \ \ const rb_data_type_t T_ ## klass = { \ .wrap_struct_name = "TinyGLTF" #klass, \ .function = { \ .dmark = NULL, \ .dfree = klass ## _free, \ .dsize = klass ## _size \ }, \ .parent = NULL, \ .data = NULL, \ .flags = RUBY_TYPED_FREE_IMMEDIATELY \ }; \ \ VALUE klass ## _alloc(VALUE k) { \ return TypedData_Wrap_Struct(k, &T_ ## klass, new klass()); \ } \ \ VALUE klass ## _is_equal(VALUE self, VALUE other) { \ klass *a, *b; \ TypedData_Get_Struct(self, klass, &T_ ## klass, a); \ TypedData_Get_Struct(other, klass, &T_ ## klass, b); \ return (*a) == (*b) ? Qtrue : Qfalse; \ } DEFN_GLTF_TYPE(Model); DEFN_GLTF_TYPE(Asset); DEFN_GLTF_TYPE(Accessor); DEFN_GLTF_TYPE(Animation); DEFN_GLTF_TYPE(AnimationChannel); DEFN_GLTF_TYPE(AnimationSampler); DEFN_GLTF_TYPE(Buffer); DEFN_GLTF_TYPE(BufferView); DEFN_GLTF_TYPE(Material); DEFN_GLTF_TYPE(Mesh); DEFN_GLTF_TYPE(Node); DEFN_GLTF_TYPE(Primitive); DEFN_GLTF_TYPE(Texture); DEFN_GLTF_TYPE(Image); DEFN_GLTF_TYPE(Skin); DEFN_GLTF_TYPE(Sampler); DEFN_GLTF_TYPE(Camera); DEFN_GLTF_TYPE(Scene); DEFN_GLTF_TYPE(Light); VALUE mode_to_sym(int mode) { switch(mode) { case TINYGLTF_MODE_POINTS: return ID2SYM(rb_intern("points")); case TINYGLTF_MODE_LINE: return ID2SYM(rb_intern("line")); case TINYGLTF_MODE_LINE_LOOP: return ID2SYM(rb_intern("line_loop")); case TINYGLTF_MODE_TRIANGLES: return ID2SYM(rb_intern("triangles")); case TINYGLTF_MODE_TRIANGLE_STRIP: return ID2SYM(rb_intern("triangle_strip")); case TINYGLTF_MODE_TRIANGLE_FAN: return ID2SYM(rb_intern("triangle_fan")); default: return ID2SYM(rb_intern("unknown")); } } VALUE component_type_to_sym(int type) { switch(type) { case TINYGLTF_COMPONENT_TYPE_BYTE: return ID2SYM(rb_intern("byte")); case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: return ID2SYM(rb_intern("ubyte")); case TINYGLTF_COMPONENT_TYPE_SHORT: return ID2SYM(rb_intern("short")); case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: return ID2SYM(rb_intern("ushort")); case TINYGLTF_COMPONENT_TYPE_INT: return ID2SYM(rb_intern("int")); case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: return ID2SYM(rb_intern("uint")); case TINYGLTF_COMPONENT_TYPE_FLOAT: return ID2SYM(rb_intern("float")); case TINYGLTF_COMPONENT_TYPE_DOUBLE: return ID2SYM(rb_intern("double")); default: return ID2SYM(rb_intern("unknown")); } } VALUE texture_filter_to_sym(int filter) { switch(filter) { case TINYGLTF_TEXTURE_FILTER_NEAREST: return ID2SYM(rb_intern("nearest")); case TINYGLTF_TEXTURE_FILTER_LINEAR: return ID2SYM(rb_intern("linear")); case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST: return ID2SYM(rb_intern("nearest_mipmap_nearest")); case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST: return ID2SYM(rb_intern("linear_mipmap_nearest")); case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR: return ID2SYM(rb_intern("nearest_mipmap_linear")); case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR: return ID2SYM(rb_intern("linear_mipmap_linear")); default: return ID2SYM(rb_intern("unknown")); } } VALUE texture_wrap_to_sym(int wrap) { switch(wrap) { case TINYGLTF_TEXTURE_WRAP_REPEAT: return ID2SYM(rb_intern("repeat")); case TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE: return ID2SYM(rb_intern("clamp_to_edge")); case TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT: return ID2SYM(rb_intern("mirrored_repeat")); default: return ID2SYM(rb_intern("unknown")); } } VALUE parameter_type_to_sym(int type) { switch(type) { case TINYGLTF_PARAMETER_TYPE_BYTE: return ID2SYM(rb_intern("byte")); case TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE: return ID2SYM(rb_intern("ubyte")); case TINYGLTF_PARAMETER_TYPE_SHORT: return ID2SYM(rb_intern("short")); case TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT: return ID2SYM(rb_intern("ushort")); case TINYGLTF_PARAMETER_TYPE_INT: return ID2SYM(rb_intern("int")); case TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT: return ID2SYM(rb_intern("uint")); case TINYGLTF_PARAMETER_TYPE_FLOAT: return ID2SYM(rb_intern("float")); case TINYGLTF_PARAMETER_TYPE_FLOAT_VEC2: return ID2SYM(rb_intern("float_vec2")); case TINYGLTF_PARAMETER_TYPE_FLOAT_VEC3: return ID2SYM(rb_intern("float_vec3")); case TINYGLTF_PARAMETER_TYPE_FLOAT_VEC4: return ID2SYM(rb_intern("float_vec4")); case TINYGLTF_PARAMETER_TYPE_INT_VEC2: return ID2SYM(rb_intern("int_vec2")); case TINYGLTF_PARAMETER_TYPE_INT_VEC3: return ID2SYM(rb_intern("int_vec3")); case TINYGLTF_PARAMETER_TYPE_INT_VEC4: return ID2SYM(rb_intern("int_vec4")); case TINYGLTF_PARAMETER_TYPE_BOOL: return ID2SYM(rb_intern("bool")); case TINYGLTF_PARAMETER_TYPE_BOOL_VEC2: return ID2SYM(rb_intern("bool_vec2")); case TINYGLTF_PARAMETER_TYPE_BOOL_VEC3: return ID2SYM(rb_intern("bool_vec3")); case TINYGLTF_PARAMETER_TYPE_BOOL_VEC4: return ID2SYM(rb_intern("bool_vec4")); case TINYGLTF_PARAMETER_TYPE_FLOAT_MAT2: return ID2SYM(rb_intern("float_mat2")); case TINYGLTF_PARAMETER_TYPE_FLOAT_MAT3: return ID2SYM(rb_intern("float_mat3")); case TINYGLTF_PARAMETER_TYPE_FLOAT_MAT4: return ID2SYM(rb_intern("float_mat4")); case TINYGLTF_PARAMETER_TYPE_SAMPLER_2D: return ID2SYM(rb_intern("sampler_2d")); default: return ID2SYM(rb_intern("unknown")); } } VALUE type_to_sym(int type) { switch(type) { case TINYGLTF_TYPE_VEC2: return ID2SYM(rb_intern("vec2")); case TINYGLTF_TYPE_VEC3: return ID2SYM(rb_intern("vec3")); case TINYGLTF_TYPE_VEC4: return ID2SYM(rb_intern("vec4")); case TINYGLTF_TYPE_MAT2: return ID2SYM(rb_intern("mat2")); case TINYGLTF_TYPE_MAT3: return ID2SYM(rb_intern("mat3")); case TINYGLTF_TYPE_MAT4: return ID2SYM(rb_intern("mat4")); case TINYGLTF_TYPE_SCALAR: return ID2SYM(rb_intern("scalar")); case TINYGLTF_TYPE_VECTOR: return ID2SYM(rb_intern("vector")); case TINYGLTF_TYPE_MATRIX: return ID2SYM(rb_intern("matrix")); default: return ID2SYM(rb_intern("unknown")); } } VALUE image_format_to_sym(int fmt) { switch(fmt) { case TINYGLTF_IMAGE_FORMAT_JPEG: return ID2SYM(rb_intern("jpeg")); case TINYGLTF_IMAGE_FORMAT_PNG: return ID2SYM(rb_intern("png")); case TINYGLTF_IMAGE_FORMAT_BMP: return ID2SYM(rb_intern("bmp")); case TINYGLTF_IMAGE_FORMAT_GIF: return ID2SYM(rb_intern("gif")); default: return ID2SYM(rb_intern("unknown")); } } VALUE texture_format_to_sym(int fmt) { switch(fmt) { case TINYGLTF_TEXTURE_FORMAT_ALPHA: return ID2SYM(rb_intern("alpha")); case TINYGLTF_TEXTURE_FORMAT_RGB: return ID2SYM(rb_intern("rgb")); case TINYGLTF_TEXTURE_FORMAT_RGBA: return ID2SYM(rb_intern("rgba")); case TINYGLTF_TEXTURE_FORMAT_LUMINANCE: return ID2SYM(rb_intern("luminance")); case TINYGLTF_TEXTURE_FORMAT_LUMINANCE_ALPHA: return ID2SYM(rb_intern("luminance_alpha")); default: return ID2SYM(rb_intern("unknown")); } } VALUE texture_target_to_sym(int tgt) { switch(tgt) { case TINYGLTF_TEXTURE_TARGET_TEXTURE2D: return ID2SYM(rb_intern("texture2d")); default: return ID2SYM(rb_intern("unknown")); } } VALUE texture_type_to_sym(int type) { switch(type) { case TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE: return ID2SYM(rb_intern("ubyte")); default: return ID2SYM(rb_intern("unknown")); } } VALUE target_to_sym(int tgt) { switch(tgt) { case TINYGLTF_TARGET_ARRAY_BUFFER: return ID2SYM(rb_intern("array_buffer")); case TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER: return ID2SYM(rb_intern("element_array_buffer")); default: return ID2SYM(rb_intern("unknown")); } } VALUE shader_type_to_sym(int type) { switch(type) { case TINYGLTF_SHADER_TYPE_VERTEX_SHADER: return ID2SYM(rb_intern("vertex_shader")); case TINYGLTF_SHADER_TYPE_FRAGMENT_SHADER: return ID2SYM(rb_intern("fragment_shader")); default: return ID2SYM(rb_intern("unknown")); } }
47.513158
108
0.604542
[ "mesh", "vector", "model" ]
beefd4ae21591d6ea845632088f664849d7eea80
2,962
cpp
C++
src/ingredientview.cpp
mattcaron/qbrew
c56cb00db69b6f13af6e19de136944c7a48d3207
[ "BSD-2-Clause" ]
1
2015-04-27T03:53:25.000Z
2015-04-27T03:53:25.000Z
src/ingredientview.cpp
mattcaron/qbrew
c56cb00db69b6f13af6e19de136944c7a48d3207
[ "BSD-2-Clause" ]
null
null
null
src/ingredientview.cpp
mattcaron/qbrew
c56cb00db69b6f13af6e19de136944c7a48d3207
[ "BSD-2-Clause" ]
null
null
null
/*************************************************************************** ingredientview.cpp ------------------- Ingredient view ------------------- Copyright 2006-2008, David Johnson Please see the header file for copyright and license information ***************************************************************************/ #include <QAction> #include <QContextMenuEvent> #include <QHeaderView> #include <QMenu> #include "ingredientview.h" /////////////////////////////////////////////////////////////////////////////// // IngredientView // /////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // IngredientView() // ------------ // Constructor IngredientView::IngredientView(QWidget *parent) : QTableView(parent), addaction_(0), removeaction_(0) { setSortingEnabled(true); // create context menu actions addaction_ = new QAction(tr("&Add Ingredient"), this); addaction_->setShortcut(QKeySequence(tr("Ctrl+Insert"))); addaction_->setStatusTip(tr("Add a new ingredient")); connect(addaction_, SIGNAL(triggered()), this, SLOT(addIngredient())); removeaction_ = new QAction(tr("&Remove Ingredient"), this); removeaction_->setShortcut(QKeySequence(tr("Ctrl+Delete"))); removeaction_->setStatusTip(tr("Remove selected ingredient")); connect(removeaction_, SIGNAL(triggered()), this, SLOT(removeIngredient())); clearaction_ = new QAction(tr("&Clear Selection"), this); clearaction_->setShortcut(QKeySequence(tr("Escape"))); clearaction_->setStatusTip(tr("Clear selection")); connect(clearaction_, SIGNAL(triggered()), this, SLOT(clearSelection())); addAction(addaction_); addAction(removeaction_); addAction(clearaction_); } IngredientView::~IngredientView() { } ////////////////////////////////////////////////////////////////////////////// // contextMenuEvent() // ------------------ // Create and show context menu void IngredientView::contextMenuEvent(QContextMenuEvent *event) { QMenu menu(this); menu.addAction(addaction_); menu.addAction(removeaction_); menu.addSeparator(); menu.addAction(clearaction_); menu.exec(event->globalPos()); } ////////////////////////////////////////////////////////////////////////////// // addIngredient() // --------------- // Add a new blank ingredient void IngredientView::addIngredient() { model()->insertRows(currentIndex().row(), 1, QModelIndex()); } ////////////////////////////////////////////////////////////////////////////// // removeIngredient() // ------------------ // Remove the selected ingredient void IngredientView::removeIngredient() { // can only remove valid indexes if (currentIndex().isValid()) { model()->removeRows(currentIndex().row(), 1, QModelIndex()); clearSelection(); } }
31.510638
80
0.51688
[ "model" ]
bef233b6573046d49fb6110df336a1b0481ec066
1,907
cpp
C++
TDEngine2/source/graphics/CGraphicsLayersInfo.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-15T01:14:15.000Z
2019-07-15T01:14:15.000Z
TDEngine2/source/graphics/CGraphicsLayersInfo.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
76
2018-10-27T16:59:36.000Z
2022-03-30T17:40:39.000Z
TDEngine2/source/graphics/CGraphicsLayersInfo.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-29T02:02:08.000Z
2019-07-29T02:02:08.000Z
#include "../../include/graphics/CGraphicsLayersInfo.h" #include <climits> #include <cmath> namespace TDEngine2 { CGraphicsLayersInfo::CGraphicsLayersInfo(): CBaseObject() { } E_RESULT_CODE CGraphicsLayersInfo::Init() { if (mIsInitialized) { return RC_FAIL; } mIsInitialized = true; return RC_OK; } E_RESULT_CODE CGraphicsLayersInfo::Free() { if (!mIsInitialized) { return RC_FAIL; } mIsInitialized = false; delete this; return RC_OK; } E_RESULT_CODE CGraphicsLayersInfo::AddLayer(F32 depthValue, const C8* layerName) { /// if there is no any layer within the vector use -infinity as the most left value F32 prevLayerDepthValue = mGraphicsLayers.empty() ? -(std::numeric_limits<F32>::infinity)() : std::get<F32>(mGraphicsLayers.back()); if (mGraphicsLayers.empty()) { prevLayerDepthValue = -(std::numeric_limits<F32>::infinity)(); /// a left bound } if (depthValue < prevLayerDepthValue) /// all layers should be defined from smallest values to highest one { return RC_INVALID_ARGS; } mGraphicsLayers.emplace_back(depthValue, (layerName ? layerName : "GraphicsLayer" + mGraphicsLayers.size())); return RC_OK; } U16 CGraphicsLayersInfo::GetLayerIndex(F32 depthValue) const { if (mGraphicsLayers.empty()) { return 0; /// there is the only one layer, so return it } U16 layerId = 0; F32 rightLayerBorderValue = 0.0f; for (TGraphicsLayersArray::const_iterator iter = mGraphicsLayers.cbegin(); iter != mGraphicsLayers.cend(); ++iter, ++layerId) { rightLayerBorderValue = std::get<F32>(*iter); if (depthValue < rightLayerBorderValue || fabs(depthValue - rightLayerBorderValue) < FloatEpsilon) { return layerId; } } return layerId; } IGraphicsLayersInfo* CreateGraphicsLayersInfo(E_RESULT_CODE& result) { return CREATE_IMPL(IGraphicsLayersInfo, CGraphicsLayersInfo, result); } }
21.670455
135
0.712113
[ "vector" ]
bef29675161d3559b0b8e0278f151a6c506fb660
15,101
cpp
C++
iphoneos/AngryMetal/AngryKit/player_animation_system.cpp
ivan-ushakov/AngryMetal
0e358be545efe50fbe83664676a9f1fcd03b8825
[ "Apache-2.0" ]
null
null
null
iphoneos/AngryMetal/AngryKit/player_animation_system.cpp
ivan-ushakov/AngryMetal
0e358be545efe50fbe83664676a9f1fcd03b8825
[ "Apache-2.0" ]
null
null
null
iphoneos/AngryMetal/AngryKit/player_animation_system.cpp
ivan-ushakov/AngryMetal
0e358be545efe50fbe83664676a9f1fcd03b8825
[ "Apache-2.0" ]
null
null
null
// // player_animation_system.cpp // AngryKit // // Created by  Ivan Ushakov on 25.05.2021. // #include "player_animation_system.hpp" #include <simd/simd.h> #include <stdexcept> #include <string> #include <unordered_map> #include "animation_component.hpp" #include "health_component.hpp" #include "mesh_component.hpp" #include "movement_component.hpp" #include "scene.hpp" using namespace angry; aiMatrix4x4 zero_ai_mat() { aiMatrix4x4 m; for (int i = 0; i < 4; i++) { m[i][i] = 0.0f; } return m; } void scaled_add(aiMatrix4x4& m1, const float scale, const aiMatrix4x4& m2) { m1.a1 += scale * m2.a1; m1.a2 += scale * m2.a2; m1.a3 += scale * m2.a3; m1.a4 += scale * m2.a4; m1.b1 += scale * m2.b1; m1.b2 += scale * m2.b2; m1.b3 += scale * m2.b3; m1.b4 += scale * m2.b4; m1.c1 += scale * m2.c1; m1.c2 += scale * m2.c2; m1.c3 += scale * m2.c3; m1.c4 += scale * m2.c4; m1.d1 += scale * m2.d1; m1.d2 += scale * m2.d2; m1.d3 += scale * m2.d3; m1.d4 += scale * m2.d4; } using TransformMap = std::unordered_map<std::string, aiMatrix4x4>; struct Processor { BufferManagerInterface& buffer_manager; Scene& scene; AnimationComponent& animation_component; Processor(BufferManagerInterface& buffer_manager, Scene& scene, AnimationComponent& animation_component) : buffer_manager(buffer_manager), scene(scene), animation_component(animation_component) { } void set_mesh_vertex_buffer(MeshComponent& mesh_component, TransformMap& node_transform_map) { auto source = mesh_component.source_mesh; std::vector<aiMatrix4x4> bone_anim_transform(source->mNumVertices, zero_ai_mat()); for (unsigned bone_index = 0; bone_index < source->mNumBones; bone_index++) { aiBone* bone = source->mBones[bone_index]; const std::string bone_name = bone->mName.C_Str(); const aiMatrix4x4 node_transform = animation_component.global_inv * node_transform_map[bone_name] * bone->mOffsetMatrix; for (unsigned weight_index = 0; weight_index < bone->mNumWeights; weight_index++) { aiVertexWeight w = bone->mWeights[weight_index]; scaled_add(bone_anim_transform[w.mVertexId], w.mWeight, node_transform); } } aiMatrix4x4 node_anim_transform; if (source->mNumBones == 0) { std::vector<aiNode*> mesh_nodes; std::function<void(aiNode*)> r; r = [source, this, &mesh_nodes, &r](aiNode* n) { for (unsigned xx = 0; xx < n->mNumMeshes; xx++) { aiMesh* tmp_mesh = get_mesh(n->mMeshes[xx]).source_mesh; if (tmp_mesh == source) { mesh_nodes.push_back(n); } } for (unsigned xx = 0; xx < n->mNumChildren; xx++) { r(n->mChildren[xx]); } }; r(animation_component.root_node); for (auto* mesh_node : mesh_nodes) { node_anim_transform *= node_transform_map[std::string(mesh_node->mName.data)]; } } const auto position_index = mesh_component.mesh.vertex_buffer[VertexAttribute::position]; auto position = buffer_manager.get_buffer_view<float>(position_index).data; for (unsigned int i = 0; i < source->mNumVertices; i++) { aiVector3D v = (source->mNumBones > 0 ? bone_anim_transform[i] : node_anim_transform) * source->mVertices[i]; position[3 * i] = v.x; position[3 * i + 1] = v.y; position[3 * i + 2] = v.z; } } void process_mesh(MeshComponent& mesh_component, TransformMap& node_transform_map) { auto source = mesh_component.source_mesh; if (mesh_component.mesh.vertex_buffer.empty()) { const auto vertex_count = source->mNumVertices; { const auto index = buffer_manager.create_buffer(vertex_count * 3 * sizeof(float)); mesh_component.mesh.vertex_buffer[VertexAttribute::position] = index; } const auto normal_index = buffer_manager.create_buffer(vertex_count * 3 * sizeof(float)); mesh_component.mesh.vertex_buffer[VertexAttribute::normal] = normal_index; const auto uv_index = buffer_manager.create_buffer(vertex_count * 2 * sizeof(float)); mesh_component.mesh.vertex_buffer[VertexAttribute::uv] = uv_index; auto normal = buffer_manager.get_buffer_view<float>(normal_index).data; auto uv = buffer_manager.get_buffer_view<float>(uv_index).data; for (unsigned int i = 0; i < source->mNumVertices; i++) { normal[3 * i] = source->mNormals[i].x; normal[3 * i + 1] = source->mNormals[i].y; normal[3 * i + 2] = source->mNormals[i].z; if (source->mTextureCoords[0]) { uv[2 * i] = source->mTextureCoords[0][i].x; uv[2 * i + 1] = source->mTextureCoords[0][i].y; } else { uv[2 * i] = 0; uv[2 * i + 1] = 0; } } mesh_component.mesh.vertex_count = vertex_count; } if (!mesh_component.mesh.index_buffer) { const auto index_count = 3 * source->mNumFaces; const auto index = buffer_manager.create_buffer(index_count * sizeof(uint32_t)); mesh_component.mesh.index_buffer = index; mesh_component.mesh.index_count = index_count; auto view = buffer_manager.get_buffer_view<uint32_t>(index); size_t p = 0; for (unsigned int i = 0; i < source->mNumFaces; i++) { aiFace& face = source->mFaces[i]; for (unsigned int j = 0; j < face.mNumIndices; j++) { const unsigned int vertex_index = face.mIndices[j]; view.data[p++] = vertex_index; } } } set_mesh_vertex_buffer(mesh_component, node_transform_map); } MeshComponent& get_mesh(unsigned int mesh_index) { switch (mesh_index) { case 0: { return scene.get_registry().get<MeshComponent>(scene.get_player()); } case 1: { return scene.get_registry().get<MeshComponent>(scene.get_gun()); } default: { throw std::runtime_error(""); } } } void process_node(aiNode* node, TransformMap& transform_map) { for (unsigned int i = 0; i < node->mNumMeshes; i++) { process_mesh(get_mesh(node->mMeshes[i]), transform_map); } for (unsigned int i = 0; i < node->mNumChildren; i++) { aiNode* child_node = node->mChildren[i]; process_node(child_node, transform_map); } } }; void append_node_points(float target_anim_ticks, aiAnimation* anim, aiMatrix4x4 transform, aiNode* node, TransformMap& node_transform_map) { aiMatrix4x4 anim_transform; bool anim_found = false; for (unsigned channel_index = 0; channel_index < anim->mNumChannels; channel_index++) { const aiNodeAnim* node_anim = anim->mChannels[channel_index]; if (node_anim->mNodeName != node->mName) { continue; } anim_found = true; // rotation animation for (unsigned x = 0; x < node_anim->mNumRotationKeys; ++x) { aiQuatKey k = node_anim->mRotationKeys[x]; // TODO see b8bf1eac041f0bbb406019a28f310509dad51b86 in https://github.com/assimp/assimp const float t = k.mTime / 1000.0f * anim->mTicksPerSecond; if (t >= target_anim_ticks) { anim_transform = aiMatrix4x4(k.mValue.GetMatrix()) * anim_transform; break; } } // position animation for (unsigned x = 0; x < node_anim->mNumPositionKeys; ++x) { aiVectorKey k = node_anim->mPositionKeys[x]; // TODO see b8bf1eac041f0bbb406019a28f310509dad51b86 in https://github.com/assimp/assimp const float t = k.mTime / 1000.0f * anim->mTicksPerSecond; if (t >= target_anim_ticks) { if (std::abs(k.mTime - target_anim_ticks) > 2.0f) { // TODO why block is empty? } anim_transform.a4 += k.mValue.x; anim_transform.b4 += k.mValue.y; anim_transform.c4 += k.mValue.z; break; } } } transform *= anim_found ? anim_transform : node->mTransformation; node_transform_map.emplace(node->mName.C_Str(), transform); for (unsigned i = 0; i < node->mNumChildren; ++i) { append_node_points(target_anim_ticks, anim, transform, node->mChildren[i], node_transform_map); } } PlayerAnimationSystem::PlayerAnimationSystem(BufferManagerInterface& buffer_manager) : _buffer_manager(buffer_manager) { } void PlayerAnimationSystem::update(Scene& scene, float time) { auto player_entity = scene.get_player(); auto& animation_component = scene.get_registry().get<AnimationComponent>(player_entity); auto& movement_component = scene.get_registry().get<MovementComponent>(player_entity); auto& health_component = scene.get_registry().get<HealthComponent>(player_entity); if (health_component.health == 0 && animation_component.death_time < 0) { animation_component.death_time = time; } aiAnimation* animation = animation_component.animation; aiNode* root_node = animation_component.root_node; TransformMap merged_node_transform_map; struct AnimationData { float weight; float min_ticks; float max_ticks; float tick_offset; float* opt_anim_start = nullptr; }; const auto process_anim = [&merged_node_transform_map, root_node, animation, time](const AnimationData& data) { if (data.weight == 0.0f) { return; } const float tick_range = data.max_ticks - data.min_ticks; float target_anim_ticks = data.opt_anim_start ? std::min((float)((time - *data.opt_anim_start) * animation->mTicksPerSecond + data.tick_offset), tick_range) : fmod(time * animation->mTicksPerSecond + data.tick_offset, tick_range); target_anim_ticks += data.min_ticks; if (target_anim_ticks < (data.min_ticks - 0.01f) || target_anim_ticks > (data.max_ticks + 0.01f)) { throw std::runtime_error("PlayerAnimationSystem::animate()"); } TransformMap local_node_transform_map; append_node_points(target_anim_ticks, animation, aiMatrix4x4(), root_node, local_node_transform_map); for (const auto& t : local_node_transform_map) { if (merged_node_transform_map.find(t.first) == merged_node_transform_map.end()) { merged_node_transform_map[t.first] = zero_ai_mat(); } // TODO += ? merged_node_transform_map[t.first] = merged_node_transform_map[t.first] + t.second * data.weight; } }; const bool is_player_moving = simd_length(movement_component.direction) > 0.1f; float theta_delta = 0; const simd_float2 movement_anim{sin(theta_delta), cos(theta_delta)}; const float delta_time = time - animation_component.last_anim_time; animation_component.last_anim_time = time; animation_component.prev_idle_weight = std::max(0.0f, animation_component.prev_idle_weight - delta_time / animation_component.transition_time); animation_component.prev_right_weight = std::max(0.0f, animation_component.prev_right_weight - delta_time / animation_component.transition_time); animation_component.prev_left_weight = std::max(0.0f, animation_component.prev_left_weight - delta_time / animation_component.transition_time); animation_component.prev_forward_weight = std::max(0.0f, animation_component.prev_forward_weight - delta_time / animation_component.transition_time); animation_component.prev_back_weight = std::max(0.0f, animation_component.prev_back_weight - delta_time / animation_component.transition_time); const bool is_dead = animation_component.death_time >= 0.0f; float death_weight = is_dead ? 1.0f : 0.0f; float idle_weight = animation_component.prev_idle_weight + ((is_dead || is_player_moving) ? 0.0f : 1.0f); float right_weight = animation_component.prev_right_weight + (is_player_moving ? std::max(0.0f, -movement_anim.x) : 0.0f); float forward_weight = animation_component.prev_forward_weight + (is_player_moving ? std::max(0.0f, movement_anim.y) : 0.0f); float back_weight = animation_component.prev_back_weight + (is_player_moving ? std::max(0.0f, -movement_anim.y) : 0.0f); float left_weight = animation_component.prev_left_weight + (is_player_moving ? std::max(0.0f, movement_anim.x) : 0.0f); const float weight_sum = death_weight + idle_weight + right_weight + forward_weight + back_weight + left_weight; death_weight /= weight_sum; idle_weight /= weight_sum; right_weight /= weight_sum; forward_weight /= weight_sum; back_weight /= weight_sum; left_weight /= weight_sum; animation_component.prev_idle_weight = std::max(animation_component.prev_idle_weight, idle_weight); animation_component.prev_right_weight = std::max(animation_component.prev_right_weight, right_weight); animation_component.prev_left_weight = std::max(animation_component.prev_left_weight, left_weight); animation_component.prev_forward_weight = std::max(animation_component.prev_forward_weight, forward_weight); animation_component.prev_back_weight = std::max(animation_component.prev_back_weight, back_weight); if (abs(right_weight + forward_weight + back_weight + left_weight + idle_weight + death_weight - 1.0f) > 0.001f) { throw std::runtime_error("PlayerAnimationSystem::animate()"); } process_anim({death_weight, 234.0f, 293.0f, 0.0f, &animation_component.death_time}); process_anim({idle_weight, 55.0f, 130.0f, 0.0f}); const float movement_anim_dur = 20.0f; process_anim({forward_weight, 134.0f, 134.0f + movement_anim_dur, 0.0f}); process_anim({right_weight, 184.0f, 184.0f + movement_anim_dur, 10.0f}); process_anim({back_weight, 159.0f, 159.0f + movement_anim_dur, 10.0f}); process_anim({left_weight, 209.0f, 209.0f + movement_anim_dur, 0.0f}); Processor processor(_buffer_manager, scene, animation_component); processor.process_node(root_node, merged_node_transform_map); }
38.522959
164
0.625521
[ "mesh", "vector", "transform" ]
befff531799e8cff3f880caaf674fdc9635a0c57
876
cpp
C++
LeetCode/daily/5716. 好因子的最大数目.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
1
2020-03-26T13:40:52.000Z
2020-03-26T13:40:52.000Z
LeetCode/daily/5716. 好因子的最大数目.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
null
null
null
LeetCode/daily/5716. 好因子的最大数目.cpp
xmmmmmovo/MyAlgorithmSolutions
f5198d438f36f41cc4f72d53bb71d474365fa80d
[ "MIT" ]
null
null
null
/** * author: xmmmmmovo * generation time: 2021/03/28 * filename: 5716. 好因子的最大数目.cpp * language & build version : C 11 & C++ 17 */ #include <algorithm> #include <iostream> #include <numeric> #include <stack> #include <string> #include <vector> using namespace std; using ll = long long; const int M = 1e9 + 7; ll qmi(ll a, ll k, int p) { ll res = 1; while (k) { if (k & 1) res = res * a % p; k >>= 1; a = a * a % p; } return res; } class Solution { public: int maxNiceDivisors(int primeFactors) { if (primeFactors <= 3) return primeFactors; if (primeFactors % 3 == 0) return qmi(3, primeFactors / 3, M); if (primeFactors % 3 == 1) return qmi(3, (primeFactors - 4) / 3, M) * 4 % M; return qmi(3, (primeFactors - 2) / 3, M) * 2 % M; } };
20.372093
61
0.528539
[ "vector" ]
8300bb2b88a1c72d35ee0ae2a59fca9dfc62320a
1,963
cpp
C++
src/Collisions/ObstacleCollisionDealer.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
src/Collisions/ObstacleCollisionDealer.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
src/Collisions/ObstacleCollisionDealer.cpp
lucashflores/jogo-tecprog
21b114f21b933247a321e17905338a4f51620d2a
[ "MIT" ]
null
null
null
#include "Collisions/ObstacleCollisionDealer.h" using namespace Collisions; ObstacleCollisionDealer::ObstacleCollisionDealer() { } ObstacleCollisionDealer::~ObstacleCollisionDealer() { } void ObstacleCollisionDealer::oilTileCollision(Entities::Entity *pE1, Entities::Entity *pE2, Coordinates::Vector<float> collision) { Entities::Character* pC1 = static_cast<Entities::Character*>(pE1); pC1->setIsOnGround(true); pC1->setVelocityCoefficient(1.f); } void ObstacleCollisionDealer::signCollision(Entities::Entity *pE1, Entities::Entity *pE2, Coordinates::Vector<float> collision) { return; } void ObstacleCollisionDealer::barrelCollision(Entities::Entity *pE1, Entities::Entity *pE2, Coordinates::Vector<float> collision) { Entities::Character* pC1 = static_cast<Entities::Character*>(pE1); if (collision.getX() > collision.getY()) { pC1->setIsOnGround(true); pC1->setPosition(Coordinates::Vector<float>(pC1->getPosition().getX(), pC1->getPosition().getY() - collision.getY())); } else { if (pC1->getPosition().getX() < pE2->getPosition().getX()) { pC1->setPosition(Coordinates::Vector<float>(pC1->getPosition().getX() - collision.getX(), pC1->getPosition().getY())); } else pC1->setPosition(Coordinates::Vector<float>(pC1->getPosition().getX() + collision.getX(), pC1->getPosition().getY())); } } void ObstacleCollisionDealer::fireCollision(Entities::Entity *pE1, Entities::Entity *pE2, Coordinates::Vector<float> collision) { if(pE1->getId() != Id::projectile) { Entities::Character* pC1 = static_cast<Entities::Character*>(pE1); Entities::Fire* pF2 = static_cast<Entities::Fire*>(pE2); if (pF2->getTimer() > 1.0f) { pC1->setLife(pC1->getLife() - pF2->getDamage()); pF2->setTimer(0.f); } } }
35.053571
130
0.642384
[ "vector" ]
830dddf7d4d36ba2804950fe41aedd4e2e68da6c
634
hpp
C++
example/prog-guide/distobj-reduce_to_rank0.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
null
null
null
example/prog-guide/distobj-reduce_to_rank0.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
null
null
null
example/prog-guide/distobj-reduce_to_rank0.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
1
2021-06-10T11:14:25.000Z
2021-06-10T11:14:25.000Z
int64_t reduce_to_rank0(int64_t my_hits) { // declare a distributed on every rank upcxx::dist_object<int64_t> all_hits(0); // set the local value of the distributed object on each rank *all_hits = my_hits; upcxx::barrier(); int64_t hits = 0; if (upcxx::rank_me() == 0) { // rank 0 gets all the values for (int i = 0; i < upcxx::rank_n(); i++) { // fetch the distributed object from remote rank i hits += all_hits.fetch(i).wait(); } } // ensure that no distributed objects are destructed before rank 0 is done upcxx::barrier(); return hits; }
31.7
78
0.608833
[ "object" ]
23fe7ce530354d0f459a69cd57fa714d557da906
1,932
cpp
C++
MatchStuff/MatchAll.cpp
mple/sigmod-programming-contest2013
900a969822f192793fa5f4152383cc9f5daafab4
[ "MIT" ]
1
2016-09-10T17:08:56.000Z
2016-09-10T17:08:56.000Z
MatchStuff/MatchAll.cpp
mple/sigmod-programming-contest2013
900a969822f192793fa5f4152383cc9f5daafab4
[ "MIT" ]
null
null
null
MatchStuff/MatchAll.cpp
mple/sigmod-programming-contest2013
900a969822f192793fa5f4152383cc9f5daafab4
[ "MIT" ]
null
null
null
/* * MatchAll1.cpp * * Created on: Mar 23, 2013 * Author: vagos */ #include "../QueryIndex/QueryIndex.h" #include "../QueryIndex/QidsVault.h" #include "../QueryIndex/QueryInfo.h" #include "../QueryIndex/bitarea.h" #include "../QueryIndex/Query.h" #include "../JobScheduler/JobMatchPrune.h" #include "../JobScheduler/job_scheduler.h" #include <stdlib.h> #include <list> #include "../TokenIndex/TokenDuplicateIndex.h" #include "../TokenIndex/TokenManager_Vector.h" #include "../TokenIndex/TokenStructs_Vector.h" #include "../MapStuff/UnorderMap.h" #include "../Includes/core.h" #include "../top_impl.h" #include <bitset> #include "../JobScheduler/JobBarrier.h" #include "../JobScheduler/JobGenHashes.h" #include "../JobScheduler/JobGenHashesToken.h" #include <vector> #include <unistd.h> #include "../MatchStuff/Relations.h" using namespace std; extern mple::JobScheduler* js; extern pthread_cond_t cond_barr; extern pthread_mutex_t mtx_barr; extern mple::JobScheduler* js; int count_genhashes; namespace mple { void SplitGenHashes() { count_genhashes = THREADS - 1; vector<Job*> jobs; for(int j=3; j>0; --j) { for (int i = 7; i < 11; ++i) { mple::JobGenHashes* JGH = new mple::JobGenHashes(i, j); jobs.push_back(JGH); } } for (int i = 7; i < 11; ++i) { mple::JobGenHashesToken* JGH2 = new mple::JobGenHashesToken(i, 0); jobs.push_back(JGH2); } for (int i = 27; i >= 0; --i) { if (i >= 7 && i <= 10) continue; for(int j=3; j>0; --j) { mple::JobGenHashes* JGH = new mple::JobGenHashes(i, j); jobs.push_back(JGH); } } for (int i = 27; i >= 0; --i) { if (i >= 7 && i <= 10) continue; mple::JobGenHashesToken* JGH2 = new mple::JobGenHashesToken(i, 0); jobs.push_back(JGH2); } for (int i = 0; i < THREADS; ++i) { JobBarrier* JB = new JobBarrier(&cond_barr, &mtx_barr, &count_genhashes); jobs.push_back(JB); } js->Schedule(jobs); } } //namespace mple
21.466667
75
0.658903
[ "vector" ]
9b01165c6cc65c50fff6f2e46bfb301b79fe8a7a
1,393
hpp
C++
Leetcode_C++/Leetcode_C++/Solution72.hpp
cwwise/Leetcode
5f8879945057312acd76492370e48314e4ec3b64
[ "MIT" ]
null
null
null
Leetcode_C++/Leetcode_C++/Solution72.hpp
cwwise/Leetcode
5f8879945057312acd76492370e48314e4ec3b64
[ "MIT" ]
null
null
null
Leetcode_C++/Leetcode_C++/Solution72.hpp
cwwise/Leetcode
5f8879945057312acd76492370e48314e4ec3b64
[ "MIT" ]
null
null
null
// // Solution72.hpp // Leetcode_C++ // // Created by chenwei on 2020/4/12. // Copyright © 2020 chenwei. All rights reserved. // #ifndef Solution72_hpp #define Solution72_hpp #include <stdio.h> /** 给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符   示例 1: 输入:word1 = "horse", word2 = "ros" 输出:3 解释: horse -> rorse (将 'h' 替换为 'r') rorse -> rose (删除 'r') rose -> ros (删除 'e') 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/edit-distance 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ class Solution72 { public: int minDistance(string word1, string word2) { size_t m = word1.length(), n = word2.length(); vector<vector<int>> dp(m+1, vector<int>(n+1, 0)); for (int i = 0; i <= m; i ++) { dp[i][0] = i; } for (int j = 0; j <= n; j ++) { dp[0][j] = j; } for (int i = 1; i <= m; i ++) { for (int j = 1; j <= n; j ++) { if (word1[i-1] == word2[j-1]) { dp[i][j] = dp[i-1][j-1]; } else { dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1; } } } return dp[m][n]; } void test() { cout << minDistance("abc", "abde") << endl; } }; #endif /* Solution72_hpp */
19.9
82
0.472362
[ "vector" ]
9b01c87bfdd3f3b8c9c0194e6e8b5ef6ac6129fa
9,907
cpp
C++
extension/sv_helper/SGA/SuffixTools/SampledSuffixArray.cpp
GenePlus/ncsv
f0f426ae4b64de86eee88518e3a1daf5718ce407
[ "Apache-2.0", "MIT" ]
1
2020-09-30T09:31:20.000Z
2020-09-30T09:31:20.000Z
extension/sv_helper/SGA/SuffixTools/SampledSuffixArray.cpp
GenePlus/ncsv
f0f426ae4b64de86eee88518e3a1daf5718ce407
[ "Apache-2.0", "MIT" ]
null
null
null
extension/sv_helper/SGA/SuffixTools/SampledSuffixArray.cpp
GenePlus/ncsv
f0f426ae4b64de86eee88518e3a1daf5718ce407
[ "Apache-2.0", "MIT" ]
null
null
null
//----------------------------------------------- // Copyright 2011 Wellcome Trust Sanger Institute // Written by Jared Simpson (js18@sanger.ac.uk) // Released under the GPL //----------------------------------------------- // // SampledSuffixArray - Data structure holding // a subset of suffix array positions. From the // sampled positions, the other entries of the // suffix array can be calculated. // #include "SampledSuffixArray.h" #include "SAReader.h" #include "SAWriter.h" #include "config.h" #if HAVE_OPENMP #include <omp.h> #endif static const uint32_t SSA_MAGIC_NUMBER = 12412; #define SSA_READ(x) pReader->read(reinterpret_cast<char*>(&(x)), sizeof((x))); #define SSA_READ_N(x,n) pReader->read(reinterpret_cast<char*>(&(x)), (n)); #define SSA_WRITE(x) pWriter->write(reinterpret_cast<const char*>(&(x)), sizeof((x))); #define SSA_WRITE_N(x,n) pWriter->write(reinterpret_cast<const char*>(&(x)), (n)); // SampledSuffixArray::SampledSuffixArray() { } SampledSuffixArray::SampledSuffixArray(const std::string& filename, SSAFileType filetype) { // Read the sampled suffix array from a file - either from a .ssa or .sai file if(filetype == SSA_FT_SSA) readSSA(filename); else readSAI(filename); } // SAElem SampledSuffixArray::calcSA(int64_t idx, const BWT* pBWT) const { size_t offset = 0; SAElem elem; while(1) { // Check if this position is sampled. If the sample rate is zero we are using the lexo. index only if(m_sampleRate > 0 && idx % m_sampleRate == 0 && !m_saSamples[idx / m_sampleRate].isEmpty()) { // A valid sample is stored for this idx elem = m_saSamples[idx / m_sampleRate]; break; } // A sample does not exist for this position, perform a backtracking step char b = pBWT->getChar(idx); idx = pBWT->getPC(b) + pBWT->getOcc(b, idx - 1); if(b == '$') { // idx (before the update) corresponds to the start of a read. // We can directly look up the saElem for idx from the lexicographic index assert(idx < (int64_t)m_saLexoIndex.size()); elem.setID(m_saLexoIndex[idx]); elem.setPos(0); break; } else { // A backtracking step is performed, increment offset offset += 1; } } elem.setPos(elem.getPos() + offset); return elem; } // Returns the ID of the read with lexicographic rank r size_t SampledSuffixArray::lookupLexoRank(size_t r) const { return m_saLexoIndex[r]; } // void SampledSuffixArray::build(const BWT* pBWT, const ReadInfoTable* pRIT, int sampleRate) { m_sampleRate = sampleRate; size_t numStrings = pRIT->getCount(); m_saLexoIndex.resize(numStrings); size_t MAX_ELEMS = std::numeric_limits<SSA_INT_TYPE>::max(); if(numStrings > MAX_ELEMS) { std::cerr << "Error: Only " << MAX_ELEMS << " reads are allowed in the sampled suffix array\n"; std::cerr << "Number of reads in your index: " << numStrings << "\n"; std::cerr << "Contact sga-users@googlegroups.com for help\n"; exit(EXIT_FAILURE); } // Set the size of the sampled vector size_t numElems = (pBWT->getBWLen() / m_sampleRate) + 1; m_saSamples.resize(numElems); // For each read, start from the end of the read and backtrack through the suffix array/BWT. // For every idx that is divisible by the sample rate, store the calculate SAElem for(size_t i = 0; i < numStrings; ++i) { // The suffix array positions for the ends of reads are ordered // by their position in the read information table, therefore // the starting suffix array index is i size_t idx = i; // The ID of the read is i. The position coordinate is inclusive but // since the read information table does not store the '$' symbol // the starting position equals the read length SAElem elem(i, pRIT->getReadLength(i)); while(1) { if(idx % m_sampleRate == 0) { // store this SAElem m_saSamples[idx / m_sampleRate] = elem; } char b = pBWT->getChar(idx); idx = pBWT->getPC(b) + pBWT->getOcc(b, idx - 1); if(b == '$') { // we have hit the beginning of this string // store the SAElem for the beginning of the read // in the lexicographic index if(elem.getPos() != 0) std::cout << "elem: " << elem << " i: " << i << "\n"; assert(elem.getPos() == 0); size_t id = elem.getID(); assert(id < MAX_ELEMS); m_saLexoIndex[idx] = id; break; // done; } else { // Decrease the position of the elem elem.setPos(elem.getPos() - 1); } } } } // A streamlined version of the above function void SampledSuffixArray::buildLexicoIndex(const BWT* pBWT, int num_threads) { int64_t numStrings = pBWT->getNumStrings(); m_saLexoIndex.resize(numStrings); int64_t MAX_ELEMS = std::numeric_limits<SSA_INT_TYPE>::max(); assert(numStrings < MAX_ELEMS); (void)num_threads; // Parallelize this computaiton using openmp, if the compiler supports it #if HAVE_OPENMP omp_set_num_threads(num_threads); #pragma omp parallel for #endif for(int64_t read_idx = 0; read_idx < numStrings; ++read_idx) { // For each read, start from the end of the read and backtrack through the suffix array/BWT // to calculate its lexicographic rank in the collection size_t idx = read_idx; while(1) { char b = pBWT->getChar(idx); idx = pBWT->getPC(b) + pBWT->getOcc(b, idx - 1); if(b == '$') { // There is a one-to-one mapping between read_index and the element // of the array that is set - therefore we can perform this operation // without a lock. m_saLexoIndex[idx] = read_idx; break; // done; } } } } // Validate the sampled suffix array values are correct void SampledSuffixArray::validate(const std::string filename, const BWT* pBWT) { ReadTable* pRT = new ReadTable(filename); SuffixArray* pSA = new SuffixArray(pRT, 1); std::cout << "Validating sampled suffix array entries\n"; for(size_t i = 0; i < pSA->getSize(); ++i) { SAElem calc = calcSA(i, pBWT); SAElem real = pSA->get(i); if(calc.getID() != real.getID() || calc.getPos() != real.getPos()) { std::cout << "Error SA elements do not match for " << i << "\n"; std::cout << "Calc: " << calc << "\n"; std::cout << "Real: " << real << "\n"; exit(1); } } std::cout << "All calculate SA values are correct\n"; delete pRT; delete pSA; } // Save the SA to disc void SampledSuffixArray::writeSSA(std::string filename) { std::ostream* pWriter = createWriter(filename, std::ios::out | std::ios::binary); // Write a magic number SSA_WRITE(SSA_MAGIC_NUMBER) // Write sample rate SSA_WRITE(m_sampleRate) // Write number of lexicographic index entries size_t n = m_saLexoIndex.size(); SSA_WRITE(n) // Write lexo index SSA_WRITE_N(m_saLexoIndex.front(), sizeof(SSA_INT_TYPE) * n) // Write number of samples n = m_saSamples.size(); SSA_WRITE(n) // Write samples SSA_WRITE_N(m_saSamples.front(), sizeof(SAElem) * n) delete pWriter; } // Save just the lexicographic index portion of the SSA to disk as plaintext void SampledSuffixArray::writeLexicoIndex(const std::string& filename) { SAWriter writer(filename); size_t num_strings = m_saLexoIndex.size(); writer.writeHeader(num_strings, num_strings); for(size_t i = 0; i < m_saLexoIndex.size(); ++i) { SAElem elem(m_saLexoIndex[i], 0); writer.writeElem(elem); } } void SampledSuffixArray::readSSA(std::string filename) { std::istream* pReader = createReader(filename, std::ios::binary); // Write a magic number uint32_t magic = 0; SSA_READ(magic) assert(magic == SSA_MAGIC_NUMBER); // Read sample rate SSA_READ(m_sampleRate) // Read number of lexicographic index entries size_t n = 0; SSA_READ(n) m_saLexoIndex.resize(n); // Read lexo index SSA_READ_N(m_saLexoIndex.front(), sizeof(SSA_INT_TYPE) * n) // Read number of samples n = 0; SSA_READ(n) m_saSamples.resize(n); // Read samples SSA_READ_N(m_saSamples.front(), sizeof(SAElem) * n) delete pReader; } void SampledSuffixArray::readSAI(std::string filename) { SAReader reader(filename); size_t num_strings, num_elems; reader.readHeader(num_strings, num_elems); assert(num_strings == num_elems); m_saLexoIndex.reserve(num_strings); reader.readElems(m_saLexoIndex); // Set the sample rate to zero to signify there are no samples m_sampleRate = 0; } // Print memory usage information void SampledSuffixArray::printInfo() const { double mb = (double)(1024*1024); double lexoSize = (double)(sizeof(SSA_INT_TYPE) * m_saLexoIndex.capacity()) / mb; double sampleSize = (double)(sizeof(SAElem) * m_saSamples.capacity()) / mb; printf("SampledSuffixArray info:\n"); printf("Sample rate: %d\n", m_sampleRate); printf("Contains %zu entries in lexicographic array (%.1lf MB)\n", m_saLexoIndex.size(), lexoSize); printf("Contains %zu entries in sample array (%.1lf MB)\n", m_saSamples.size(), sampleSize); printf("Total size: %.1lf\n", lexoSize + sampleSize); }
31.154088
106
0.608156
[ "vector" ]
9b06f31ab5e9732c6648f5413271159977cb1ea1
481
cpp
C++
cpp/turbodbc/Library/src/result_sets/result_set.cpp
arikfr/turbodbc
80a29a7edfbdabf12410af01c0c0ae74bfc3aab4
[ "MIT" ]
537
2016-03-18T21:46:05.000Z
2022-03-29T04:43:17.000Z
cpp/turbodbc/Library/src/result_sets/result_set.cpp
arikfr/turbodbc
80a29a7edfbdabf12410af01c0c0ae74bfc3aab4
[ "MIT" ]
325
2016-04-08T11:54:41.000Z
2022-03-21T23:58:42.000Z
cpp/turbodbc/Library/src/result_sets/result_set.cpp
arikfr/turbodbc
80a29a7edfbdabf12410af01c0c0ae74bfc3aab4
[ "MIT" ]
83
2016-06-15T13:55:44.000Z
2022-03-26T02:32:26.000Z
#include <turbodbc/result_sets/result_set.h> namespace turbodbc { namespace result_sets { result_set::result_set() = default; result_set::~result_set() = default; std::size_t result_set::fetch_next_batch() { return do_fetch_next_batch(); } std::vector<column_info> result_set::get_column_info() const { return do_get_column_info(); } std::vector<std::reference_wrapper<cpp_odbc::multi_value_buffer const>> result_set::get_buffers() const { return do_get_buffers(); } } }
19.24
103
0.765073
[ "vector" ]
9b0e6f285a7ec0a02c519f7dd503eda309fc9d6b
1,974
cc
C++
vendor/chromium/base/sampling_heap_profiler/module_cache.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
5,411
2017-04-14T08:57:56.000Z
2022-03-30T19:35:15.000Z
vendor/chromium/base/sampling_heap_profiler/module_cache.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
802
2017-04-21T14:18:36.000Z
2022-03-31T21:20:48.000Z
vendor/chromium/base/sampling_heap_profiler/module_cache.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
2,011
2017-04-14T09:44:15.000Z
2022-03-31T15:40:39.000Z
// Copyright 2018 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 "base/sampling_heap_profiler/module_cache.h" #include <utility> namespace base { ModuleCache::ModuleCache() = default; ModuleCache::~ModuleCache() = default; const ModuleCache::Module* ModuleCache::GetModuleForAddress(uintptr_t address) { Module* module = FindModuleForAddress(non_native_modules_, address); if (module) return module; module = FindModuleForAddress(native_modules_, address); if (module) return module; std::unique_ptr<Module> new_module = CreateModuleForAddress(address); if (!new_module) return nullptr; native_modules_.push_back(std::move(new_module)); return native_modules_.back().get(); } std::vector<const ModuleCache::Module*> ModuleCache::GetModules() const { std::vector<const Module*> result; result.reserve(native_modules_.size()); for (const std::unique_ptr<Module>& module : native_modules_) result.push_back(module.get()); return result; } void ModuleCache::AddNonNativeModule(std::unique_ptr<Module> module) { DCHECK(!module->IsNative()); non_native_modules_.push_back(std::move(module)); } void ModuleCache::InjectModuleForTesting(std::unique_ptr<Module> module) { native_modules_.push_back(std::move(module)); } // static ModuleCache::Module* ModuleCache::FindModuleForAddress( const std::vector<std::unique_ptr<Module>>& modules, uintptr_t address) { auto it = std::find_if(modules.begin(), modules.end(), [address](const std::unique_ptr<Module>& module) { return address >= module->GetBaseAddress() && address < module->GetBaseAddress() + module->GetSize(); }); return it != modules.end() ? it->get() : nullptr; } } // namespace base
32.360656
80
0.678825
[ "vector" ]
9b14116c039d2a2ab499bd5d74bd19f07a5a5d08
3,829
cpp
C++
CI3-14/src/Supermercado.cpp
pemesteves/AEDA_1819-exercises
c8158547a53865c3910e420208b853579d0971c6
[ "MIT" ]
2
2018-11-28T10:59:27.000Z
2018-12-21T14:33:12.000Z
CI3-14/src/Supermercado.cpp
pemesteves/AEDA_1819-exercises
c8158547a53865c3910e420208b853579d0971c6
[ "MIT" ]
null
null
null
CI3-14/src/Supermercado.cpp
pemesteves/AEDA_1819-exercises
c8158547a53865c3910e420208b853579d0971c6
[ "MIT" ]
1
2018-11-18T23:41:41.000Z
2018-11-18T23:41:41.000Z
/* * Supermercado.cpp * * Created on: Dec 3, 2014 * */ #include "Supermercado.h" #include <map> #include <utility> #include <sstream> int Cliente::numeroItens() const{ int num = 0; for(list<Cesto>::const_iterator it = cestos.begin(); it != cestos.end(); it++){ num += it->getItens().size(); } return num; } int Cliente::valorItens() const{ int valor = 0; stack<Item> s; for(list<Cesto>::const_iterator it = cestos.begin(); it != cestos.end(); it++){ if (!it->empty()){ s = it->getItens(); while(!s.empty()){ valor += s.top().preco; s.pop(); } } } return valor; } int Cliente::trocarItem(Item& novoItem){ int numItens = 0; stack<Item> s; for(list<Cesto>::iterator it = cestos.begin(); it != cestos.end(); it++){ if (!it->empty()){ s = it->getItens(); while(!it->empty()){ it->popItem(); } while(!s.empty()){ if(s.top().produto == novoItem.produto && s.top().preco > novoItem.preco){ numItens++; s.pop(); it->pushItem(novoItem); } else{ it->pushItem(s.top()); s.pop(); } } } } return numItens; } void Cliente::organizarCestos(){ stack<Item> itens; vector<Item> v; for(list<Cesto>::iterator it = cestos.begin(); it != cestos.end(); it++){ v.clear(); itens = it->getItens(); while(!itens.empty()){ v.push_back(itens.top()); itens.pop(); it->popItem(); } sort(v.begin(),v.end()); for(vector<Item>::iterator it1 = v.begin(); it1 != v.end(); it1++){ it->pushItem(*it1); } } } vector<string> Cliente::contarItensPorTipo(){ map<string, int> m; map<string, int>::iterator im; pair<string, int> p; stack<Item> s; for(list<Cesto>::iterator it = cestos.begin(); it != cestos.end(); it++){ if (!it->empty()){ s = it->getItens(); while(!s.empty()){ im = m.find(s.top().tipo); if (im == m.end()){ p = make_pair(s.top().tipo, 1); m.insert(p); } else{ (*im).second++; } s.pop(); } } } vector<string> v; ostringstream oss; for(im = m.begin(); im != m.end(); im++){ oss.str(std::string()); oss << (*im).first << " " << (*im).second; v.push_back(oss.str()); } return v; } int Cesto::novoItem(const Item& umItem){ if(umItem.peso + peso > max_peso || umItem.volume + volume > max_volume){ return 0; } itens.push(umItem); peso += umItem.peso; volume += umItem.volume; return itens.size(); } int Cliente::novoItem(const Item& umItem){ list<Cesto>::iterator it = cestos.begin(); for(; it != cestos.end(); it++){ if(it->novoItem(umItem) != 0) break; } if(it == cestos.end()){ Cesto c; c.pushItem(umItem); cestos.push_back(c); } return cestos.size(); } int Supermercado::novoCliente(Cliente& umCliente){ if(umCliente.getIdade() < 65){ filaNormal.push(umCliente); } else{ if(filaNormal.size() < filaPrioritaria.size()){ filaNormal.push(umCliente); } else{ filaPrioritaria.push(umCliente); } } return filaNormal.size() + filaPrioritaria.size(); } Cliente Supermercado::sairDaFila(string umNomeDeCliente){ queue<Cliente> fila = filaNormal; queue<Cliente> novaFila; while(!fila.empty()){ if (fila.front().getNome() == umNomeDeCliente){ Cliente c; c = fila.front(); fila.pop(); while(!fila.empty()){ novaFila.push(fila.front()); fila.pop(); } filaNormal = novaFila; return c; } novaFila.push(fila.front()); fila.pop(); } while(!novaFila.empty()){ novaFila.pop(); } fila = filaPrioritaria; while(!fila.empty()){ if (fila.front().getNome() == umNomeDeCliente){ Cliente c; c = fila.front(); fila.pop(); while(!fila.empty()){ novaFila.push(fila.front()); fila.pop(); } filaPrioritaria = novaFila; return c; } novaFila.push(fila.front()); fila.pop(); } throw ClienteInexistente(umNomeDeCliente); }
19.535714
80
0.591277
[ "vector" ]
9b1b9bfed562090cf096e903fca4982596351a03
735
cpp
C++
Problemset/longest-valid-parentheses/longest-valid-parentheses.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
1
2020-10-06T01:06:45.000Z
2020-10-06T01:06:45.000Z
Problemset/longest-valid-parentheses/longest-valid-parentheses.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
null
null
null
Problemset/longest-valid-parentheses/longest-valid-parentheses.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
1
2021-11-17T13:52:51.000Z
2021-11-17T13:52:51.000Z
// @Title: 最长有效括号 (Longest Valid Parentheses) // @Author: Singularity0909 // @Date: 2020-10-01 01:15:18 // @Runtime: 4 ms // @Memory: 7.3 MB class Solution { public: int longestValidParentheses(string s) { int mx = 0, n = (int)s.length(); vector<int> dp(n, 0); for (int i = 1; i < n; ++i) { if (s[i] == ')') { if (s[i - 1] == '(') { dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2; } else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') { dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2; } mx = max(mx, dp[i]); } } return mx; } };
27.222222
95
0.361905
[ "vector" ]
9b280c4acc66cf6ac9b2dabc6ecd1ff127f64557
1,732
cpp
C++
src/TantechEngine/input_system.cpp
evinstk/TantechEngine
6621b6d159629547c8d75a49ffdf099a8052a2f6
[ "MIT" ]
null
null
null
src/TantechEngine/input_system.cpp
evinstk/TantechEngine
6621b6d159629547c8d75a49ffdf099a8052a2f6
[ "MIT" ]
2
2015-11-16T16:05:08.000Z
2015-11-16T16:06:10.000Z
src/TantechEngine/input_system.cpp
evinstk/TantechEngine
6621b6d159629547c8d75a49ffdf099a8052a2f6
[ "MIT" ]
null
null
null
#include "command_system.h" #include <algorithm> namespace te { InputSystem::InputSystem(std::shared_ptr<CommandSystem> pCommandSystem) : mpCommandSystem(pCommandSystem) , mKeyPressMap() , mKeyReleaseMap() { assert(pCommandSystem); } static void assignCommand(char ch, Command&& cmd, std::map<char, std::vector<Command>>& map) { auto commandIt = map.find(ch); if (commandIt == map.end()) { map.insert(std::pair<char, std::vector<Command>>(ch, { std::move(cmd) })); } else { commandIt->second.push_back(cmd); } } void InputSystem::setKeyPress(char ch, Command&& cmd) { assignCommand(ch, std::move(cmd), mKeyPressMap); } void InputSystem::setKeyRelease(char ch, Command&& cmd) { assignCommand(ch, std::move(cmd), mKeyReleaseMap); } std::map<char, std::vector<Command>>& InputSystem::getInputMap(InputType type) { switch (type) { case InputType::PRESS: return mKeyPressMap; case InputType::RELEASE: return mKeyReleaseMap; default: throw std::runtime_error("InputSystem::processInput: Unsupported input type."); } } void InputSystem::processInput(char ch, InputType type) { std::map<char, std::vector<Command>>& pMap = getInputMap(type); auto commandsIt = pMap.find(ch); if (commandsIt != pMap.end()) { std::for_each(std::begin(commandsIt->second), std::end(commandsIt->second), [this](const Command& cmd) { mpCommandSystem->queueCommand(cmd); }); } } }
29.355932
96
0.572748
[ "vector" ]
9b2a81a8427b5460908a4a40caf6dae24bd38f94
14,071
cpp
C++
Source/Utility/BridgeSunset/BridgeSunset.cpp
paintdream/PaintsNow
52e14de651b56c100caac0ce2b14348441543e1a
[ "MIT" ]
15
2016-09-17T16:29:42.000Z
2021-11-24T06:21:27.000Z
Source/Utility/BridgeSunset/BridgeSunset.cpp
paintdream/PaintsNow
52e14de651b56c100caac0ce2b14348441543e1a
[ "MIT" ]
null
null
null
Source/Utility/BridgeSunset/BridgeSunset.cpp
paintdream/PaintsNow
52e14de651b56c100caac0ce2b14348441543e1a
[ "MIT" ]
3
2017-04-07T13:33:57.000Z
2021-03-31T02:04:48.000Z
#include "BridgeSunset.h" using namespace PaintsNow; SharedContext::SharedContext() : next(nullptr) { atomicValue.store(0, std::memory_order_release); } SharedContext::~SharedContext() { SharedContext* p = next.exchange(nullptr, std::memory_order_acq_rel); while (p != nullptr) { SharedContext* t = p; p = p->next.load(std::memory_order_relaxed); t->next = nullptr; t->ReleaseObject(); } } BridgeSunset::BridgeSunset(IThread& t, IScript& s, uint32_t threadCount, uint32_t warpCount) : ISyncObject(t), RequestPool(s, warpCount), threadPool(t, threadCount), kernel(threadPool, warpCount) { memset(warpBitset, 0, sizeof(warpBitset)); if (!threadPool.IsInitialized()) { threadPool.Initialize(); } script.DoLock(); for (uint32_t k = 0; k < threadPool.GetThreadCount(); k++) { threadPool.SetThreadContext(k, this); } // register script dispatcher hook origDispatcher = script.GetDispatcher(); script.SetDispatcher(Wrap(this, &BridgeSunset::ContinueScriptDispatcher)); script.UnLock(); } BridgeSunset::~BridgeSunset() { assert(threadPool.IsInitialized()); threadPool.Uninitialize(); IScript::Request& mainRequest = script.GetDefaultRequest(); assert(script.GetDispatcher() == Wrap(this, &BridgeSunset::ContinueScriptDispatcher)); script.SetDispatcher(origDispatcher); requestPool.Clear(); // clear request pool } void BridgeSunset::ScriptInitialize(IScript::Request& request) { Library::ScriptInitialize(request); } void BridgeSunset::ScriptUninitialize(IScript::Request& request) { Library::ScriptUninitialize(request); } TObject<IReflect>& BridgeSunset::operator () (IReflect& reflect) { BaseClass::operator () (reflect); if (reflect.IsReflectMethod()) { ReflectMethod(RequestNewSharedContext)[ScriptMethod = "NewSharedContext"]; ReflectMethod(RequestSetSharedContextCounter)[ScriptMethodLocked = "SetSharedContextCounter"]; ReflectMethod(RequestCompareExchangeSharedContextCounter)[ScriptMethodLocked = "CompareExchangeSharedContextCounter"]; ReflectMethod(RequestAddSharedContextCounter)[ScriptMethodLocked = "AddSharedContextCounter"]; ReflectMethod(RequestSubSharedContextCounter)[ScriptMethodLocked = "SubSharedContextCounter"]; ReflectMethod(RequestGetSharedContextCounter)[ScriptMethodLocked = "GetSharedContextCounter"]; ReflectMethod(RequestSetSharedContextObjects)[ScriptMethodLocked = "SetSharedContextObjects"]; ReflectMethod(RequestGetSharedContextObjects)[ScriptMethodLocked = "GetSharedContextObjects"]; ReflectMethod(RequestSetSharedContextObject)[ScriptMethodLocked = "SetSharedContextObject"]; ReflectMethod(RequestGetSharedContextObject)[ScriptMethodLocked = "GetSharedContextObject"]; ReflectMethod(RequestChainSharedContext)[ScriptMethodLocked = "ChainSharedContext"]; ReflectMethod(RequestExtractSharedContextChain)[ScriptMethodLocked = "ExtractSharedContextChain"]; ReflectMethod(RequestNewGraph)[ScriptMethod = "NewGraph"]; ReflectMethod(RequestQueueGraphRoutine)[ScriptMethodLocked = "QueueGraphRoutine"]; ReflectMethod(RequestConnectGraphRoutine)[ScriptMethodLocked = "ConnectGraphRoutine"]; ReflectMethod(RequestExecuteGraph)[ScriptMethod = "ExecuteGraph"]; ReflectMethod(RequestQueueRoutine)[ScriptMethodLocked = "QueueRoutine"]; // Auto-locked ReflectMethod(RequestGetWarpCount)[ScriptMethodLocked = "GetWarpCount"]; ReflectMethod(RequestSetWarpIndex)[ScriptMethodLocked = "SetWarpIndex"]; ReflectMethod(RequestGetWarpIndex)[ScriptMethodLocked = "GetWarpIndex"]; ReflectMethod(RequestGetCurrentThreadIndex)[ScriptMethodLocked = "GetCurrentThreadIndex"]; ReflectMethod(RequestGetCurrentWarpIndex)[ScriptMethodLocked = "GetCurrentWarpIndex"]; ReflectMethod(RequestGetNullWarpIndex)[ScriptMethodLocked = "GetNullWarpIndex"]; ReflectMethod(RequestAllocateWarpIndex)[ScriptMethodLocked = "AllocateWarpIndex"]; ReflectMethod(RequestFreeWarpIndex)[ScriptMethodLocked = "FreeWarpIndex"]; ReflectMethod(RequestPin)[ScriptMethodLocked = "Pin"]; ReflectMethod(RequestUnpin)[ScriptMethodLocked = "Unpin"]; ReflectMethod(RequestClone)[ScriptMethod = "Clone"]; } return *this; } Kernel& BridgeSunset::GetKernel() { return kernel; } void BridgeSunset::ContinueScriptDispatcher(IScript::Request& request, IHost* host, size_t paramCount, const TWrapper<void, IScript::Request&>& continuer) { // check if current warp is yielded static thread_local uint32_t stackWarpIndex = ~(uint32_t)0; uint32_t warpIndex = kernel.GetCurrentWarpIndex(); if (warpIndex != ~(uint32_t)0) { stackWarpIndex = warpIndex; continuer(request); stackWarpIndex = warpIndex; } else { uint32_t saveStackWarpIndex = stackWarpIndex; if (saveStackWarpIndex != ~(uint32_t)0) { request.UnLock(); kernel.WaitWarp(stackWarpIndex); request.DoLock(); } continuer(request); stackWarpIndex = saveStackWarpIndex; kernel.YieldCurrentWarp(); } } void BridgeSunset::RequestQueueRoutine(IScript::Request& request, IScript::Delegate<WarpTiny> unit, IScript::Request::Ref callback) { CHECK_REFERENCES_WITH_TYPE_LOCKED(callback, IScript::Request::FUNCTION); CHECK_DELEGATE(unit); if (GetKernel().GetCurrentWarpIndex() != unit->GetWarpIndex()) { GetKernel().QueueRoutinePost(unit.Get(), CreateTaskScriptOnce(callback)); } else { // Already locked! // request.DoLock(); request.Push(); request.Call(callback); request.Dereference(callback); request.Pop(); // request.UnLock(); } } uint32_t BridgeSunset::RequestGetWarpCount(IScript::Request& request) { CHECK_REFERENCES_NONE(); return GetKernel().GetWarpCount(); } TShared<TaskGraph> BridgeSunset::RequestNewGraph(IScript::Request& request, int32_t startupWarp) { CHECK_REFERENCES_NONE(); return TShared<TaskGraph>::From(new TaskGraph(kernel)); } size_t BridgeSunset::RequestQueueGraphRoutine(IScript::Request& request, IScript::Delegate<TaskGraph> graph, IScript::Delegate<WarpTiny> unit, IScript::Request::Ref callback) { CHECK_REFERENCES_WITH_TYPE_LOCKED(callback, IScript::Request::FUNCTION); CHECK_DELEGATE(graph); CHECK_DELEGATE(unit); return graph->Insert(unit.Get(), CreateTaskScriptOnce(callback)); } void BridgeSunset::RequestConnectGraphRoutine(IScript::Request& request, IScript::Delegate<TaskGraph> graph, int32_t prev, int32_t next) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(graph); graph->Next(prev, next); } struct ScriptTaskWrapper { ScriptTaskWrapper(BridgeSunset* b, ITask* t) : bridgeSunset(b), task(t) {} void operator () () { bridgeSunset->threadPool.Dispatch(task); } BridgeSunset* bridgeSunset; ITask* task; }; void BridgeSunset::RequestExecuteGraph(IScript::Request& request, IScript::Delegate<TaskGraph> graph, IScript::Request::Ref callback) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(graph); if (callback) { ScriptTaskWrapper wrapper(this, CreateTaskScriptOnce(callback)); graph->Dispatch(WrapClosure(std::move(wrapper), &ScriptTaskWrapper::operator ())); } else { graph->Dispatch(); } } void BridgeSunset::RequestSetWarpIndex(IScript::Request& request, IScript::Delegate<WarpTiny> source, uint32_t index) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(source); source->SetWarpIndex(index); } uint32_t BridgeSunset::RequestGetWarpIndex(IScript::Request& request, IScript::Delegate<WarpTiny> source) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(source); return source->GetWarpIndex(); } uint32_t BridgeSunset::RequestGetCurrentThreadIndex(IScript::Request& request) { CHECK_REFERENCES_NONE(); return kernel.GetThreadPool().GetCurrentThreadIndex(); } uint32_t BridgeSunset::RequestGetCurrentWarpIndex(IScript::Request& request) { CHECK_REFERENCES_NONE(); return kernel.GetCurrentWarpIndex(); } uint32_t BridgeSunset::RequestGetNullWarpIndex(IScript::Request& request) { CHECK_REFERENCES_NONE(); return ~(uint32_t)0; } TShared<SharedTiny> BridgeSunset::RequestClone(IScript::Request& request, IScript::Delegate<SharedTiny> source) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(source); return static_cast<SharedTiny*>(source->Clone()); } void BridgeSunset::RequestPin(IScript::Request& request, IScript::Delegate<WarpTiny> source) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(source); source->Flag().fetch_or(Tiny::TINY_PINNED); } void BridgeSunset::RequestUnpin(IScript::Request& request, IScript::Delegate<WarpTiny> source) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(source); source->Flag().fetch_and(~Tiny::TINY_PINNED); } uint32_t BridgeSunset::RequestAllocateWarpIndex(IScript::Request& request) { CHECK_REFERENCES_NONE(); static_assert(WARP_VAR_COUNT * sizeof(size_t) * 8 == (1 << WarpTiny::WARP_BITS), "Warp count must be multiplier of sizeof(size_t) * 8"); for (size_t i = 0; i < WARP_VAR_COUNT; i++) { std::atomic<size_t>& v = reinterpret_cast<std::atomic<size_t>&>(warpBitset[i]); size_t value = v.load(std::memory_order_relaxed); if (value != ~(size_t)0) { size_t mask = Math::Alignment(value + 1); if (!(v.fetch_or(mask, std::memory_order_relaxed) & mask)) { return (1 + Math::Log2x(mask)) & ((1 << WarpTiny::WARP_BITS) - 1); // warp 0 is reserved } } } // overflow return 0; } void BridgeSunset::RequestFreeWarpIndex(IScript::Request& request, uint32_t warpIndex) { CHECK_REFERENCES_NONE(); if (warpIndex-- != 0) { std::atomic<size_t>& v = reinterpret_cast<std::atomic<size_t>&>(warpBitset[warpIndex / (sizeof(size_t) * 8)]); size_t mask = (size_t)1 << (warpIndex & (sizeof(size_t) * 8 - 1)); v.fetch_and(~mask, std::memory_order_relaxed); } else { request.Error("Can not free warp 0"); } } TShared<SharedContext> BridgeSunset::RequestNewSharedContext(IScript::Request& request) { return TShared<SharedContext>::From(new SharedContext()); } size_t BridgeSunset::RequestSetSharedContextCounter(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext, size_t counter) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); return sharedContext->atomicValue.exchange(counter, std::memory_order_acq_rel); } bool BridgeSunset::RequestCompareExchangeSharedContextCounter(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext, size_t comparedTo, size_t counter) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); return sharedContext->atomicValue.compare_exchange_strong(comparedTo, counter, std::memory_order_acq_rel); } size_t BridgeSunset::RequestAddSharedContextCounter(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext, size_t counter) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); return sharedContext->atomicValue.fetch_add(counter, std::memory_order_acq_rel); } size_t BridgeSunset::RequestSubSharedContextCounter(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext, size_t counter) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); return sharedContext->atomicValue.fetch_sub(counter, std::memory_order_acq_rel); } size_t BridgeSunset::RequestGetSharedContextCounter(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); return sharedContext->atomicValue.load(std::memory_order_acquire); } void BridgeSunset::RequestSetSharedContextObjects(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext, std::vector<IScript::Delegate<SharedTiny> >& tinies) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); std::vector<TShared<SharedTiny> > vec(tinies.size()); for (size_t i = 0; i < tinies.size(); i++) { vec[i] = tinies[i].Get(); } std::swap(sharedContext->objectVector, vec); } void BridgeSunset::RequestSetSharedContextObject(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext, size_t index, IScript::Delegate<SharedTiny> tiny) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); if (index < sharedContext->objectVector.size()) { sharedContext->objectVector[index] = tiny.Get(); } } const std::vector<TShared<SharedTiny> >& BridgeSunset::RequestGetSharedContextObjects(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); return sharedContext->objectVector; } TShared<SharedTiny> BridgeSunset::RequestGetSharedContextObject(IScript::Request& request, IScript::Delegate<SharedContext> sharedContext, size_t index) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sharedContext); if (index < sharedContext->objectVector.size()) { return sharedContext->objectVector[index]; } else { return nullptr; } } void BridgeSunset::RequestChainSharedContext(IScript::Request& request, IScript::Delegate<SharedContext> sentinelSharedContext, IScript::Delegate<SharedContext> sharedContext) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sentinelSharedContext); CHECK_DELEGATE(sharedContext); SharedContext* p = sentinelSharedContext.Get(); SharedContext* q = sharedContext.Get(); q->ReferenceObject(); SharedContext* head = q->next.load(std::memory_order_relaxed); do { q->next.store(head, std::memory_order_relaxed); } while (p->next.compare_exchange_strong(head, q, std::memory_order_release, std::memory_order_relaxed)); } std::vector<TShared<SharedContext> > BridgeSunset::RequestExtractSharedContextChain(IScript::Request& request, IScript::Delegate<SharedContext> sentinelSharedContext) { CHECK_REFERENCES_NONE(); CHECK_DELEGATE(sentinelSharedContext); std::vector<TShared<SharedContext> > result; SharedContext* p = sentinelSharedContext->next.exchange(nullptr, std::memory_order_acq_rel); while (p != nullptr) { SharedContext* t = p; p = p->next.load(std::memory_order_relaxed); t->next = nullptr; result.emplace_back(TShared<SharedContext>::From(t)); } return result; }
37.323607
198
0.757515
[ "vector" ]
9b2d2d1ded28b431214b406e6f1b579ff83d9249
2,614
cpp
C++
week-02/beach-bars/src/main.cpp
tehwalris/algolab
489e0f6dd137336fa32b8002fc6eed8a7d35d87a
[ "MIT" ]
1
2021-01-17T08:21:32.000Z
2021-01-17T08:21:32.000Z
week-02/beach-bars/src/main.cpp
tehwalris/algolab
489e0f6dd137336fa32b8002fc6eed8a7d35d87a
[ "MIT" ]
null
null
null
week-02/beach-bars/src/main.cpp
tehwalris/algolab
489e0f6dd137336fa32b8002fc6eed8a7d35d87a
[ "MIT" ]
null
null
null
#include <iostream> #include <bitset> #include <vector> #include <assert.h> #include <algorithm> #include <deque> #include <limits> const int max_parasols = 1'000'000; const int beach_size = 2 * max_parasols + 1; const int beach_middle = beach_size / 2; const int max_near_distance = 100; void testcase() { std::bitset<beach_size> parasols; int n; std::cin >> n; assert(n >= 1 && n <= max_parasols); for (int i = 0; i < n; i++) { int v; std::cin >> v; v += beach_middle; assert(v >= 0 && v < beach_size); parasols.set(v); } std::vector<int> nearby_customers_by_pos(beach_size, 0); std::vector<int> longest_walk_by_pos(beach_size, -1); std::deque<int> nearby_customers; for (int bar = -max_near_distance; bar < beach_size + max_near_distance; bar++) { int new_customer_pos = bar + max_near_distance; assert(new_customer_pos >= 0); if (new_customer_pos < beach_size && parasols.test(new_customer_pos)) { nearby_customers.push_front(new_customer_pos); } int old_customer_pos = bar - max_near_distance - 1; assert(old_customer_pos < beach_size); if (old_customer_pos >= 0 && parasols.test(old_customer_pos)) { nearby_customers.pop_back(); } if (bar >= 0 && bar < beach_size) { nearby_customers_by_pos.at(bar) = nearby_customers.size(); if (nearby_customers.size() > 0) { longest_walk_by_pos.at(bar) = std::max(abs(nearby_customers.front() - bar), abs(nearby_customers.back() - bar)); } } } int max_nearby_customers = *std::max_element(nearby_customers_by_pos.begin(), nearby_customers_by_pos.end()); assert(max_nearby_customers >= 1); int min_relevant_walk = std::numeric_limits<int>::max(); for (int i = 0; i < beach_size; i++) { if (nearby_customers_by_pos.at(i) == max_nearby_customers) { min_relevant_walk = std::min({min_relevant_walk, longest_walk_by_pos.at(i)}); } } assert(min_relevant_walk >= 0 && min_relevant_walk < std::numeric_limits<int>::max()); std::cout << max_nearby_customers << " " << min_relevant_walk << "\n"; bool needs_space = false; for (int i = 0; i < beach_size; i++) { if (nearby_customers_by_pos.at(i) == max_nearby_customers && longest_walk_by_pos.at(i) == min_relevant_walk) { if (needs_space) { std::cout << " "; } std::cout << i - beach_middle; needs_space = true; } } std::cout << "\n"; } int main() { std::ios_base::sync_with_stdio(false); int n; std::cin >> n; for (int i = 0; i < n; i++) { testcase(); } return 0; }
25.881188
120
0.637337
[ "vector" ]
9b32ac806abbc295ab9a63e769786ebfc113e1ba
52,168
cpp
C++
LeopardFF8.cpp
TheBlueMatt/leopard
e078197da272b2fb50d2c4eaf0216cb5cc8f05f7
[ "BSD-3-Clause" ]
2
2017-06-29T19:08:18.000Z
2021-06-27T14:22:43.000Z
LeopardFF8.cpp
TheBlueMatt/leopard
e078197da272b2fb50d2c4eaf0216cb5cc8f05f7
[ "BSD-3-Clause" ]
null
null
null
LeopardFF8.cpp
TheBlueMatt/leopard
e078197da272b2fb50d2c4eaf0216cb5cc8f05f7
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017 Christopher A. Taylor. 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 Leopard-RS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "LeopardFF8.h" #ifdef LEO_HAS_FF8 #include <string.h> #ifdef _MSC_VER #pragma warning(disable: 4752) // found Intel(R) Advanced Vector Extensions; consider using /arch:AVX #endif namespace leopard { namespace ff8 { //------------------------------------------------------------------------------ // Datatypes and Constants // Basis used for generating logarithm tables static const ffe_t kCantorBasis[kBits] = { 1, 214, 152, 146, 86, 200, 88, 230 }; // Using the Cantor basis {2} here enables us to avoid a lot of extra calculations // when applying the formal derivative in decoding. //------------------------------------------------------------------------------ // Field Operations // z = x + y (mod kModulus) static inline ffe_t AddMod(const ffe_t a, const ffe_t b) { const unsigned sum = static_cast<unsigned>(a) + b; // Partial reduction step, allowing for kModulus to be returned return static_cast<ffe_t>(sum + (sum >> kBits)); } // z = x - y (mod kModulus) static inline ffe_t SubMod(const ffe_t a, const ffe_t b) { const unsigned dif = static_cast<unsigned>(a) - b; // Partial reduction step, allowing for kModulus to be returned return static_cast<ffe_t>(dif + (dif >> kBits)); } //------------------------------------------------------------------------------ // Fast Walsh-Hadamard Transform (FWHT) (mod kModulus) // {a, b} = {a + b, a - b} (Mod Q) static LEO_FORCE_INLINE void FWHT_2(ffe_t& LEO_RESTRICT a, ffe_t& LEO_RESTRICT b) { const ffe_t sum = AddMod(a, b); const ffe_t dif = SubMod(a, b); a = sum; b = dif; } #if defined(LEO_FWHT_OPT) static LEO_FORCE_INLINE void FWHT_4(ffe_t* data, unsigned s) { const unsigned s2 = s << 1; ffe_t t0 = data[0]; ffe_t t1 = data[s]; ffe_t t2 = data[s2]; ffe_t t3 = data[s2 + s]; FWHT_2(t0, t1); FWHT_2(t2, t3); FWHT_2(t0, t2); FWHT_2(t1, t3); data[0] = t0; data[s] = t1; data[s2] = t2; data[s2 + s] = t3; } // Decimation in time (DIT) Fast Walsh-Hadamard Transform // Unrolls pairs of layers to perform cross-layer operations in registers // m_truncated: Number of elements that are non-zero at the front of data static void FWHT(ffe_t* data, const unsigned m, const unsigned m_truncated) { // Decimation in time: Unroll 2 layers at a time unsigned dist = 1, dist4 = 4; for (; dist4 <= m; dist = dist4, dist4 <<= 2) { // For each set of dist*4 elements: for (unsigned r = 0; r < m_truncated; r += dist4) { // For each set of dist elements: for (unsigned i = r; i < r + dist; ++i) FWHT_4(data + i, dist); } } // If there is one layer left: if (dist < m) for (unsigned i = 0; i < dist; ++i) FWHT_2(data[i], data[i + dist]); } #else // LEO_FWHT_OPT // Reference implementation void FWHT(ffe_t* data, const unsigned bits) { const unsigned size = (unsigned)(1UL << bits); for (unsigned width = 1; width < size; width <<= 1) for (unsigned i = 0; i < size; i += (width << 1)) for (unsigned j = i; j < (width + i); ++j) FWHT_2(data[j], data[j + width]); } #endif // LEO_FWHT_OPT //------------------------------------------------------------------------------ // Logarithm Tables static ffe_t LogLUT[kOrder]; static ffe_t ExpLUT[kOrder]; // Returns a * Log(b) static ffe_t MultiplyLog(ffe_t a, ffe_t log_b) { /* Note that this operation is not a normal multiplication in a finite field because the right operand is already a logarithm. This is done because it moves K table lookups from the Decode() method into the initialization step that is less performance critical. The LogWalsh[] table below contains precalculated logarithms so it is easier to do all the other multiplies in that form as well. */ if (a == 0) return 0; return ExpLUT[AddMod(LogLUT[a], log_b)]; } // Initialize LogLUT[], ExpLUT[] static void InitializeLogarithmTables() { // LFSR table generation: unsigned state = 1; for (unsigned i = 0; i < kModulus; ++i) { ExpLUT[state] = static_cast<ffe_t>(i); state <<= 1; if (state >= kOrder) state ^= kPolynomial; } ExpLUT[0] = kModulus; // Conversion to Cantor basis {2}: LogLUT[0] = 0; for (unsigned i = 0; i < kBits; ++i) { const ffe_t basis = kCantorBasis[i]; const unsigned width = static_cast<unsigned>(1UL << i); for (unsigned j = 0; j < width; ++j) LogLUT[j + width] = LogLUT[j] ^ basis; } for (unsigned i = 0; i < kOrder; ++i) LogLUT[i] = ExpLUT[LogLUT[i]]; // Generate Exp table from Log table: for (unsigned i = 0; i < kOrder; ++i) ExpLUT[LogLUT[i]] = i; // Note: Handles modulus wrap around with LUT ExpLUT[kModulus] = ExpLUT[0]; } //------------------------------------------------------------------------------ // Multiplies /* The multiplication algorithm used follows the approach outlined in {4}. Specifically section 6 outlines the algorithm used here for 8-bit fields. */ struct { LEO_ALIGNED LEO_M128 Value[2]; } static Multiply128LUT[kOrder]; #if defined(LEO_TRY_AVX2) struct { LEO_ALIGNED LEO_M256 Value[2]; } static Multiply256LUT[kOrder]; #endif // LEO_TRY_AVX2 static ffe_t Multiply8LUT[256 * 256]; void InitializeMultiplyTables() { if (!CpuHasSSSE3) { for (unsigned x = 0; x < 256; ++x) { ffe_t* lut = Multiply8LUT + x; if (x == 0) { for (unsigned log_y = 0; log_y < 256; ++log_y, lut += 256) lut[log_y] = 0; } else { const ffe_t log_x = LogLUT[x]; for (unsigned log_y = 0; log_y < 256; ++log_y, lut += 256) { const ffe_t prod = ExpLUT[AddMod(log_x, log_y)]; *lut = prod; } } } return; } // For each value we could multiply by: for (unsigned log_m = 0; log_m < kOrder; ++log_m) { // For each 4 bits of the finite field width in bits: for (unsigned i = 0, shift = 0; i < 2; ++i, shift += 4) { // Construct 16 entry LUT for PSHUFB uint8_t lut[16]; for (ffe_t x = 0; x < 16; ++x) lut[x] = MultiplyLog(x << shift, static_cast<ffe_t>(log_m)); // Store in 128-bit wide table const LEO_M128 *v_ptr = reinterpret_cast<const LEO_M128 *>(&lut[0]); const LEO_M128 value = _mm_loadu_si128(v_ptr); _mm_storeu_si128(&Multiply128LUT[log_m].Value[i], value); // Store in 256-bit wide table #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { _mm256_storeu_si256(&Multiply256LUT[log_m].Value[i], _mm256_broadcastsi128_si256(value)); } #endif // LEO_TRY_AVX2 } } } void mul_mem( void * LEO_RESTRICT x, const void * LEO_RESTRICT y, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32 = reinterpret_cast<LEO_M256 *>(x); const LEO_M256 * LEO_RESTRICT y32 = reinterpret_cast<const LEO_M256 *>(y); do { #define LEO_MUL_256(x_ptr, y_ptr) { \ LEO_M256 data = _mm256_loadu_si256(y_ptr); \ LEO_M256 lo = _mm256_and_si256(data, clr_mask); \ lo = _mm256_shuffle_epi8(table_lo_y, lo); \ LEO_M256 hi = _mm256_srli_epi64(data, 4); \ hi = _mm256_and_si256(hi, clr_mask); \ hi = _mm256_shuffle_epi8(table_hi_y, hi); \ _mm256_storeu_si256(x_ptr, _mm256_xor_si256(lo, hi)); } LEO_MUL_256(x32 + 1, y32 + 1); LEO_MUL_256(x32, y32); y32 += 2, x32 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 if (CpuHasSSSE3) { const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16 = reinterpret_cast<LEO_M128 *>(x); const LEO_M128 * LEO_RESTRICT y16 = reinterpret_cast<const LEO_M128 *>(y); do { #define LEO_MUL_128(x_ptr, y_ptr) { \ LEO_M128 data = _mm_loadu_si128(y_ptr); \ LEO_M128 lo = _mm_and_si128(data, clr_mask); \ lo = _mm_shuffle_epi8(table_lo_y, lo); \ LEO_M128 hi = _mm_srli_epi64(data, 4); \ hi = _mm_and_si128(hi, clr_mask); \ hi = _mm_shuffle_epi8(table_hi_y, hi); \ _mm_storeu_si128(x_ptr, _mm_xor_si128(lo, hi)); } LEO_MUL_128(x16 + 3, y16 + 3); LEO_MUL_128(x16 + 2, y16 + 2); LEO_MUL_128(x16 + 1, y16 + 1); LEO_MUL_128(x16, y16); x16 += 4, y16 += 4; bytes -= 64; } while (bytes > 0); return; } // Reference version: const ffe_t* LEO_RESTRICT lut = Multiply8LUT + log_m * 256; ffe_t * LEO_RESTRICT x1 = reinterpret_cast<ffe_t *>(x); const ffe_t * LEO_RESTRICT y1 = reinterpret_cast<const ffe_t *>(y); do { for (unsigned j = 0; j < 64; ++j) x1[j] = lut[y1[j]]; x1 += 64, y1 += 64; bytes -= 64; } while (bytes > 0); } //------------------------------------------------------------------------------ // FFT // Twisted factors used in FFT static ffe_t FFTSkew[kModulus]; // Factors used in the evaluation of the error locator polynomial static ffe_t LogWalsh[kOrder]; static void FFTInitialize() { ffe_t temp[kBits - 1]; // Generate FFT skew vector {1}: for (unsigned i = 1; i < kBits; ++i) temp[i - 1] = static_cast<ffe_t>(1UL << i); for (unsigned m = 0; m < (kBits - 1); ++m) { const unsigned step = 1UL << (m + 1); FFTSkew[(1UL << m) - 1] = 0; for (unsigned i = m; i < (kBits - 1); ++i) { const unsigned s = (1UL << (i + 1)); for (unsigned j = (1UL << m) - 1; j < s; j += step) FFTSkew[j + s] = FFTSkew[j] ^ temp[i]; } temp[m] = kModulus - LogLUT[MultiplyLog(temp[m], LogLUT[temp[m] ^ 1])]; for (unsigned i = m + 1; i < (kBits - 1); ++i) { const ffe_t sum = AddMod(LogLUT[temp[i] ^ 1], temp[m]); temp[i] = MultiplyLog(temp[i], sum); } } for (unsigned i = 0; i < kModulus; ++i) FFTSkew[i] = LogLUT[FFTSkew[i]]; // Precalculate FWHT(Log[i]): for (unsigned i = 0; i < kOrder; ++i) LogWalsh[i] = LogLUT[i]; LogWalsh[0] = 0; FWHT(LogWalsh, kOrder, kOrder); } void VectorFFTButterfly( const uint64_t bytes, unsigned count, void** x, void** y, const ffe_t log_m) { if (log_m == kModulus) { VectorXOR(bytes, count, y, x); return; } #ifdef LEO_USE_VECTOR4_OPT while (count >= 4) { fft_butterfly4( x[0], y[0], x[1], y[1], x[2], y[2], x[3], y[3], log_m, bytes); x += 4, y += 4; count -= 4; } #endif // LEO_USE_VECTOR4_OPT for (unsigned i = 0; i < count; ++i) fft_butterfly(x[i], y[i], log_m, bytes); } /* Decimation in time IFFT: The decimation in time IFFT algorithm allows us to unroll 2 layers at a time, performing calculations on local registers and faster cache memory. Each ^___^ below indicates a butterfly between the associated indices. The ifft_butterfly(x, y) operation: if (log_m != kModulus) x[] ^= exp(log(y[]) + log_m) y[] ^= x[] Layer 0: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ Layer 1: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ Layer 2: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ Layer 3: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ DIT layer 0-1 operations, grouped 4 at a time: {0-1, 2-3, 0-2, 1-3}, {4-5, 6-7, 4-6, 5-7}, DIT layer 1-2 operations, grouped 4 at a time: {0-2, 4-6, 0-4, 2-6}, {1-3, 5-7, 1-5, 3-7}, DIT layer 2-3 operations, grouped 4 at a time: {0-4, 0'-4', 0-0', 4-4'}, {1-5, 1'-5', 1-1', 5-5'}, */ void ifft_butterfly( void * LEO_RESTRICT x, void * LEO_RESTRICT y, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32 = reinterpret_cast<LEO_M256 *>(x); LEO_M256 * LEO_RESTRICT y32 = reinterpret_cast<LEO_M256 *>(y); do { #define LEO_IFFTB_256(x_ptr, y_ptr) { \ LEO_M256 x_data = _mm256_loadu_si256(x_ptr); \ LEO_M256 y_data = _mm256_loadu_si256(y_ptr); \ y_data = _mm256_xor_si256(y_data, x_data); \ _mm256_storeu_si256(y_ptr, y_data); \ LEO_M256 lo = _mm256_and_si256(y_data, clr_mask); \ lo = _mm256_shuffle_epi8(table_lo_y, lo); \ LEO_M256 hi = _mm256_srli_epi64(y_data, 4); \ hi = _mm256_and_si256(hi, clr_mask); \ hi = _mm256_shuffle_epi8(table_hi_y, hi); \ x_data = _mm256_xor_si256(x_data, _mm256_xor_si256(lo, hi)); \ _mm256_storeu_si256(x_ptr, x_data); } LEO_IFFTB_256(x32 + 1, y32 + 1); LEO_IFFTB_256(x32, y32); y32 += 2, x32 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 if (CpuHasSSSE3) { const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16 = reinterpret_cast<LEO_M128 *>(x); LEO_M128 * LEO_RESTRICT y16 = reinterpret_cast<LEO_M128 *>(y); do { #define LEO_IFFTB_128(x_ptr, y_ptr) { \ LEO_M128 x_data = _mm_loadu_si128(x_ptr); \ LEO_M128 y_data = _mm_loadu_si128(y_ptr); \ y_data = _mm_xor_si128(y_data, x_data); \ _mm_storeu_si128(y_ptr, y_data); \ LEO_M128 lo = _mm_and_si128(y_data, clr_mask); \ lo = _mm_shuffle_epi8(table_lo_y, lo); \ LEO_M128 hi = _mm_srli_epi64(y_data, 4); \ hi = _mm_and_si128(hi, clr_mask); \ hi = _mm_shuffle_epi8(table_hi_y, hi); \ x_data = _mm_xor_si128(x_data, _mm_xor_si128(lo, hi)); \ _mm_storeu_si128(x_ptr, x_data); } LEO_IFFTB_128(x16 + 3, y16 + 3); LEO_IFFTB_128(x16 + 2, y16 + 2); LEO_IFFTB_128(x16 + 1, y16 + 1); LEO_IFFTB_128(x16, y16); x16 += 4, y16 += 4; bytes -= 64; } while (bytes > 0); return; } // Reference version: const ffe_t* LEO_RESTRICT lut = Multiply8LUT + log_m * 256; xor_mem(y, x, bytes); #ifdef LEO_TARGET_MOBILE ffe_t * LEO_RESTRICT x1 = reinterpret_cast<ffe_t *>(x); ffe_t * LEO_RESTRICT y1 = reinterpret_cast<ffe_t *>(y); do { for (unsigned j = 0; j < 64; ++j) x1[j] ^= lut[y1[j]]; x1 += 64, y1 += 64; bytes -= 64; } while (bytes > 0); #else uint64_t * LEO_RESTRICT x8 = reinterpret_cast<uint64_t *>(x); ffe_t * LEO_RESTRICT y1 = reinterpret_cast<ffe_t *>(y); do { for (unsigned j = 0; j < 8; ++j) { uint64_t x_0 = x8[j]; x_0 ^= (uint64_t)lut[y1[0]]; x_0 ^= (uint64_t)lut[y1[1]] << 8; x_0 ^= (uint64_t)lut[y1[2]] << 16; x_0 ^= (uint64_t)lut[y1[3]] << 24; x_0 ^= (uint64_t)lut[y1[4]] << 32; x_0 ^= (uint64_t)lut[y1[5]] << 40; x_0 ^= (uint64_t)lut[y1[6]] << 48; x_0 ^= (uint64_t)lut[y1[7]] << 56; x8[j] = x_0; y1 += 8; } x8 += 8; bytes -= 64; } while (bytes > 0); #endif } // 4-way butterfly static void IFFT_DIT4( uint64_t bytes, void** work, unsigned dist, const ffe_t log_m01, const ffe_t log_m23, const ffe_t log_m02) { #ifdef LEO_INTERLEAVE_BUTTERFLY4_OPT #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 t01_lo = _mm256_loadu_si256(&Multiply256LUT[log_m01].Value[0]); const LEO_M256 t01_hi = _mm256_loadu_si256(&Multiply256LUT[log_m01].Value[1]); const LEO_M256 t23_lo = _mm256_loadu_si256(&Multiply256LUT[log_m23].Value[0]); const LEO_M256 t23_hi = _mm256_loadu_si256(&Multiply256LUT[log_m23].Value[1]); const LEO_M256 t02_lo = _mm256_loadu_si256(&Multiply256LUT[log_m02].Value[0]); const LEO_M256 t02_hi = _mm256_loadu_si256(&Multiply256LUT[log_m02].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT work0 = reinterpret_cast<LEO_M256 *>(work[0]); LEO_M256 * LEO_RESTRICT work1 = reinterpret_cast<LEO_M256 *>(work[dist]); LEO_M256 * LEO_RESTRICT work2 = reinterpret_cast<LEO_M256 *>(work[dist * 2]); LEO_M256 * LEO_RESTRICT work3 = reinterpret_cast<LEO_M256 *>(work[dist * 3]); do { #define LEO_IFFTB4_256(x_reg, y_reg, table_lo, table_hi) { \ LEO_M256 lo = _mm256_and_si256(y_reg, clr_mask); \ lo = _mm256_shuffle_epi8(table_lo, lo); \ LEO_M256 hi = _mm256_srli_epi64(y_reg, 4); \ hi = _mm256_and_si256(hi, clr_mask); \ hi = _mm256_shuffle_epi8(table_hi, hi); \ x_reg = _mm256_xor_si256(x_reg, _mm256_xor_si256(lo, hi)); } LEO_M256 work0_reg = _mm256_loadu_si256(work0); LEO_M256 work1_reg = _mm256_loadu_si256(work1); // First layer: work1_reg = _mm256_xor_si256(work0_reg, work1_reg); if (log_m01 != kModulus) { LEO_IFFTB4_256(work0_reg, work1_reg, t01_lo, t01_hi); } LEO_M256 work2_reg = _mm256_loadu_si256(work2); LEO_M256 work3_reg = _mm256_loadu_si256(work3); // First layer: work3_reg = _mm256_xor_si256(work2_reg, work3_reg); if (log_m23 != kModulus) { LEO_IFFTB4_256(work2_reg, work3_reg, t23_lo, t23_hi); } // Second layer: work2_reg = _mm256_xor_si256(work0_reg, work2_reg); work3_reg = _mm256_xor_si256(work1_reg, work3_reg); if (log_m02 != kModulus) { LEO_IFFTB4_256(work0_reg, work2_reg, t02_lo, t02_hi); LEO_IFFTB4_256(work1_reg, work3_reg, t02_lo, t02_hi); } _mm256_storeu_si256(work0, work0_reg); _mm256_storeu_si256(work1, work1_reg); _mm256_storeu_si256(work2, work2_reg); _mm256_storeu_si256(work3, work3_reg); work0++, work1++, work2++, work3++; bytes -= 32; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 if (CpuHasSSSE3) { const LEO_M128 t01_lo = _mm_loadu_si128(&Multiply128LUT[log_m01].Value[0]); const LEO_M128 t01_hi = _mm_loadu_si128(&Multiply128LUT[log_m01].Value[1]); const LEO_M128 t23_lo = _mm_loadu_si128(&Multiply128LUT[log_m23].Value[0]); const LEO_M128 t23_hi = _mm_loadu_si128(&Multiply128LUT[log_m23].Value[1]); const LEO_M128 t02_lo = _mm_loadu_si128(&Multiply128LUT[log_m02].Value[0]); const LEO_M128 t02_hi = _mm_loadu_si128(&Multiply128LUT[log_m02].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT work0 = reinterpret_cast<LEO_M128 *>(work[0]); LEO_M128 * LEO_RESTRICT work1 = reinterpret_cast<LEO_M128 *>(work[dist]); LEO_M128 * LEO_RESTRICT work2 = reinterpret_cast<LEO_M128 *>(work[dist * 2]); LEO_M128 * LEO_RESTRICT work3 = reinterpret_cast<LEO_M128 *>(work[dist * 3]); do { #define LEO_IFFTB4_128(x_reg, y_reg, table_lo, table_hi) { \ LEO_M128 lo = _mm_and_si128(y_reg, clr_mask); \ lo = _mm_shuffle_epi8(table_lo, lo); \ LEO_M128 hi = _mm_srli_epi64(y_reg, 4); \ hi = _mm_and_si128(hi, clr_mask); \ hi = _mm_shuffle_epi8(table_hi, hi); \ x_reg = _mm_xor_si128(x_reg, _mm_xor_si128(lo, hi)); } LEO_M128 work0_reg = _mm_loadu_si128(work0); LEO_M128 work1_reg = _mm_loadu_si128(work1); // First layer: work1_reg = _mm_xor_si128(work0_reg, work1_reg); if (log_m01 != kModulus) { LEO_IFFTB4_128(work0_reg, work1_reg, t01_lo, t01_hi); } LEO_M128 work2_reg = _mm_loadu_si128(work2); LEO_M128 work3_reg = _mm_loadu_si128(work3); // First layer: work3_reg = _mm_xor_si128(work2_reg, work3_reg); if (log_m23 != kModulus) { LEO_IFFTB4_128(work2_reg, work3_reg, t23_lo, t23_hi); } // Second layer: work2_reg = _mm_xor_si128(work0_reg, work2_reg); work3_reg = _mm_xor_si128(work1_reg, work3_reg); if (log_m02 != kModulus) { LEO_IFFTB4_128(work0_reg, work2_reg, t02_lo, t02_hi); LEO_IFFTB4_128(work1_reg, work3_reg, t02_lo, t02_hi); } _mm_storeu_si128(work0, work0_reg); _mm_storeu_si128(work1, work1_reg); _mm_storeu_si128(work2, work2_reg); _mm_storeu_si128(work3, work3_reg); work0++, work1++, work2++, work3++; bytes -= 16; } while (bytes > 0); return; } #endif // LEO_INTERLEAVE_BUTTERFLY4_OPT // First layer: if (log_m01 == kModulus) xor_mem(work[dist], work[0], bytes); else ifft_butterfly(work[0], work[dist], log_m01, bytes); if (log_m23 == kModulus) xor_mem(work[dist * 3], work[dist * 2], bytes); else ifft_butterfly(work[dist * 2], work[dist * 3], log_m23, bytes); // Second layer: if (log_m02 == kModulus) { xor_mem(work[dist * 2], work[0], bytes); xor_mem(work[dist * 3], work[dist], bytes); } else { ifft_butterfly(work[0], work[dist * 2], log_m02, bytes); ifft_butterfly(work[dist], work[dist * 3], log_m02, bytes); } } void IFFT_DIT( const uint64_t bytes, const void* const* data, const unsigned m_truncated, void** work, void** xor_result, const unsigned m, const ffe_t* skewLUT) { // FIXME: Roll into first layer if (data) { for (unsigned i = 0; i < m_truncated; ++i) memcpy(work[i], data[i], bytes); for (unsigned i = m_truncated; i < m; ++i) memset(work[i], 0, bytes); } // I tried splitting up the first few layers into L3-cache sized blocks but // found that it only provides about 5% performance boost, which is not // worth the extra complexity. // Decimation in time: Unroll 2 layers at a time unsigned dist = 1, dist4 = 4; for (; dist4 <= m; dist = dist4, dist4 <<= 2) { // For each set of dist*4 elements: for (unsigned r = 0; r < m_truncated; r += dist4) { const ffe_t log_m01 = skewLUT[r + dist]; const ffe_t log_m23 = skewLUT[r + dist * 3]; const ffe_t log_m02 = skewLUT[r + dist * 2]; // For each set of dist elements: for (unsigned i = r; i < r + dist; ++i) { IFFT_DIT4( bytes, work + i, dist, log_m01, log_m23, log_m02); } } // I tried alternating sweeps left->right and right->left to reduce cache misses. // It provides about 1% performance boost when done for both FFT and IFFT, so it // does not seem to be worth the extra complexity. // Clear data after the first layer data = nullptr; } // If there is one layer left: if (dist < m) { const ffe_t log_m = skewLUT[dist]; if (log_m == kModulus) VectorXOR(bytes, dist, work + dist, work); else { for (unsigned i = 0; i < dist; ++i) { ifft_butterfly( work[i], work[i + dist], log_m, bytes); } } } // FIXME: Roll into last layer if (xor_result) for (unsigned i = 0; i < m; ++i) xor_mem(xor_result[i], work[i], bytes); } /* Decimation in time FFT: The decimation in time FFT algorithm allows us to unroll 2 layers at a time, performing calculations on local registers and faster cache memory. Each ^___^ below indicates a butterfly between the associated indices. The fft_butterfly(x, y) operation: y[] ^= x[] if (log_m != kModulus) x[] ^= exp(log(y[]) + log_m) Layer 0: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ Layer 1: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ Layer 2: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ Layer 3: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ DIT layer 0-1 operations, grouped 4 at a time: {0-0', 4-4', 0-4, 0'-4'}, {1-1', 5-5', 1-5, 1'-5'}, DIT layer 1-2 operations, grouped 4 at a time: {0-4, 2-6, 0-2, 4-6}, {1-5, 3-7, 1-3, 5-7}, DIT layer 2-3 operations, grouped 4 at a time: {0-2, 1-3, 0-1, 2-3}, {4-6, 5-7, 4-5, 6-7}, */ void fft_butterfly( void * LEO_RESTRICT x, void * LEO_RESTRICT y, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32 = reinterpret_cast<LEO_M256 *>(x); LEO_M256 * LEO_RESTRICT y32 = reinterpret_cast<LEO_M256 *>(y); do { #define LEO_FFTB_256(x_ptr, y_ptr) { \ LEO_M256 y_data = _mm256_loadu_si256(y_ptr); \ LEO_M256 lo = _mm256_and_si256(y_data, clr_mask); \ lo = _mm256_shuffle_epi8(table_lo_y, lo); \ LEO_M256 hi = _mm256_srli_epi64(y_data, 4); \ hi = _mm256_and_si256(hi, clr_mask); \ hi = _mm256_shuffle_epi8(table_hi_y, hi); \ LEO_M256 x_data = _mm256_loadu_si256(x_ptr); \ x_data = _mm256_xor_si256(x_data, _mm256_xor_si256(lo, hi)); \ y_data = _mm256_xor_si256(y_data, x_data); \ _mm256_storeu_si256(x_ptr, x_data); \ _mm256_storeu_si256(y_ptr, y_data); } LEO_FFTB_256(x32 + 1, y32 + 1); LEO_FFTB_256(x32, y32); y32 += 2, x32 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 if (CpuHasSSSE3) { const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16 = reinterpret_cast<LEO_M128 *>(x); LEO_M128 * LEO_RESTRICT y16 = reinterpret_cast<LEO_M128 *>(y); do { #define LEO_FFTB_128(x_ptr, y_ptr) { \ LEO_M128 y_data = _mm_loadu_si128(y_ptr); \ LEO_M128 lo = _mm_and_si128(y_data, clr_mask); \ lo = _mm_shuffle_epi8(table_lo_y, lo); \ LEO_M128 hi = _mm_srli_epi64(y_data, 4); \ hi = _mm_and_si128(hi, clr_mask); \ hi = _mm_shuffle_epi8(table_hi_y, hi); \ LEO_M128 x_data = _mm_loadu_si128(x_ptr); \ x_data = _mm_xor_si128(x_data, _mm_xor_si128(lo, hi)); \ y_data = _mm_xor_si128(y_data, x_data); \ _mm_storeu_si128(x_ptr, x_data); \ _mm_storeu_si128(y_ptr, y_data); } LEO_FFTB_128(x16 + 3, y16 + 3); LEO_FFTB_128(x16 + 2, y16 + 2); LEO_FFTB_128(x16 + 1, y16 + 1); LEO_FFTB_128(x16, y16); x16 += 4, y16 += 4; bytes -= 64; } while (bytes > 0); return; } // Reference version: const ffe_t* LEO_RESTRICT lut = Multiply8LUT + log_m * 256; #ifdef LEO_TARGET_MOBILE ffe_t * LEO_RESTRICT x1 = reinterpret_cast<ffe_t *>(x); ffe_t * LEO_RESTRICT y1 = reinterpret_cast<ffe_t *>(y); do { for (unsigned j = 0; j < 64; ++j) { ffe_t x_0 = x1[j]; ffe_t y_0 = y1[j]; x_0 ^= lut[y_0]; x1[j] = x_0; y1[j] = y_0 ^ x_0; } x1 += 64, y1 += 64; bytes -= 64; } while (bytes > 0); #else uint64_t * LEO_RESTRICT x8 = reinterpret_cast<uint64_t *>(x); uint64_t * LEO_RESTRICT y8 = reinterpret_cast<uint64_t *>(y); ffe_t * LEO_RESTRICT y1 = reinterpret_cast<ffe_t *>(y); do { for (unsigned j = 0; j < 8; ++j) { uint64_t x_0 = x8[j], y_0 = y8[j]; x_0 ^= (uint64_t)lut[y1[0]]; x_0 ^= (uint64_t)lut[y1[1]] << 8; x_0 ^= (uint64_t)lut[y1[2]] << 16; x_0 ^= (uint64_t)lut[y1[3]] << 24; x_0 ^= (uint64_t)lut[y1[4]] << 32; x_0 ^= (uint64_t)lut[y1[5]] << 40; x_0 ^= (uint64_t)lut[y1[6]] << 48; x_0 ^= (uint64_t)lut[y1[7]] << 56; x8[j] = x_0, y8[j] = y_0 ^ x_0; y1 += 8; } x8 += 8, y8 += 8; bytes -= 64; } while (bytes > 0); #endif } #ifdef LEO_USE_VECTOR4_OPT void fft_butterfly4( void * LEO_RESTRICT x_0, void * LEO_RESTRICT y_0, void * LEO_RESTRICT x_1, void * LEO_RESTRICT y_1, void * LEO_RESTRICT x_2, void * LEO_RESTRICT y_2, void * LEO_RESTRICT x_3, void * LEO_RESTRICT y_3, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32_0 = reinterpret_cast<LEO_M256 *>(x_0); LEO_M256 * LEO_RESTRICT y32_0 = reinterpret_cast<LEO_M256 *>(y_0); LEO_M256 * LEO_RESTRICT x32_1 = reinterpret_cast<LEO_M256 *>(x_1); LEO_M256 * LEO_RESTRICT y32_1 = reinterpret_cast<LEO_M256 *>(y_1); LEO_M256 * LEO_RESTRICT x32_2 = reinterpret_cast<LEO_M256 *>(x_2); LEO_M256 * LEO_RESTRICT y32_2 = reinterpret_cast<LEO_M256 *>(y_2); LEO_M256 * LEO_RESTRICT x32_3 = reinterpret_cast<LEO_M256 *>(x_3); LEO_M256 * LEO_RESTRICT y32_3 = reinterpret_cast<LEO_M256 *>(y_3); do { LEO_FFTB_256(x32_0 + 1, y32_0 + 1); LEO_FFTB_256(x32_0, y32_0); y32_0 += 2, x32_0 += 2; LEO_FFTB_256(x32_1 + 1, y32_1 + 1); LEO_FFTB_256(x32_1, y32_1); y32_1 += 2, x32_1 += 2; LEO_FFTB_256(x32_2 + 1, y32_2 + 1); LEO_FFTB_256(x32_2, y32_2); y32_2 += 2, x32_2 += 2; LEO_FFTB_256(x32_3 + 1, y32_3 + 1); LEO_FFTB_256(x32_3, y32_3); y32_3 += 2, x32_3 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 if (CpuHasSSSE3) { const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16_0 = reinterpret_cast<LEO_M128 *>(x_0); LEO_M128 * LEO_RESTRICT y16_0 = reinterpret_cast<LEO_M128 *>(y_0); LEO_M128 * LEO_RESTRICT x16_1 = reinterpret_cast<LEO_M128 *>(x_1); LEO_M128 * LEO_RESTRICT y16_1 = reinterpret_cast<LEO_M128 *>(y_1); LEO_M128 * LEO_RESTRICT x16_2 = reinterpret_cast<LEO_M128 *>(x_2); LEO_M128 * LEO_RESTRICT y16_2 = reinterpret_cast<LEO_M128 *>(y_2); LEO_M128 * LEO_RESTRICT x16_3 = reinterpret_cast<LEO_M128 *>(x_3); LEO_M128 * LEO_RESTRICT y16_3 = reinterpret_cast<LEO_M128 *>(y_3); do { LEO_FFTB_128(x16_0 + 3, y16_0 + 3); LEO_FFTB_128(x16_0 + 2, y16_0 + 2); LEO_FFTB_128(x16_0 + 1, y16_0 + 1); LEO_FFTB_128(x16_0, y16_0); x16_0 += 4, y16_0 += 4; LEO_FFTB_128(x16_1 + 3, y16_1 + 3); LEO_FFTB_128(x16_1 + 2, y16_1 + 2); LEO_FFTB_128(x16_1 + 1, y16_1 + 1); LEO_FFTB_128(x16_1, y16_1); x16_1 += 4, y16_1 += 4; LEO_FFTB_128(x16_2 + 3, y16_2 + 3); LEO_FFTB_128(x16_2 + 2, y16_2 + 2); LEO_FFTB_128(x16_2 + 1, y16_2 + 1); LEO_FFTB_128(x16_2, y16_2); x16_2 += 4, y16_2 += 4; LEO_FFTB_128(x16_3 + 3, y16_3 + 3); LEO_FFTB_128(x16_3 + 2, y16_3 + 2); LEO_FFTB_128(x16_3 + 1, y16_3 + 1); LEO_FFTB_128(x16_3, y16_3); x16_3 += 4, y16_3 += 4; bytes -= 64; } while (bytes > 0); } } #endif // LEO_USE_VECTOR4_OPT static void FFT_DIT4( uint64_t bytes, void** work, unsigned dist, const ffe_t log_m01, const ffe_t log_m23, const ffe_t log_m02) { #ifdef LEO_INTERLEAVE_BUTTERFLY4_OPT if (CpuHasAVX2) { const LEO_M256 t01_lo = _mm256_loadu_si256(&Multiply256LUT[log_m01].Value[0]); const LEO_M256 t01_hi = _mm256_loadu_si256(&Multiply256LUT[log_m01].Value[1]); const LEO_M256 t23_lo = _mm256_loadu_si256(&Multiply256LUT[log_m23].Value[0]); const LEO_M256 t23_hi = _mm256_loadu_si256(&Multiply256LUT[log_m23].Value[1]); const LEO_M256 t02_lo = _mm256_loadu_si256(&Multiply256LUT[log_m02].Value[0]); const LEO_M256 t02_hi = _mm256_loadu_si256(&Multiply256LUT[log_m02].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT work0 = reinterpret_cast<LEO_M256 *>(work[0]); LEO_M256 * LEO_RESTRICT work1 = reinterpret_cast<LEO_M256 *>(work[dist]); LEO_M256 * LEO_RESTRICT work2 = reinterpret_cast<LEO_M256 *>(work[dist * 2]); LEO_M256 * LEO_RESTRICT work3 = reinterpret_cast<LEO_M256 *>(work[dist * 3]); do { #define LEO_FFTB4_256(x_reg, y_reg, table_lo, table_hi) { \ LEO_M256 lo = _mm256_and_si256(y_reg, clr_mask); \ lo = _mm256_shuffle_epi8(table_lo, lo); \ LEO_M256 hi = _mm256_srli_epi64(y_reg, 4); \ hi = _mm256_and_si256(hi, clr_mask); \ hi = _mm256_shuffle_epi8(table_hi, hi); \ x_reg = _mm256_xor_si256(x_reg, _mm256_xor_si256(lo, hi)); } LEO_M256 work0_reg = _mm256_loadu_si256(work0); LEO_M256 work2_reg = _mm256_loadu_si256(work2); LEO_M256 work1_reg = _mm256_loadu_si256(work1); LEO_M256 work3_reg = _mm256_loadu_si256(work3); // First layer: if (log_m02 != kModulus) { LEO_FFTB4_256(work0_reg, work2_reg, t02_lo, t02_hi); LEO_FFTB4_256(work1_reg, work3_reg, t02_lo, t02_hi); } work2_reg = _mm256_xor_si256(work0_reg, work2_reg); work3_reg = _mm256_xor_si256(work1_reg, work3_reg); // Second layer: if (log_m01 != kModulus) { LEO_FFTB4_256(work0_reg, work1_reg, t01_lo, t01_hi); } work1_reg = _mm256_xor_si256(work0_reg, work1_reg); _mm256_storeu_si256(work0, work0_reg); _mm256_storeu_si256(work1, work1_reg); work0++, work1++; if (log_m23 != kModulus) { LEO_FFTB4_256(work2_reg, work3_reg, t23_lo, t23_hi); } work3_reg = _mm256_xor_si256(work2_reg, work3_reg); _mm256_storeu_si256(work2, work2_reg); _mm256_storeu_si256(work3, work3_reg); work2++, work3++; bytes -= 32; } while (bytes > 0); return; } if (CpuHasSSSE3) { const LEO_M128 t01_lo = _mm_loadu_si128(&Multiply128LUT[log_m01].Value[0]); const LEO_M128 t01_hi = _mm_loadu_si128(&Multiply128LUT[log_m01].Value[1]); const LEO_M128 t23_lo = _mm_loadu_si128(&Multiply128LUT[log_m23].Value[0]); const LEO_M128 t23_hi = _mm_loadu_si128(&Multiply128LUT[log_m23].Value[1]); const LEO_M128 t02_lo = _mm_loadu_si128(&Multiply128LUT[log_m02].Value[0]); const LEO_M128 t02_hi = _mm_loadu_si128(&Multiply128LUT[log_m02].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT work0 = reinterpret_cast<LEO_M128 *>(work[0]); LEO_M128 * LEO_RESTRICT work1 = reinterpret_cast<LEO_M128 *>(work[dist]); LEO_M128 * LEO_RESTRICT work2 = reinterpret_cast<LEO_M128 *>(work[dist * 2]); LEO_M128 * LEO_RESTRICT work3 = reinterpret_cast<LEO_M128 *>(work[dist * 3]); do { #define LEO_FFTB4_128(x_reg, y_reg, table_lo, table_hi) { \ LEO_M128 lo = _mm_and_si128(y_reg, clr_mask); \ lo = _mm_shuffle_epi8(table_lo, lo); \ LEO_M128 hi = _mm_srli_epi64(y_reg, 4); \ hi = _mm_and_si128(hi, clr_mask); \ hi = _mm_shuffle_epi8(table_hi, hi); \ x_reg = _mm_xor_si128(x_reg, _mm_xor_si128(lo, hi)); } LEO_M128 work0_reg = _mm_loadu_si128(work0); LEO_M128 work2_reg = _mm_loadu_si128(work2); LEO_M128 work1_reg = _mm_loadu_si128(work1); LEO_M128 work3_reg = _mm_loadu_si128(work3); // First layer: if (log_m02 != kModulus) { LEO_FFTB4_128(work0_reg, work2_reg, t02_lo, t02_hi); LEO_FFTB4_128(work1_reg, work3_reg, t02_lo, t02_hi); } work2_reg = _mm_xor_si128(work0_reg, work2_reg); work3_reg = _mm_xor_si128(work1_reg, work3_reg); // Second layer: if (log_m01 != kModulus) { LEO_FFTB4_128(work0_reg, work1_reg, t01_lo, t01_hi); } work1_reg = _mm_xor_si128(work0_reg, work1_reg); _mm_storeu_si128(work0, work0_reg); _mm_storeu_si128(work1, work1_reg); work0++, work1++; if (log_m23 != kModulus) { LEO_FFTB4_128(work2_reg, work3_reg, t23_lo, t23_hi); } work3_reg = _mm_xor_si128(work2_reg, work3_reg); _mm_storeu_si128(work2, work2_reg); _mm_storeu_si128(work3, work3_reg); work2++, work3++; bytes -= 16; } while (bytes > 0); return; } #endif // LEO_INTERLEAVE_BUTTERFLY4_OPT // First layer: if (log_m02 == kModulus) { xor_mem(work[dist * 2], work[0], bytes); xor_mem(work[dist * 3], work[dist], bytes); } else { fft_butterfly(work[0], work[dist * 2], log_m02, bytes); fft_butterfly(work[dist], work[dist * 3], log_m02, bytes); } // Second layer: if (log_m01 == kModulus) xor_mem(work[dist], work[0], bytes); else fft_butterfly(work[0], work[dist], log_m01, bytes); if (log_m23 == kModulus) xor_mem(work[dist * 3], work[dist * 2], bytes); else fft_butterfly(work[dist * 2], work[dist * 3], log_m23, bytes); } void FFT_DIT( const uint64_t bytes, void** work, const unsigned m_truncated, const unsigned m, const ffe_t* skewLUT) { // Decimation in time: Unroll 2 layers at a time unsigned dist4 = m, dist = m >> 2; for (; dist != 0; dist4 = dist, dist >>= 2) { // For each set of dist*4 elements: for (unsigned r = 0; r < m_truncated; r += dist4) { const ffe_t log_m01 = skewLUT[r + dist]; const ffe_t log_m23 = skewLUT[r + dist * 3]; const ffe_t log_m02 = skewLUT[r + dist * 2]; // For each set of dist elements: for (unsigned i = r; i < r + dist; ++i) { FFT_DIT4( bytes, work + i, dist, log_m01, log_m23, log_m02); } } } // If there is one layer left: if (dist4 == 2) { for (unsigned r = 0; r < m_truncated; r += 2) { const ffe_t log_m = skewLUT[r + 1]; if (log_m == kModulus) xor_mem(work[r + 1], work[r], bytes); else { fft_butterfly( work[r], work[r + 1], log_m, bytes); } } } } //------------------------------------------------------------------------------ // Reed-Solomon Encode void ReedSolomonEncode( uint64_t buffer_bytes, unsigned original_count, unsigned recovery_count, unsigned m, const void* const* data, void** work) { // work <- IFFT(data, m, m) const ffe_t* skewLUT = FFTSkew + m - 1; IFFT_DIT( buffer_bytes, data, original_count < m ? original_count : m, work, nullptr, // No xor output m, skewLUT); const unsigned last_count = original_count % m; if (m >= original_count) goto skip_body; // For sets of m data pieces: for (unsigned i = m; i + m <= original_count; i += m) { data += m; skewLUT += m; // work <- work xor IFFT(data + i, m, m + i) IFFT_DIT( buffer_bytes, data, // data source m, work + m, // temporary workspace work, // xor destination m, skewLUT); } // Handle final partial set of m pieces: if (last_count != 0) { const unsigned i = original_count - last_count; data += m; skewLUT += m; // work <- work xor IFFT(data + i, m, m + i) IFFT_DIT( buffer_bytes, data, // data source last_count, work + m, // temporary workspace work, // xor destination m, skewLUT); } skip_body: // work <- FFT(work, m, 0) FFT_DIT( buffer_bytes, work, recovery_count, m, FFTSkew - 1); } //------------------------------------------------------------------------------ // ErrorBitfield #ifdef LEO_ERROR_BITFIELD_OPT // Used in decoding to decide which final FFT operations to perform class ErrorBitfield { static const unsigned kWords = kOrder / 64; uint64_t Words[7][kWords] = {}; public: LEO_FORCE_INLINE void Set(unsigned i) { Words[0][i / 64] |= (uint64_t)1 << (i % 64); } void Prepare(); LEO_FORCE_INLINE bool IsNeeded(unsigned mip_level, unsigned bit) const { if (mip_level >= 8) return true; return 0 != (Words[mip_level - 1][bit / 64] & ((uint64_t)1 << (bit % 64))); } }; static const uint64_t kHiMasks[5] = { 0xAAAAAAAAAAAAAAAAULL, 0xCCCCCCCCCCCCCCCCULL, 0xF0F0F0F0F0F0F0F0ULL, 0xFF00FF00FF00FF00ULL, 0xFFFF0000FFFF0000ULL, }; void ErrorBitfield::Prepare() { // First mip level is for final layer of FFT: pairs of data for (unsigned i = 0; i < kWords; ++i) { uint64_t w_i = Words[0][i]; const uint64_t hi2lo0 = w_i | ((w_i & kHiMasks[0]) >> 1); const uint64_t lo2hi0 = ((w_i & (kHiMasks[0] >> 1)) << 1); Words[0][i] = w_i = hi2lo0 | lo2hi0; for (unsigned j = 1, bits = 2; j < 5; ++j, bits <<= 1) { const uint64_t hi2lo_j = w_i | ((w_i & kHiMasks[j]) >> bits); const uint64_t lo2hi_j = ((w_i & (kHiMasks[j] >> bits)) << bits); Words[j][i] = w_i = hi2lo_j | lo2hi_j; } } for (unsigned i = 0; i < kWords; ++i) { uint64_t w = Words[4][i]; w |= w >> 32; w |= w << 32; Words[5][i] = w; } for (unsigned i = 0; i < kWords; i += 2) Words[6][i] = Words[6][i + 1] = Words[5][i] | Words[5][i + 1]; } #endif // LEO_ERROR_BITFIELD_OPT //------------------------------------------------------------------------------ // Reed-Solomon Decode void ReedSolomonDecode( uint64_t buffer_bytes, unsigned original_count, unsigned recovery_count, unsigned m, // NextPow2(recovery_count) unsigned n, // NextPow2(m + original_count) = work_count const void* const * const original, // original_count entries const void* const * const recovery, // recovery_count entries void** work) // n entries { // Fill in error locations #ifdef LEO_ERROR_BITFIELD_OPT ErrorBitfield ErrorBits; #endif // LEO_ERROR_BITFIELD_OPT ffe_t ErrorLocations[kOrder] = {}; for (unsigned i = 0; i < recovery_count; ++i) if (!recovery[i]) ErrorLocations[i] = 1; for (unsigned i = recovery_count; i < m; ++i) ErrorLocations[i] = 1; for (unsigned i = 0; i < original_count; ++i) { if (!original[i]) { ErrorLocations[i + m] = 1; #ifdef LEO_ERROR_BITFIELD_OPT ErrorBits.Set(i + m); #endif // LEO_ERROR_BITFIELD_OPT } } #ifdef LEO_ERROR_BITFIELD_OPT ErrorBits.Prepare(); #endif // LEO_ERROR_BITFIELD_OPT // Evaluate error locator polynomial FWHT(ErrorLocations, kOrder, m + original_count); for (unsigned i = 0; i < kOrder; ++i) ErrorLocations[i] = ((unsigned)ErrorLocations[i] * (unsigned)LogWalsh[i]) % kModulus; FWHT(ErrorLocations, kOrder, kOrder); // work <- recovery data for (unsigned i = 0; i < recovery_count; ++i) { if (recovery[i]) mul_mem(work[i], recovery[i], ErrorLocations[i], buffer_bytes); else memset(work[i], 0, buffer_bytes); } for (unsigned i = recovery_count; i < m; ++i) memset(work[i], 0, buffer_bytes); // work <- original data for (unsigned i = 0; i < original_count; ++i) { if (original[i]) mul_mem(work[m + i], original[i], ErrorLocations[m + i], buffer_bytes); else memset(work[m + i], 0, buffer_bytes); } for (unsigned i = m + original_count; i < n; ++i) memset(work[i], 0, buffer_bytes); // work <- IFFT(work, n, 0) IFFT_DIT( buffer_bytes, nullptr, m + original_count, work, nullptr, n, FFTSkew - 1); // work <- FormalDerivative(work, n) for (unsigned i = 1; i < n; ++i) { const unsigned width = ((i ^ (i - 1)) + 1) >> 1; VectorXOR( buffer_bytes, width, work + i - width, work + i); } // work <- FFT(work, n, 0) truncated to m + original_count unsigned mip_level = LastNonzeroBit32(n); const unsigned output_count = m + original_count; for (unsigned width = (n >> 1); width > 0; width >>= 1, --mip_level) { const ffe_t* skewLUT = FFTSkew + width - 1; const unsigned range = width << 1; #ifdef LEO_SCHEDULE_OPT for (unsigned j = (m < range) ? 0 : m; j < output_count; j += range) #else for (unsigned j = 0; j < n; j += range) #endif { #ifdef LEO_ERROR_BITFIELD_OPT if (!ErrorBits.IsNeeded(mip_level, j)) continue; #endif // LEO_ERROR_BITFIELD_OPT VectorFFTButterfly( buffer_bytes, width, work + j, work + j + width, skewLUT[j]); } } // Reveal erasures for (unsigned i = 0; i < original_count; ++i) if (!original[i]) mul_mem(work[i], work[i + m], kModulus - ErrorLocations[i + m], buffer_bytes); } //------------------------------------------------------------------------------ // API static bool IsInitialized = false; bool Initialize() { if (IsInitialized) return true; InitializeLogarithmTables(); InitializeMultiplyTables(); FFTInitialize(); IsInitialized = true; return true; } }} // namespace leopard::ff8 #endif // LEO_HAS_FF8
30.650999
105
0.55467
[ "vector", "transform" ]
9b38c021e30ceac1410f18e44b06d7ca233ffdd4
5,442
hpp
C++
include/mist/algorithm/TupleSpace.hpp
andbanman/mist
2546fb41bccea1f89a43dbdbed7ce3a257926b54
[ "MIT" ]
null
null
null
include/mist/algorithm/TupleSpace.hpp
andbanman/mist
2546fb41bccea1f89a43dbdbed7ce3a257926b54
[ "MIT" ]
4
2021-03-30T21:40:44.000Z
2021-11-08T18:54:34.000Z
include/mist/algorithm/TupleSpace.hpp
andbanman/mist
2546fb41bccea1f89a43dbdbed7ce3a257926b54
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <map> #include <memory> #include <set> #include <vector> #ifdef BOOST_PYTHON_EXTENSIONS #include <boost/python.hpp> namespace p = boost::python; #endif #include "../Variable.hpp" #include "it/EntropyCalculator.hpp" namespace mist { namespace algorithm { /** Interface for processing tuples in the TupleSpace * * A class can specialize the TupleSpaceTraverser to gain access to the stream * of tuples generated by TupleSpace::traverse family of functions. */ class TupleSpaceTraverser { public: using tuple_t = Variable::indexes; using count_t = std::uint64_t; virtual void process_tuple(count_t tuple_no, tuple_t const& tuple) = 0; virtual void process_tuple_entropy( count_t tuple_no, tuple_t const& tuple, it::Entropy const& e) = 0; }; /** Tuple Space defines the set of tuples over which to run a computation * search. */ class TupleSpace { public: using tuple_t = Variable::indexes; using index_t = Variable::index_t; using count_t = std::uint64_t; TupleSpace(); TupleSpace(int N, int d); ~TupleSpace(); /** Define a named logical group of variables * @param name group name * @param vars set of variables in the group, duplicates will be ignored * @return index of created variable group * @throws TupleSpaceException variable already listed in existing variable * group */ int addVariableGroup(std::string const& name, tuple_t const& vars); /** Add a variable group tuple * * The cross product of groups in the group tuple generates a set of * variable tuples that will be added to the TupleSpace by * TupleSpaceTupleProducer. * * @param groups Array of group names * @throws TupleSpaceException group does not exists */ void addVariableGroupTuple(std::vector<std::string> const& groups); /** Add a variable group tuple * * The cross product of groups in the group tuple generates a set of * variable tuples that will be added to the TupleSpace by * TupleSpaceTupleProducer. * * @param groups Array of group indexed by order created * @throws TupleSpaceException group index out of range */ void addVariableGroupTuple(tuple_t const& groups); /** Get variable names */ std::vector<std::string> names() const; /** Set variable names */ void set_names(std::vector<std::string> const& names); int tupleSize() const; #if BOOST_PYTHON_EXTENSIONS int pyAddVariableGroup(std::string const& name, p::list const& list); void pyAddVariableGroupTuple(p::list const& list); #endif /** Calculate the size of the tuple space, i.e. count the generated number of * tuples. */ count_t count_tuples() const; count_t count_tuples_group_tuple(tuple_t const&) const; tuple_t find_tuple(count_t target) const; tuple_t const& getVariableGroup(int index) const; tuple_t const& getVariableGroup(std::string const& name) const; std::vector<std::size_t> const& getVariableGroupSizes() const; tuple_t const& getVariableGroupAppearances(int index) const; std::vector<tuple_t> const& getVariableGroups() const; std::vector<tuple_t> const& getVariableGroupTuples() const; /** Walk through all tuples in the tuple space * @param traverser Process each tuple with methods defined in specialization */ void traverse(TupleSpaceTraverser& traverser) const; /** Walk through as subset of tuples in the tuple space * * TupleSpace generates an ordered list of tuples, that can begin at any * position in the list. * * @param start Begin the walk at tuple in position start * @param stop End the walk at tuple in position stop * @param traverser Process each tuple with methods defined in specialization */ void traverse(count_t start, count_t stop, TupleSpaceTraverser& traverser) const; /** Walk through all tuples in the tuple space, computing entropy values as * you go. * * Some it::Measure classes compute the entropy values of sub-tuples. It is * most efficient to compute these as you walk through the tuple space so * intermediary values can be reused many times. * * @param ecalc it::EntropyCalculator object to perform entropy computations * @param traverser Process each tuple with methods defined in specialization */ void traverse_entropy(it::EntropyCalculator &ecalc, TupleSpaceTraverser& traverser) const; /** Walk through a subset of tuples in the tuple space, computing entropy values as * you go. */ void traverse_entropy(count_t start, count_t stop, it::EntropyCalculator &ecalc, TupleSpaceTraverser& traverser) const; private: // variable names, e.g. from data header std::vector<std::string> variableNames; // groups of variables that construct a tuple std::vector<tuple_t> variableGroups; std::vector<std::size_t> variableGroupSizes; // names for the variable groups and their identifying index std::map<std::string, int> variableGroupNames; // list of groups that define variable tuples std::vector<tuple_t> variableGroupTuples; // keep track of seen variables to detect duplicates std::set<int> seen_vars; int tuple_size = 0; }; class TupleSpaceException : public std::exception { private: std::string msg; public: TupleSpaceException(std::string const& method, std::string const& msg) : msg("TupleSpace" + method + " : " + msg) {} virtual const char* what() const throw() { return msg.c_str(); }; }; } // algorithm } // mist
34.0125
121
0.73043
[ "object", "vector" ]
9b4042855f4c512ca9450a0b32f41727e4e04958
9,046
cpp
C++
ContextCommon/src/md5.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
ContextCommon/src/md5.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
ContextCommon/src/md5.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
// Copyright (c) 2007-2009 Google Inc. // Copyright (c) 2006-2007 Jaiku Ltd. // Copyright (c) 2002-2006 Mika Raento and Renaud Petit // // This software is licensed at your choice under either 1 or 2 below. // // 1. MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // 2. Gnu General Public license 2.0 // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // // This file is part of the JaikuEngine mobile client. #include "md5.h" #ifndef LSB_FIRST void byteSwap(UWORD32 *buf, unsigned words) { md5byte *p = (md5byte *)buf; do { *buf++ = (UWORD32)((unsigned)p[3] << 8 | p[2]) << 16 | ((unsigned)p[1] << 8 | p[0]); p += 4; } while (--words); } #else #define byteSwap(buf,words) #endif void md5_memcpy (void* output, const void* input, unsigned int len); void md5_memset (void* output, int value, unsigned int len); /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ EXPORT_C void MD5Init(struct MD5Context *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bytes[0] = 0; ctx->bytes[1] = 0; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ EXPORT_C void MD5Update(struct MD5Context *ctx, md5byte const *buf, unsigned len) { UWORD32 t; /* Update byte count */ t = ctx->bytes[0]; if ((ctx->bytes[0] = t + len) < t) ctx->bytes[1]++; /* Carry from low to high */ t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */ if (t > len) { md5_memcpy((md5byte *)ctx->in + 64 - t, buf, len); return; } /* First chunk is an odd size */ md5_memcpy((md5byte *)ctx->in + 64 - t, buf, t); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); buf += t; len -= t; /* Process data in 64-byte chunks */ while (len >= 64) { md5_memcpy(ctx->in, buf, 64); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ md5_memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ EXPORT_C void MD5Final(md5byte digest[16], struct MD5Context *ctx) { int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */ md5byte *p = (md5byte *)ctx->in + count; /* Set the first char of padding to 0x80. There is always room. */ *p++ = 0x80; /* Bytes of padding needed to make 56 bytes (-8..55) */ count = 56 - 1 - count; if (count < 0) { /* Padding forces an extra block */ md5_memset(p, 0, count + 8); byteSwap(ctx->in, 16); MD5Transform(ctx->buf, ctx->in); p = (md5byte *)ctx->in; count = 56; } md5_memset(p, 0, count); byteSwap(ctx->in, 14); /* Append length in bits and transform */ ctx->in[14] = ctx->bytes[0] << 3; ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29; MD5Transform(ctx->buf, ctx->in); byteSwap(ctx->buf, 4); md5_memcpy(digest, ctx->buf, 16); md5_memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */ } #ifndef ASM_MD5 /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f,w,x,y,z,in,s) \ (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ EXPORT_C void MD5Transform(UWORD32 buf[4], UWORD32 const in[16]) { register UWORD32 a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } #endif void md5_memcpy (void* output, const void* input, unsigned int len) { Mem::Copy(output, input, len); } /* Note: Replace "for loop" with standard memset if possible. */ void md5_memset (void* output, int value, unsigned int len) { Mem::Fill(output, len, value); }
32.894545
82
0.627239
[ "transform" ]
9b4370adcb68c70d180a676a245607bc20ad8cdc
741
cpp
C++
leetcode/140. Word Break II/tle.cpp
joycse06/LeetCode-1
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
[ "Fair" ]
1
2021-02-11T01:23:10.000Z
2021-02-11T01:23:10.000Z
leetcode/140. Word Break II/tle.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
null
null
null
leetcode/140. Word Break II/tle.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
1
2021-03-25T17:11:14.000Z
2021-03-25T17:11:14.000Z
class Solution { private: vector<string> ans; unordered_set<string> dict; void dfs(string &s, int start, string tmp) { if (start == s.size()) { ans.push_back(tmp); return; } for (int i = start; i < s.size(); ++i) { string sub = s.substr(start, i - start + 1); if (dict.find(sub) == dict.end()) continue; string next = tmp; if (next.size()) next.push_back(' '); next += sub; dfs(s, i + 1, next); } } public: vector<string> wordBreak(string s, vector<string>& wordDict) { dict = unordered_set<string>(wordDict.begin(), wordDict.end()); dfs(s, 0, ""); return ans; } };
29.64
71
0.492578
[ "vector" ]
9b45a6555fb6c80b006ad74dea1c3c4eb0731315
1,031
cpp
C++
tests/test_message_parser.cpp
pmakaruk/-Network-File-System
8fddd7d9c5d850f1e3b621481f21fe378b1e8a21
[ "MIT" ]
null
null
null
tests/test_message_parser.cpp
pmakaruk/-Network-File-System
8fddd7d9c5d850f1e3b621481f21fe378b1e8a21
[ "MIT" ]
null
null
null
tests/test_message_parser.cpp
pmakaruk/-Network-File-System
8fddd7d9c5d850f1e3b621481f21fe378b1e8a21
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <cassert> #include "./utils.hpp" #include "../libraries/core/serializers.hpp" int main() { std::vector<u_int8_t> data = std::vector<u_int8_t>{ (u_int8_t) MessageType::CLOSE_REQUEST, 0x00, 0x00, 0x00, 5, 0x69, 0x12, 0x34, 0x56, 0x78, 0x99, 0x99, 0x99, 0x99, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x00, 0x00, 0x00, 5, 1, 2, 3, 4, 5, 0x00, 0x00, 0x00, 5, 'a', 'b', 'c', 'd', 'e' }; MessageParser parser = MessageParser(data); assert(parser.readMessageType() == MessageType::CLOSE_REQUEST); assert(parser.readSize() == 5); assert(parser.readUInt8T() == 0x69); assert(parser.readInt32T() == 0x12345678); assert(parser.readUInt32T() == 0x99999999); assert(parser.readUInt64T() == 0x1234567890ABCDEF); std::vector<u_int8_t> expected_bytes = std::vector<u_int8_t>{1, 2, 3, 4, 5}; assert(parser.readBytes() == expected_bytes); std::string expected_string = "abcde"; assert(parser.readString() == expected_string); }
29.457143
78
0.659554
[ "vector" ]
9b460704bdb75b1c3bb93c251fb3c3395d81416c
1,798
cpp
C++
02_Trees/05_Disjoint_Set.cpp
premnaaath/DSA
e63598d33f52e398556b71ae92a3f9c3fe29f8a4
[ "MIT" ]
6
2021-07-10T15:09:22.000Z
2022-03-29T10:06:49.000Z
02_Trees/05_Disjoint_Set.cpp
premnaaath/DSA
e63598d33f52e398556b71ae92a3f9c3fe29f8a4
[ "MIT" ]
null
null
null
02_Trees/05_Disjoint_Set.cpp
premnaaath/DSA
e63598d33f52e398556b71ae92a3f9c3fe29f8a4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long #define deb(x) cout << #x << ": " << x << "\n" class disjointSet { private: vector<int> parent; vector<int> weight; public: disjointSet(int n) { for (int i = 0; i < n; ++i) { parent.push_back(i); weight.push_back(0); } } int collapsingFind(int node) { if (parent[node] == node) return node; parent[node] = collapsingFind(parent[node]); return parent[node]; } void weightedUnion(int node1, int node2) { int parent1 = collapsingFind(node1); int parent2 = collapsingFind(node2); if (parent[parent1] > parent[parent2]) parent[parent2] = parent1; else if (parent[parent2] > parent[parent2]) parent[parent1] = parent2; else { parent[parent2] = parent1; weight[parent1]++; } } }; void solve() { int n = 3; disjointSet ds = disjointSet(n); if (ds.collapsingFind(2) == ds.collapsingFind(3)) cout << "Same Parent\n"; else cout << "Different Parent\n"; ds.weightedUnion(2, 3); if (ds.collapsingFind(2) == ds.collapsingFind(3)) cout << "Same Parent\n"; else cout << "Different Parent\n"; if (ds.collapsingFind(1) == ds.collapsingFind(2)) cout << "Same Parent\n"; else cout << "Different Parent\n"; ds.weightedUnion(1, 2); if (ds.collapsingFind(1) == ds.collapsingFind(2)) cout << "Same Parent\n"; else cout << "Different Parent\n"; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t{1}; // cin >> t; while (t--) solve(); return 0; }
20.906977
58
0.532258
[ "vector" ]
9b46abbc49b756c528208cd6b8dcc9a5c35160e2
718
hpp
C++
include/Ball.hpp
IyadHamid/Bored
1e865548a2c2c12043a43084a6e5306a4893d45b
[ "MIT" ]
1
2021-01-27T23:46:26.000Z
2021-01-27T23:46:26.000Z
include/Ball.hpp
IyadHamid/Bored
1e865548a2c2c12043a43084a6e5306a4893d45b
[ "MIT" ]
null
null
null
include/Ball.hpp
IyadHamid/Bored
1e865548a2c2c12043a43084a6e5306a4893d45b
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics.hpp> class Ball : public sf::Drawable { public: Ball(float radius, float maxRange, sf::Vector2f pos = sf::Vector2f(0, 0), size_t points = 50); void setPhysics(float gravity, float drag, float bouncy); void setVisibility(bool visible, float timeTotal = 0); void addForce(float forceX, float forceY); void addForce(sf::Vector2f force); void tick(sf::Vector2f center, float dt); void dragScene(float dt, sf::Vector2f dPos); protected: void draw(sf::RenderTarget& target, sf::RenderStates states) const override; sf::CircleShape shape; sf::Vector2f pos, vel, force, dispVec = {0,0}; float gravity, drag, bouncy; float timeVisible, timeTotal; float radius, range; };
27.615385
95
0.732591
[ "shape" ]
9b56ae2ea29059c63d49986a1281c03c6ea2f835
4,902
hpp
C++
include/codegen/include/UnityEngine/ProBuilder/Experimental/CSG/CSG_VertexUtility.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/ProBuilder/Experimental/CSG/CSG_VertexUtility.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/ProBuilder/Experimental/CSG/CSG_VertexUtility.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:22 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: UnityEngine.ProBuilder.CSG_Vertex #include "UnityEngine/ProBuilder/CSG_Vertex.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IList`1<T> template<typename T> class IList_1; // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Skipping declaration: Vector3 because it is already included! // Skipping declaration: Color because it is already included! // Skipping declaration: Vector2 because it is already included! // Forward declaring type: Mesh class Mesh; // Forward declaring type: Transform class Transform; } // Forward declaring namespace: UnityEngine::ProBuilder namespace UnityEngine::ProBuilder { // Skipping declaration: MeshArrays because it is already included! } // Completed forward declares // Type namespace: UnityEngine.ProBuilder.Experimental.CSG namespace UnityEngine::ProBuilder::Experimental::CSG { // Autogenerated type: UnityEngine.ProBuilder.Experimental.CSG.CSG_VertexUtility class CSG_VertexUtility : public ::Il2CppObject { public: // static public System.Void GetArrays(System.Collections.Generic.IList`1<UnityEngine.ProBuilder.CSG_Vertex> vertices, UnityEngine.Vector3[] position, UnityEngine.Color[] color, UnityEngine.Vector2[] uv0, UnityEngine.Vector3[] normal, UnityEngine.Vector4[] tangent, UnityEngine.Vector2[] uv2, System.Collections.Generic.List`1<UnityEngine.Vector4> uv3, System.Collections.Generic.List`1<UnityEngine.Vector4> uv4) // Offset: 0xF7F960 static void GetArrays(System::Collections::Generic::IList_1<UnityEngine::ProBuilder::CSG_Vertex>* vertices, ::Array<UnityEngine::Vector3>*& position, ::Array<UnityEngine::Color>*& color, ::Array<UnityEngine::Vector2>*& uv0, ::Array<UnityEngine::Vector3>*& normal, ::Array<UnityEngine::Vector4>*& tangent, ::Array<UnityEngine::Vector2>*& uv2, System::Collections::Generic::List_1<UnityEngine::Vector4>*& uv3, System::Collections::Generic::List_1<UnityEngine::Vector4>*& uv4); // static public System.Void GetArrays(System.Collections.Generic.IList`1<UnityEngine.ProBuilder.CSG_Vertex> vertices, UnityEngine.Vector3[] position, UnityEngine.Color[] color, UnityEngine.Vector2[] uv0, UnityEngine.Vector3[] normal, UnityEngine.Vector4[] tangent, UnityEngine.Vector2[] uv2, System.Collections.Generic.List`1<UnityEngine.Vector4> uv3, System.Collections.Generic.List`1<UnityEngine.Vector4> uv4, UnityEngine.ProBuilder.MeshArrays attributes) // Offset: 0xF7F98C static void GetArrays(System::Collections::Generic::IList_1<UnityEngine::ProBuilder::CSG_Vertex>* vertices, ::Array<UnityEngine::Vector3>*& position, ::Array<UnityEngine::Color>*& color, ::Array<UnityEngine::Vector2>*& uv0, ::Array<UnityEngine::Vector3>*& normal, ::Array<UnityEngine::Vector4>*& tangent, ::Array<UnityEngine::Vector2>*& uv2, System::Collections::Generic::List_1<UnityEngine::Vector4>*& uv3, System::Collections::Generic::List_1<UnityEngine::Vector4>*& uv4, UnityEngine::ProBuilder::MeshArrays attributes); // static public UnityEngine.ProBuilder.CSG_Vertex[] GetVertices(UnityEngine.Mesh mesh) // Offset: 0xF7D468 static ::Array<UnityEngine::ProBuilder::CSG_Vertex>* GetVertices(UnityEngine::Mesh* mesh); // static public System.Void SetMesh(UnityEngine.Mesh mesh, System.Collections.Generic.IList`1<UnityEngine.ProBuilder.CSG_Vertex> vertices) // Offset: 0xF7DAA8 static void SetMesh(UnityEngine::Mesh* mesh, System::Collections::Generic::IList_1<UnityEngine::ProBuilder::CSG_Vertex>* vertices); // static public UnityEngine.ProBuilder.CSG_Vertex Mix(UnityEngine.ProBuilder.CSG_Vertex x, UnityEngine.ProBuilder.CSG_Vertex y, System.Single weight) // Offset: 0xF7F180 static UnityEngine::ProBuilder::CSG_Vertex Mix(UnityEngine::ProBuilder::CSG_Vertex x, UnityEngine::ProBuilder::CSG_Vertex y, float weight); // static public UnityEngine.ProBuilder.CSG_Vertex TransformVertex(UnityEngine.Transform transform, UnityEngine.ProBuilder.CSG_Vertex vertex) // Offset: 0xF7DDD8 static UnityEngine::ProBuilder::CSG_Vertex TransformVertex(UnityEngine::Transform* transform, UnityEngine::ProBuilder::CSG_Vertex vertex); }; // UnityEngine.ProBuilder.Experimental.CSG.CSG_VertexUtility } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::Experimental::CSG::CSG_VertexUtility*, "UnityEngine.ProBuilder.Experimental.CSG", "CSG_VertexUtility"); #pragma pack(pop)
74.272727
526
0.768462
[ "mesh", "object", "transform" ]
9b6dcb907ba7c2a302f57f478eaaf432183aaaaa
5,993
cpp
C++
src/io.cpp
ps142020/flinng4dense
b35e0dc35e611bb59d590e72dfabb2bb3ad5a0ce
[ "MIT" ]
null
null
null
src/io.cpp
ps142020/flinng4dense
b35e0dc35e611bb59d590e72dfabb2bb3ad5a0ce
[ "MIT" ]
null
null
null
src/io.cpp
ps142020/flinng4dense
b35e0dc35e611bb59d590e72dfabb2bb3ad5a0ce
[ "MIT" ]
null
null
null
#include "io.h" namespace flinng { void FlinngIndex::write_index(const char* fname){ FileIO idx_stream; size_t ret; short * bits; int *inds; std::vector<int> rambo_size; int lsh_size; idx_stream.fname = fname; idx_stream.fp = fopen(fname, "wb"); if (idx_stream.fp == NULL) { std::cout << "Error occured during opening index file for writing\n"; return; } //header info WRITE_VERIFY(&this->dimension, sizeof(this->dimension), 1, idx_stream); WRITE_VERIFY(&this->num_points, sizeof(this->num_points), 1, idx_stream); WRITE_VERIFY(&this->blooms_per_row, sizeof(this->blooms_per_row), 1, idx_stream); WRITE_VERIFY(&this->row_count, sizeof(this->row_count), 1, idx_stream); WRITE_VERIFY(&this->num_bins, sizeof(this->num_bins), 1, idx_stream); WRITE_VERIFY(&this->hash_repeats, sizeof(this->hash_repeats), 1, idx_stream); WRITE_VERIFY(&this->internal_hash_bits, sizeof(this->internal_hash_bits), 1, idx_stream); WRITE_VERIFY(&this->internal_hash_length, sizeof(this->internal_hash_length), 1, idx_stream); WRITE_VERIFY(&this->is_dataset_stored, sizeof(this->is_dataset_stored), 1, idx_stream); //LSH WRITE_VERIFY(&this->samsize, sizeof(this->samsize), 1, idx_stream); this->hash_family->getLSHparams(&bits, &inds); lsh_size = (this->internal_hash_bits * this->hash_repeats * this->samsize); std::cout << "bits is: " << bits << " \n"; WRITE_VERIFY(bits, sizeof(bits[0]), lsh_size, idx_stream); WRITE_VERIFY(inds, sizeof(inds[0]), lsh_size, idx_stream); //meta rambo rambo_size.resize(this->num_bins); this->getmetaRamboSizes(rambo_size.data()); //write the sizes of each rambo row WRITE_VERIFY(rambo_size.data(), sizeof(rambo_size[0]), this->num_bins, idx_stream); for (uint i = 0; i < this->num_bins; i++) { WRITE_VERIFY(this->meta_rambo[i].data(), sizeof(this->meta_rambo[0][0]), rambo_size[i], idx_stream); } //rambo array rambo_size.resize(this->hash_repeats * this->internal_hash_length); this->getRamboSizes(rambo_size.data()); //write the sizes of each rambo row WRITE_VERIFY(rambo_size.data(), sizeof(rambo_size[0]), (this->hash_repeats * this->internal_hash_length), idx_stream); for (uint i = 0; i < this->internal_hash_length * this->hash_repeats; i++) { WRITE_VERIFY(this->rambo_array[i].data(), sizeof(this->rambo_array[0][0]), rambo_size[i], idx_stream); } //bases if (this->is_dataset_stored) { WRITE_VERIFY(this->bases.data(), sizeof(this->bases[0]), (this->num_points*this->dimension), idx_stream); } fclose(idx_stream.fp); } void FlinngIndex::read_index(const char* fname){ FileIO idx_stream; size_t ret; short *bits; int *inds; int *rambo_size; int lsh_size; idx_stream.fname = fname; idx_stream.fp = fopen(fname, "rb"); if (idx_stream.fp == NULL) { std::cout << "Error occured during opening index file for reading\n"; return; } //header info READ_VERIFY(&this->dimension, sizeof(this->dimension), 1, idx_stream); READ_VERIFY(&this->num_points, sizeof(this->num_points), 1, idx_stream); READ_VERIFY(&this->blooms_per_row, sizeof(this->blooms_per_row), 1, idx_stream); READ_VERIFY(&this->row_count, sizeof(this->row_count), 1, idx_stream); READ_VERIFY(&this->num_bins, sizeof(this->num_bins), 1, idx_stream); READ_VERIFY(&this->hash_repeats, sizeof(this->hash_repeats), 1, idx_stream); READ_VERIFY(&this->internal_hash_bits, sizeof(this->internal_hash_bits), 1, idx_stream); READ_VERIFY(&this->internal_hash_length, sizeof(this->internal_hash_length), 1, idx_stream); READ_VERIFY(&this->is_dataset_stored, sizeof(this->is_dataset_stored), 1, idx_stream); //LSH READ_VERIFY(&this->samsize, sizeof(this->samsize), 1, idx_stream); this->hash_family = new LSH(this->internal_hash_bits, this->hash_repeats, this->dimension, this->samsize, false); lsh_size = (this->internal_hash_bits * this->hash_repeats * this->samsize); this->hash_family->getLSHparams(&bits, &inds); std::cout << "bits now : " << bits << "\n"; READ_VERIFY(bits, sizeof(bits[0]), lsh_size, idx_stream); READ_VERIFY(inds, sizeof(inds[0]), lsh_size, idx_stream); //meta rambo rambo_size = new int[(this->num_bins)]; this->meta_rambo = new std::vector<uint>[this->num_bins]; //write the sizes of each rambo row READ_VERIFY(rambo_size, sizeof(rambo_size[0]), (this->num_bins), idx_stream); for (uint i = 0; i < this->num_bins; i++) { std::vector<uint> rambo_buffer; rambo_buffer.resize(rambo_size[i]); READ_VERIFY(rambo_buffer.data(), sizeof(rambo_buffer[0]), rambo_size[i], idx_stream); this->meta_rambo[i] = rambo_buffer; } delete[] rambo_size; //rambo array rambo_size = new int[(this->hash_repeats * this->internal_hash_length)]; this->rambo_array = new std::vector<uint32_t>[this->hash_repeats * this->internal_hash_length]; //write the sizes of each rambo row READ_VERIFY(rambo_size, sizeof(rambo_size[0]), (this->hash_repeats * this->internal_hash_length), idx_stream); for (uint i = 0; i < this->internal_hash_length * this->hash_repeats; i++) { std::vector<uint32_t> rambo_buffer; rambo_buffer.resize(rambo_size[i]); READ_VERIFY(rambo_buffer.data(), sizeof(rambo_buffer[0]), rambo_size[i], idx_stream); this->rambo_array[i] = rambo_buffer; } //bases if (this->is_dataset_stored) { this->bases.resize(this->num_points*this->dimension); READ_VERIFY(this->bases.data(), sizeof(this->bases[0]), (this->num_points*this->dimension), idx_stream); } fclose(idx_stream.fp); delete[] rambo_size; } } //end namespace flinng
45.06015
123
0.661271
[ "vector" ]
9b715d32b02615cf1875d83e16b8433c71026a34
3,218
hpp
C++
hello/hello.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
4
2015-08-02T06:48:46.000Z
2017-10-15T14:46:35.000Z
hello/hello.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
null
null
null
hello/hello.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
null
null
null
#include <nall/nall.hpp> using namespace nall; #include <phoenix/phoenix.hpp> using namespace phoenix; #include "nthings.hpp" #include "nterra.hpp" namespace NTerra { struct device_t { camera_t camera; matrix_t projection; matrix_t view; /**** TODO: set up back-buffer (copy of NCanvas.data()) TODO: set up flip (copy back-buffer to front-buffer) TODO: rewrite render to copy front-buffer to NCanvas.data pointer) ****/ void flip() {} void setView() { view = Transform::LH::lookAt(camera.position, camera.target, vec3_t(0.0, 1.0, 0.0)); } void setProjection(const NCanvas &c) { Size z = c.size(); if (z.width>0&&z.height>0) projection = Transform::LH::PerspectiveFOV(0.78, z.width/z.height, 0.01, 1.0); else projection.identity(); } void render(NCanvas &c, const mesh_t &m) { Size z = c.size(); uint32_t col = 0x80ffffff, c2 = 0x408080ff, rad = 8; if (z.width>0&&z.height>0) { //matrix_t view = Transform::LH::lookAt(camera.position, camera.target, vec3_t(0.0, 1.0, 0.0)); //matrix_t projection = Transform::LH::PerspectiveFOV(0.78, z.width/z.height, 0.01, 1.0); matrix_t world = Transform::Rotation::YawPitchRoll(m.rotation.y, m.rotation.x, m.rotation.z)*Transform::Translate(m.position.x, m.position.y, m.position.z); matrix_t xform = world*view*projection; for (auto &f : m.faces) { vec2_t p1 = Transform::Project(m.vertices[f[0]], xform, z.width, z.height); vec2_t p2 = Transform::Project(m.vertices[f[1]], xform, z.width, z.height); vec2_t p3 = Transform::Project(m.vertices[f[2]], xform, z.width, z.height); if (abs(p1.x-p2.x)>1.0||abs(p1.y-p2.y)>1.0) c.line(p1.x, p1.y, p2.x, p2.y, col); if (abs(p2.x-p3.x)>1.0||abs(p2.y-p3.y)>1.0) c.line(p2.x, p2.y, p3.x, p3.y, col); if (abs(p3.x-p1.x)>1.0||abs(p3.y-p1.y)>1.0) c.line(p3.x, p3.y, p1.x, p1.y, col); } for (auto &v : m.vertices) { vec2_t p = Transform::Project(v, xform, z.width, z.height); c.circle((unsigned)p.x, (unsigned)p.y, rad, c2); } } } }; } struct Prog { /** program properties **/ string name; /* app name */ float version; /* app version */ /** program methods **/ void open(const string &fn); /* open a file */ void close(); /* close a file */ void interactiveMode(const char *fn); /* open the GUI */ void usage(); /* print out program usage */ void init(); /* initialize program variables */ /** constructors **/ Prog(int argc, char **argv); } *prog = nullptr; struct Win : Window { /** menus **/ Menu mFile; Item mFileOpen; Item mFileQuit; Menu mHelp; Item mHelpAbout; /** layouts **/ VerticalLayout lMain, lTab1, lTab1a, lTab2, lTab3; HorizontalLayout lT2Btns; TabFrame lTabbed; Frame fsT1; /** widgets **/ //FileEntry feFile; Label lblText, lblT2, lblT3; Button bImg, bImgText, bText; NCanvas cnSmp; unsigned clicks; /** aux **/ Spritesheet sprTabs; BrowserWindow browser; /* file browser for "Open File" functionality */ NTerra::device_t dev; NTerra::mesh_t mesh; Curve bzc; Timer tUpdater; /** proc **/ void openFile(const string &fn); void init(); void initProc(); void reflowStatic(); void reflow(); void resize(); /**** more proc ****/ void repaint(); /** constructors **/ Win(); } *win = nullptr;
30.647619
159
0.65289
[ "mesh", "render", "transform" ]
f92b41ca4333860ce4e7321f591c95007a611295
3,916
cpp
C++
mathtools/src/matrix_operator.cpp
lygbuaa/eco_tracker
d77afb97d356769bfe5f7d9cb5e96b3cf40c4601
[ "MIT" ]
14
2019-04-20T05:38:18.000Z
2021-04-08T06:30:41.000Z
mathtools/src/matrix_operator.cpp
lygbuaa/eco_tracker
d77afb97d356769bfe5f7d9cb5e96b3cf40c4601
[ "MIT" ]
2
2020-06-06T11:12:06.000Z
2020-08-10T11:27:12.000Z
mathtools/src/matrix_operator.cpp
lygbuaa/eco_tracker
d77afb97d356769bfe5f7d9cb5e96b3cf40c4601
[ "MIT" ]
7
2019-07-12T03:47:34.000Z
2021-04-08T06:44:17.000Z
#include "matrix_operator.hpp" EcoFeats operator+(const EcoFeats &feats1, const EcoFeats &feats2) { EcoFeats result; if (feats1.size() != feats2.size()) { printf("two feature size are not equal!\n"); assert(false); } // for each feature for (size_t i = 0; i < feats1.size(); i++) { std::vector<Eigen::MatrixXcf> feat_vec; // for each dimension for (size_t j = 0; j < (size_t)feats1[i].size(); j++) { Eigen::MatrixXcf temp = feats1[i][j] + feats2[i][j]; feat_vec.push_back(temp); } result.push_back(feat_vec); } return result; } EcoFeats operator-(const EcoFeats &feats1, const EcoFeats &feats2) { EcoFeats result; if (feats1.size() != feats2.size()) { printf("two feature size are not equal!\n"); assert(false); } // for each feature for (size_t i = 0; i < feats1.size(); i++) { std::vector<Eigen::MatrixXcf> feat_vec; // for each dimension for (size_t j = 0; j < (size_t)feats1[i].size(); j++) { Eigen::MatrixXcf temp = feats1[i][j] - feats2[i][j]; feat_vec.push_back(temp); } result.push_back(feat_vec); } return result; } EcoFeats operator*(const EcoFeats &feats, const float& coef) { EcoFeats result; if (feats.empty()) { return feats; } // for each feature for (size_t i = 0; i < feats.size(); i++) { std::vector<Eigen::MatrixXcf> feat_vec; // for each dimension for (size_t j = 0; j < (size_t)feats[i].size(); j++) { Eigen::MatrixXcf temp = feats[i][j] * coef; feat_vec.push_back(temp); } result.push_back(feat_vec); } return result; } std::vector<Eigen::MatrixXcf> operator+( const std::vector<Eigen::MatrixXcf>& data1, const std::vector<Eigen::MatrixXcf>& data2) { std::vector<Eigen::MatrixXcf> result; if (data1.size() != data2.size()) { printf("two data size are not equal!\n"); assert(false); } for (size_t i = 0; i < data1.size(); i++) { Eigen::MatrixXcf temp = data1[i] + data2[i]; result.push_back(temp); } return result; } std::vector<Eigen::MatrixXcf> operator-( const std::vector<Eigen::MatrixXcf>& data1, const std::vector<Eigen::MatrixXcf>& data2) { std::vector<Eigen::MatrixXcf> result; if (data1.size() != data2.size()) { printf("two data size are not equal!\n"); assert(false); } for (size_t i = 0; i < data1.size(); i++) { Eigen::MatrixXcf temp = data1[i] - data2[i]; result.push_back(temp); } return result; } std::vector<Eigen::MatrixXcf> operator*( const std::vector<Eigen::MatrixXcf>& data, const float& coef) { std::vector<Eigen::MatrixXcf> result; if (data.empty()) { printf("data is empty!\n"); return data; } // for each feature for (size_t i = 0; i < data.size(); i++) { Eigen::MatrixXcf temp = data[i] * coef; result.push_back(temp); } return result; } ECO_Train operator+(const ECO_Train& data1, const ECO_Train& data2) { ECO_Train result; if (data1.part1.size() != data2.part1.size() || data1.part2.size() != data2.part2.size()) { printf("two ECO_Train size are not equal!\n"); assert(false); } result.part1 = data1.part1 + data2.part1; result.part2 = data1.part2 + data2.part2; return result; } ECO_Train operator-(const ECO_Train& data1, const ECO_Train& data2) { ECO_Train result; if (data1.part1.size() != data2.part1.size() || data1.part2.size() != data2.part2.size()) { printf("two ECO_Train size are not equal!\n"); assert(false); } result.part1 = data1.part1 - data2.part1; result.part2 = data1.part2 - data2.part2; return result; } ECO_Train operator*(const ECO_Train& data, const float& scale) { ECO_Train result; if (data.part1.empty() || data.part2.empty()) { printf("data is empty!\n"); return data; } result.part1 = data.part1 * scale; result.part2 = data.part2 * scale; return result; }
25.933775
69
0.622063
[ "vector" ]
f930ab81a56b0b3d0dcb2fe807d87ae2d55610e2
12,714
cpp
C++
c++/src/NeuralNetwork.cpp
RyanStonebraker/Snowball
19f735d04ebd7262f500f205f22f2fe34eec2f5d
[ "MIT" ]
null
null
null
c++/src/NeuralNetwork.cpp
RyanStonebraker/Snowball
19f735d04ebd7262f500f205f22f2fe34eec2f5d
[ "MIT" ]
null
null
null
c++/src/NeuralNetwork.cpp
RyanStonebraker/Snowball
19f735d04ebd7262f500f205f22f2fe34eec2f5d
[ "MIT" ]
1
2019-06-29T02:46:27.000Z
2019-06-29T02:46:27.000Z
// NeuralNetwork.cpp // Cpp for the container class for all Snowball functionality #include "NeuralNetwork.h" #include <string> #include <fstream> #include <utility> #include "constants.h" #include "WeightedNode.h" #include <random> using std::random_device; using std::mt19937; using std::uniform_real_distribution; #include "moveGenerator.h" #include "board.h" #include <iostream> // TODO: If moves are within certain threshold (weighted value bounded between 0,1 - a percentage) // then choose random move (out of moves within threshold range) WeightedNode NeuralNetwork::generateRandomWeights() { random_device rdev; mt19937 rand_gen(rdev()); uniform_real_distribution<double> rand_weight(-1, 1); uniform_real_distribution<double> capped_weight(0, 1); WeightedNode currentWeights; currentWeights.kingingWeight = rand_weight(rand_gen); currentWeights.qualityWeight = rand_weight(rand_gen); currentWeights.availableMovesWeight = rand_weight(rand_gen); currentWeights.riskFactor = rand_weight(rand_gen); currentWeights.enemyFactor = rand_weight(rand_gen); currentWeights.randomMoveThreshold = capped_weight(rand_gen); currentWeights.depthWeight = rand_weight(rand_gen); currentWeights.riskFactor = rand_weight(rand_gen); currentWeights.riskThreshold = capped_weight(rand_gen); currentWeights.enemyFactor = rand_weight(rand_gen); currentWeights.randomMoveThreshold = capped_weight(rand_gen); return currentWeights; } NeuralNetwork::NeuralNetwork() : _gameState(GAME_RUNNING), _startingColor(COMPUTER_BLACK), _bestMoveWeight(-1), _currentMove(STARTING_BOARD_STRING), _bpsTiming(std::chrono::duration<double>::zero()), _lastDepth(0) {} void NeuralNetwork::loadStartingWeightsFromFile(const std::string & readLocation) { std::ifstream weightReader (readLocation); weightReader >> _weights; } void NeuralNetwork::loadStartingWeights(WeightedNode & startWeights) { _weights = std::move(startWeights); } void NeuralNetwork::writeWeightsToFile(const std::string & writeLocation) { std::ofstream weightWriter(writeLocation); weightWriter << _weights; } void NeuralNetwork::setMoveColor(int startingPlayer) { _startingColor = startingPlayer; } void NeuralNetwork::receiveMove(const std::string & currentMove) { _currentMove = currentMove; } std::vector<Board> NeuralNetwork::flipAllColor(std::vector<Board> validMoves) { std::transform(validMoves.begin(), validMoves.end(), validMoves.begin(), [](Board & b) { std::string flippedBoard = ""; std::string boardString = b.getBoardStateString(); int quality = b.getQuality(); std::reverse(boardString.begin(), boardString.end()); b = { boardString, quality}; for (auto & n : b.getBoardStateString()) { int piece = n - '0'; if (piece == BLACK) flippedBoard += '1'; else if (piece == RED) flippedBoard += '2'; else if (piece == BLACK_KING) flippedBoard += '3'; else if (piece == RED_KING) flippedBoard += '4'; else flippedBoard += '0'; } Board temp(flippedBoard, quality); return temp; }); return validMoves; } std::string NeuralNetwork::flipBoardColor(const std::string & board) { std::string flippedBoard = ""; for (int i = board.size() - 1; i >= 0; --i) { auto piece = board[i] - '0'; if (piece == BLACK) flippedBoard += '1'; else if (piece == RED) flippedBoard += '2'; else if (piece == BLACK_KING) flippedBoard += '3'; else if (piece == RED_KING) flippedBoard += '4'; else flippedBoard += '0'; } return flippedBoard; } double NeuralNetwork::evaluateBoard(const Board & futureState, int depthToLimit) { auto futureBoardInfo = getBoardInfo(futureState); auto computerIsBlack = _startingColor == COMPUTER_BLACK; auto redPiecesTaken = _topLevelWeights.numberOfRedPieces - futureBoardInfo.numberOfRedPieces; auto blackPiecesTaken = _topLevelWeights.numberOfBlackPieces - futureBoardInfo.numberOfBlackPieces; auto redKingsMade = futureBoardInfo.numberOfRedKings - _topLevelWeights.numberOfRedKings; auto blackKingsMade = futureBoardInfo.numberOfBlackKings - _topLevelWeights.numberOfBlackKings; auto enemyPiecesTaken = (computerIsBlack) ? redPiecesTaken : blackPiecesTaken; auto piecesLost = (computerIsBlack) ? blackPiecesTaken : redPiecesTaken; auto enemyKingsMade = (computerIsBlack) ? redKingsMade : blackKingsMade; auto kingsMade = (computerIsBlack) ? blackKingsMade : redKingsMade; auto pieceCaptureWeight = (enemyPiecesTaken - piecesLost) * _weights.qualityWeight; auto kingWeight = kingsMade * _weights.kingingWeight; auto enemyKingWeights = enemyKingsMade * _weights.enemyFactor; auto depthWeight = depthToLimit * _weights.depthWeight; auto playerPieces = (computerIsBlack) ? _topLevelWeights.numberOfBlackPieces : _topLevelWeights.numberOfRedPieces; auto enemyPieces = (computerIsBlack) ? _topLevelWeights.numberOfRedPieces : _topLevelWeights.numberOfBlackPieces; auto satisfiesThreshold = (double(enemyPieces) / double(playerPieces) < _weights.riskThreshold); if (satisfiesThreshold) { pieceCaptureWeight = (enemyPiecesTaken * 1 / (1 - _weights.riskFactor) - piecesLost) * _weights.qualityWeight; } auto raw_weight = pieceCaptureWeight + kingWeight + depthWeight + enemyKingWeights; return raw_weight; } ExpandedWeights NeuralNetwork::getBoardInfo(const Board & board) { ExpandedWeights boardWeighting; boardWeighting.numberOfRedKings = board.getRedKingCount(); boardWeighting.numberOfBlackKings = board.getBlackKingCount(); boardWeighting.numberOfRedPieces = board.getRedPieceCount(); boardWeighting.numberOfBlackPieces = board.getBlackPieceCount(); return boardWeighting; } ExpandedWeights NeuralNetwork::getBoardInfo(const std::string & minimalBoard) { Board board {minimalBoard}; ExpandedWeights boardWeighting; boardWeighting.numberOfRedKings = board.getRedKingCount(); boardWeighting.numberOfBlackKings = board.getBlackKingCount(); boardWeighting.numberOfRedPieces = board.getRedPieceCount(); boardWeighting.numberOfBlackPieces = board.getBlackPieceCount(); return boardWeighting; } bool NeuralNetwork::checkIfGameIsEnded(const std::string & currentMove) const { auto blackWon = currentMove.find("1") == std::string::npos && currentMove.find("3") == std::string::npos; if (blackWon) return true; auto redWon = currentMove.find("2") == std::string::npos && currentMove.find("4") == std::string::npos; if (redWon) return true; return false; } void NeuralNetwork::setEndCondition(const std::string & currentMove) { Board endBoard {currentMove}; if (endBoard.getBlackPieceCount() == 0) { _gameState = RED_WON; } else if (endBoard.getRedPieceCount() == 0) { _gameState = BLACK_WON; } else { _gameState = STALEMATE; } } void NeuralNetwork::evaluateChildren(int depth) { auto firstMoveSet = (_startingColor == COMPUTER_BLACK) ? spawnBlack(_currentMove) : spawnRed(_currentMove); if (firstMoveSet.size() == 0) { setEndCondition(_currentMove); return; } _topLevelWeights = getBoardInfo(_currentMove); auto enemyPlayedMove = _currentMove; for (unsigned possibleMove = 0; possibleMove < firstMoveSet.size(); ++possibleMove) { NeuronLinkedList node; node.board = firstMoveSet[possibleMove].getBoardStateString(); _children.push_back(std::make_shared<NeuronLinkedList>(node)); _children[possibleMove] = recurseSpawning(depth - 1, node, _startingColor); _children[possibleMove]->weight = sigmoid(_children[possibleMove]->weight); auto isBestMove = _children[possibleMove]->weight >= _bestMoveWeight; if (abs(_children[possibleMove]->weight - _bestMoveWeight) < _weights.randomMoveThreshold && _children[possibleMove]->board != _currentMove) { isBestMove = splitTie(); } if (isBestMove) { _bestMoveWeight = _children[possibleMove]->weight; _currentMove = _children[possibleMove]->board; if (_children[possibleMove]->weight == _bestMoveWeight && _currentMove != enemyPlayedMove) { if (_children[possibleMove]->board != _currentMove) { _currentMove = (splitTie()) ? _currentMove : _children[possibleMove]->board; if (checkIfGameIsEnded(_currentMove)) setEndCondition(_currentMove); } } } } } bool NeuralNetwork::splitTie() { random_device rdev; mt19937 rand_gen(rdev()); uniform_real_distribution<double> randomChoice(0, 1); auto chosenSide = randomChoice(rand_gen); return chosenSide >= 0.5; } // TODO: could do alpha-beta pruning by adding a "bestBoard at this level" parameter and // then only continuing if its >= to the child // OR, could just say if <= depthLeft X (could assign a percentage of the way to depth) and weight is // greater than 1 standard deviation less than bestMove, then end std::shared_ptr<NeuronLinkedList> NeuralNetwork::recurseSpawning(int depth, NeuronLinkedList parent, int color) { auto nextColor = (color == COMPUTER_BLACK) ? COMPUTER_RED : COMPUTER_BLACK; if (parent.children.size() > 0) { auto deeperParent = std::make_shared<NeuronLinkedList>(parent); for (auto i = 0; i < parent.children.size(); ++i) { deeperParent->children[i] = recurseSpawning(depth - 1, *(deeperParent->children[i]), nextColor); } parent = *deeperParent; } else { auto nextMoveSet = (color == COMPUTER_BLACK) ? spawnRed(parent.board) : spawnBlack(parent.board); for (auto & nextMove : nextMoveSet) { NeuronLinkedList nextChild; nextChild.board = nextMove.getBoardStateString(); nextChild.weight = evaluateBoard(nextMove, depth); parent.weight += nextChild.weight; parent.children.push_back(std::make_shared<NeuronLinkedList>(nextChild)); if (depth > 0) { // ALPHA-BETA PRUNING - More of a heuristic since doesn't DEFINITELY guarantee this // move cant be the best. Also, using sigmoid this much hurts. // auto startAlphaBetaDepth = 0.5; // auto cutOffPercentage = 0.5; // if (depth <= int(startAlphaBetaDepth * _weights.depth) && sigmoid(parent.weight) <= cutOffPercentage * _bestMoveWeight) // break; parent.children[parent.children.size() - 1] = recurseSpawning(depth - 1, nextChild, nextColor); } } parent.weight /= nextMoveSet.size(); } return std::make_shared<NeuronLinkedList>(parent); } double NeuralNetwork::sigmoid(double weight) { return tanh(weight); } std::vector<Board> NeuralNetwork::spawnBlack (const std::string & initBoard) { MoveGenerator moveGen; return moveGen.generateRandomMoves({initBoard}); } // Red spawning is a little confusing. First, the board is "flipped" (i.e. the string is reversed). // Then, all reds and blacks swap coloring. This way, moves are still generated on the bottom of // the board for black, but these moves are actually red moves so before spawnRed returns, it // "flips" the board back to its original state. std::vector<Board> NeuralNetwork::spawnRed (const std::string & initBoard) { MoveGenerator moveGen; Board flippedInitBoard = flipBoardColor(initBoard); auto flippedBoardMoves = moveGen.generateRandomMoves(flippedInitBoard); // TODO: This needs to be replaced with a generateRandomMoves that generates for // flippedBoards as flipping ALL red boards is really expensive. return flipAllColor(flippedBoardMoves); } std::string NeuralNetwork::getBestMove() { _bestMoveWeight = -10; _children.clear(); auto startMoveEval = std::chrono::system_clock::now(); // std::chrono::duration<double> relativeDuration = std::chrono::duration<double>::zero(); // for (auto relDepth = 2; relDepth <= _weights.depth; ++relDepth) { // if (relativeDuration.count() > MAX_TIME_LIMIT) { // std::cout << "CALLED\n"; // break; // } evaluateChildren(_weights.depth); // relativeDuration = std::chrono::system_clock::now() - startMoveEval; // } auto endMoveEval = std::chrono::system_clock::now(); _bpsTiming += endMoveEval - startMoveEval; return _currentMove; } double NeuralNetwork::getBestWeight() const { return _bestMoveWeight; } bool NeuralNetwork::gameIsOver() { if (checkIfGameIsEnded(_currentMove)) setEndCondition(_currentMove); return _gameState != 0; } std::string NeuralNetwork::getWinner() const { if (_gameState == STALEMATE) return "Draw!"; else return (_gameState == RED_WON) ? "RED WON!" : "BLACK WON!"; } double NeuralNetwork::getEvaluationTime() const { return _bpsTiming.count(); } void NeuralNetwork::clearEvaluationTime() { _bpsTiming = std::chrono::duration<double>::zero(); } void NeuralNetwork::setDepth(unsigned depth) { _weights.depth = depth; }
34.643052
146
0.728646
[ "vector", "transform" ]
f9334023dc75239a8e06b9c531524977efa8dc19
3,103
hpp
C++
libs/actor/test/test_object_pool.hpp
nousxiong/gce
722edb8c91efaf16375664d66134ecabb16e1447
[ "BSL-1.0" ]
118
2015-01-24T01:16:46.000Z
2022-03-09T07:31:21.000Z
libs/actor/test/test_object_pool.hpp
txwdyzcb/gce
722edb8c91efaf16375664d66134ecabb16e1447
[ "BSL-1.0" ]
1
2015-09-24T13:03:11.000Z
2016-12-24T04:00:59.000Z
libs/actor/test/test_object_pool.hpp
txwdyzcb/gce
722edb8c91efaf16375664d66134ecabb16e1447
[ "BSL-1.0" ]
30
2015-03-12T09:21:45.000Z
2021-12-15T01:55:08.000Z
/// /// Copyright (c) 2009-2014 Nous Xiong (348944179 at qq dot com) /// /// 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) /// /// See https://github.com/nousxiong/gce for latest version. /// #include <gce/actor/detail/object_pool.hpp> #include <gce/detail/unique_ptr.hpp> #include <string> namespace gce { class object_pool_ut { struct my_base { my_base(std::size_t index, std::string const& name) : index_(index) , name_(name) { } virtual ~my_base() { } void clear() { index_ = 0; name_.clear(); } std::size_t index_; std::string name_; }; struct my_data : public detail::object_pool<my_data, std::string>::object , public my_base { explicit my_data(std::string const& str) : my_base(0, str) , str_(str) , i_(0) , l_(0) { } ~my_data() { } void on_free() { my_base::clear(); str_.clear(); i_ = 0; l_ = 0; } void print() { //std::cout << "my_base[ index_: " << index_ << ", name_: " << name_ << " ]" << std::endl; //std::cout << "basic_object[ ]" << std::endl; //std::cout << "my_data[ str_: " << str_ << ", i_: " << i_ << ", l_: " << l_ << std::endl; } std::string str_; int i_; long l_; }; public: static void run() { std::cout << "object_pool_ut begin." << std::endl; test_freelist(); std::cout << "object_pool_ut end." << std::endl; } private: static void test_freelist() { typedef detail::object_pool<my_data, std::string> op_t; detail::unique_ptr<op_t> op(new op_t((detail::cache_pool*)0, std::string(), size_nil)); //boost::timer::auto_cpu_timer t; run_test(op.get(), true); } template <typename Op> static void run_test(Op* op, bool st) { for (std::size_t i=0; i<10; ++i) { { my_data* md = op->get(); md->str_ = "md"; md->index_ = 1; //md->print(); op->free(md); if (st) { BOOST_ASSERT(md->str_.empty()); BOOST_ASSERT(md->name_.empty()); BOOST_ASSERT(md->index_ == 0); } } for (std::size_t j=0; j<100; ++j) { std::vector<my_data*> my_data_list(1000, (my_data*)0); for (std::size_t i=0; i<my_data_list.size(); ++i) { my_data* md = op->get(); md->str_ = "md_list"; md->index_ = i; BOOST_ASSERT(md->str_ == "md_list"); BOOST_ASSERT(md->name_.empty()); BOOST_ASSERT(md->index_ == i); //md->print(); my_data_list[i] = md; } for (std::size_t i=0; i<my_data_list.size(); ++i) { my_data* md = my_data_list[i]; //md->print(); op->free(md); BOOST_ASSERT(md->str_.empty()); BOOST_ASSERT(md->name_.empty()); BOOST_ASSERT(md->index_ == 0); } my_data_list.clear(); } } } }; }
21.548611
96
0.515308
[ "object", "vector" ]
f933ebdc4845d5dbea8d761177069e527222c586
1,976
cpp
C++
ImportantExample/ObjectInspectorDemo/objectinspector/model/transformpropertynode.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/ObjectInspectorDemo/objectinspector/model/transformpropertynode.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/ObjectInspectorDemo/objectinspector/model/transformpropertynode.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
#include "transformpropertynode.h" #include <QTransform> TransformPropertyNode::TransformPropertyNode(QObject *parent): PropertyTreeNode(parent) { setExpandable(true); PropertyTreeNode * node; for(int i=0;i<9;i++) { node = new PropertyTreeNode; node->setType(detailedNode); node->setValue(0.0); fmatrix[i]=node; insertChild(node); } fmatrix[0]->setObjectName("m11"); fmatrix[1]->setObjectName("m12"); fmatrix[2]->setObjectName("m13"); fmatrix[3]->setObjectName("m21"); fmatrix[4]->setObjectName("m22"); fmatrix[5]->setObjectName("m23"); fmatrix[6]->setObjectName("m31"); fmatrix[7]->setObjectName("m32"); fmatrix[8]->setObjectName("m33"); setValue(QTransform()); } QString TransformPropertyNode::stringValue() { QTransform ftransform = value().value<QTransform>(); return QString("[%1 %2 %3][%4 %5 %6][%7 %8 %9]") .arg(ftransform.m11()).arg(ftransform.m12()).arg(ftransform.m13()) .arg(ftransform.m21()).arg(ftransform.m22()).arg(ftransform.m23()) .arg(ftransform.m31()).arg(ftransform.m32()).arg(ftransform.m33()); } TreeNode::NodeType TransformPropertyNode::type() const { return propertyNode; } void TransformPropertyNode::updateValue() { QTransform transform = value().value<QTransform>(); fmatrix[0]->setValue(transform.m11()); fmatrix[1]->setValue(transform.m12()); fmatrix[2]->setValue(transform.m13()); fmatrix[3]->setValue(transform.m21()); fmatrix[4]->setValue(transform.m22()); fmatrix[5]->setValue(transform.m23()); fmatrix[6]->setValue(transform.m31()); fmatrix[7]->setValue(transform.m32()); fmatrix[8]->setValue(transform.m33()); } void TransformPropertyNode::populateProperties() { for(int i=0;i<9;i++) { fmatrix[i]->setWritable(metaProperty().isWritable()); fmatrix[i]->setResetable(metaProperty().isResettable()); } }
28.228571
79
0.641194
[ "transform" ]
f93e4d08b918c90d8a80c784a61bc257c80bb923
6,309
cpp
C++
Drag/SecondCase.cpp
GEslinger/PhysClass
5e34167c34ca0e8779e4002063d95ffa24a24c9d
[ "BSD-2-Clause" ]
null
null
null
Drag/SecondCase.cpp
GEslinger/PhysClass
5e34167c34ca0e8779e4002063d95ffa24a24c9d
[ "BSD-2-Clause" ]
null
null
null
Drag/SecondCase.cpp
GEslinger/PhysClass
5e34167c34ca0e8779e4002063d95ffa24a24c9d
[ "BSD-2-Clause" ]
null
null
null
#include <gnuplot-iostream/gnuplot-iostream.h> #include <boost/tuple/tuple.hpp> #include <iostream> #include <iomanip> #include <functional> #include <vector> #include <cmath> #include "Tools.hpp" #define PI 3.14159265 using namespace std; /*********************************************************************** Second Case: 2D drag! DragObject2D is a class for a point particle in 2D coordinates. Instead of individual accessor methods like Euler1D, getAttrs returns a vector of the four instance variables. The Euler step and updating code is all built in as well. A frequently used data type in this program is vector<vector<double>>, usually called path. The data stored is a vector of x values and y values in a projectile's trajectory, ex. {{x1,x2,x3...},{y1,y2,y3...}}. Passing a data type like this around is much easier than writing two methods or using evil libraries to make functions return multiple values. The getPath function takes an initial x and y velocity and performs the Euler method on an instance of DragObject2D, saving the x and y values in vectors. It simulates until a sign change is detected in y, meaning the object has returned to the ground. For that reason, making v_i negative is a bad idea. After simulation, the function returns a path. plotPath just plots the path given with axes of path[0], path[1]. RangeVAngle is more complicated, as it performs all calculation and plots the range vs. angle graph. It iterates from -pi/2 to pi/2 with a step size of dth. For each iteration, it gets the path with getPath. The final x value is the range when the object returns to the ground, by the definition of the getPath function. ***********************************************************************/ const double v_i = 10; // Initial velocity for both the trajectory and the range v. angle plot const double th = PI/6; // Firing angle for the trajectory plot const double y_0 = 1; // Global starting height, Should be either zero or something positive, as the range vs. angle graph must be complete. const double g = 9.8; // Gravitational acceleration (negative) const double b = 0;//.56832; // Calculated drag constant for Syd Miyasaki const double dt = 0.001; // Timestep const double dth = 0.001; // Step in angle for the range v. angle plot class DragObject2D{ // Problem-specific class public: DragObject2D(double vx_0, double vy_0); // Constructor vector<double> getAttrs() const; // Accessor method for instance variables double getSpeed() const; // Accessor / calculation method for speed void update(); // Euler step and updating private: double x, y, vx, vy; }; DragObject2D::DragObject2D(double vx_0, double vy_0){ // Constructor sets x to zero, y to starting height, initial velocities as arguments x = 0; y = y_0; vx = vx_0; vy = vy_0; } vector<double> DragObject2D::getAttrs() const { // Usage of anonymously declared vectors to return all instance variables return vector<double>{x,y,vx,vy}; } double DragObject2D::getSpeed() const { // *trivial* mechanics (component velocity to speed) return sqrt(vx*vx + vy*vy); } void DragObject2D::update(){ // Update all the things! double v = this->getSpeed();// Get speed on the current object instance. "this" returns a pointer to the instance, and -> is an abbreviation of (*this).getSpeed() x += vx*dt; // Update x and y y += vy*dt; vx += -(b*v*vx)*dt; // Euler step for x and y vy += -(g+b*v*vy)*dt; } vector<vector<double>> getPath(double vx_0, double vy_0){ // Get the path thing vector<double> x_n; // Vectors for the path vector<double> y_n; double yval = 0; // The value of y DragObject2D object(vx_0, vy_0);// The object to track while(yval >= 0){ // Only track until the object hits the ground vector<double> attrs = object.getAttrs(); // Get attributes (x, y, vx, vy) x_n.push_back(attrs[0]); // Add attributes to vectors, update y value y_n.push_back(attrs[1]); yval = attrs[1]; object.update(); // Perform Euler step and updates } return vector<vector<double>>{x_n,y_n}; // Return the two vectors of x and y together } void plotPath(vector<vector<double>>& path){ // Plot the path; pretty basic stuff Gnuplot gp; gp << setprecision(3); gp << "set xrange [0:" << path[0].back() << "]\n"; gp << "set yrange [0:" << getMaxVal(path[1])*1.1 << "]\n"; gp << "set format y \"%.1f\"\n"; gp << "set term png size 720,480 font \"FreeSerif,12\"\n"; gp << "set xlabel \"x (m)\"\n"; gp << "set ylabel \"y (m)\"\n"; gp << "set title \"Trajectory of Syd Under Rayleigh's Drag Equation\\nb = " << b; gp << ", v_i = " << v_i << ", {/Symbol q}_i = " << th << "\"\n"; gp << "set output \"Trajectory.png\"\n"; gp << "plot '-' with dots lc rgb \"black\" notitle\n"; gp.send1d(boost::make_tuple(path[0],path[1])); } void rangeVAngle(){ // Calculation and plotting of the range vs. angle plot vector<double> ranges; // Declare vectors vector<double> angles; for(double ang = -PI/2; ang < PI/2; ang += dth){ // From -pi/2 to pi/2, steps of dth double vx_0 = v_i*cos(ang); // From v_i and ang, determine the initial velocities double vy_0 = v_i*sin(ang); vector<vector<double>> path = getPath(vx_0, vy_0); // Generate path double range = path[0].back(); // The last x value is the range angles.push_back(ang); // Save angle and range ranges.push_back(range); } Gnuplot gp; // Now plot! gp << setprecision(3); gp << "set xrange [" << -PI/2 << ":" << PI/2 << "]\n"; gp << "set yrange [0:" << getMaxVal(ranges)*1.1 << "]\n"; gp << "set format y \"%.1f\"\n"; gp << "set term png size 720,480 font \"FreeSerif,12\"\n"; gp << "set xlabel \"angle (rad)\"\n"; gp << "set ylabel \"range (m)\"\n"; gp << "set title \"Range vs. Firing Angle of Syd Under Rayleigh's Drag Equation, b = " << b << "\"\n"; gp << "set output \"RangeAngle.png\"\n"; gp << "plot '-' with dots lc rgb \"black\" notitle\n"; gp.send1d(boost::make_tuple(angles,ranges)); } int main(){ // Main function double vx_0 = v_i*cos(th); // Use v_i and the launch angle th to determine initial velocities by components double vy_0 = v_i*sin(th); vector<vector<double>> path = getPath(vx_0, vy_0); // Generate the path plotPath(path); // Plot it rangeVAngle(); // And make the range vs. angle plot! return 0; // If it all worked, return 0 }
38.944444
163
0.671263
[ "object", "vector" ]
f946f154e9c370b85c23f644e02824e194906f3e
597
cpp
C++
dp/Matrix_Chain_Multiplication/MCM.cpp
N9199/apuntes_icpc
198571d3d516d09e5418ab51893b400bceb01acd
[ "MIT" ]
1
2020-03-06T20:32:33.000Z
2020-03-06T20:32:33.000Z
dp/Matrix_Chain_Multiplication/MCM.cpp
N9199/apuntes_icpc
198571d3d516d09e5418ab51893b400bceb01acd
[ "MIT" ]
null
null
null
dp/Matrix_Chain_Multiplication/MCM.cpp
N9199/apuntes_icpc
198571d3d516d09e5418ab51893b400bceb01acd
[ "MIT" ]
null
null
null
#include "../../headers/headers.h" int inline op(int a, int b) { return (a + b) % 100; } int inline cost(int a, int b) { return a * b; } vector<vector<ll>> DP; vector<vector<int>> A; // Minimize on [i,j] ll func(int i, int j) { if (DP[i][j] != -1) return DP[i][j]; ll temp, ans = 1e9; repx(k, i, j) { temp = cost(A[i][k], A[k + 1][j]) + func(i, k) + func(k + 1, j); ans = min(ans, temp); } return DP[i][j] = ans; } void inline fill() { rep(i, A.size()) repx(j, i + 1, A.size()) A[i][j] = op(A[i][j - 1], A[j][j]); } // Call func(0, DP.size()-1)
23.88
100
0.489112
[ "vector" ]
f94f3b655ffbb1829d7fc58ddc9915654ccba415
5,969
cpp
C++
Test/TestTopDown.cpp
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
2
2020-09-10T19:14:20.000Z
2021-09-11T16:36:56.000Z
Test/TestTopDown.cpp
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
null
null
null
Test/TestTopDown.cpp
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
3
2020-09-11T01:19:47.000Z
2021-09-02T02:05:01.000Z
#include "TestTopDown.h" #include "../EngineLayer/CommonParameters.h" #include "../EngineLayer/PrecursorSearchModes/SinglePpmAroundZeroMassDiffAcceptor.h" #include "../TaskLayer/MetaMorpheusTask.h" #include "../EngineLayer/PeptideSpectralMatch.h" using namespace EngineLayer; using namespace EngineLayer::ClassicSearch; using namespace EngineLayer::Indexing; using namespace EngineLayer::ModernSearch; using namespace IO::MzML; using namespace MzLibUtil; using namespace NUnit::Framework; using namespace Proteomics; using namespace Proteomics::ProteolyticDigestion; using namespace TaskLayer; using namespace UsefulProteomicsDatabases; namespace Test { void TestTopDown::TestClassicSearchEngineTopDown() { DigestionParams tempVar(protease: L"top-down"); CommonParameters *CommonParameters = new CommonParameters(digestionParams: &tempVar, scoreCutoff: 1, assumeOrphanPeaksAreZ1Fragments: false); auto variableModifications = std::vector<Modification*>(); auto fixedModifications = std::vector<Modification*>(); auto proteinList = std::vector<Protein*> {new Protein(L"MPKVYSYQEVAEHNGPENFWIIIDDKVYDVSQFKDEHPGGDEIIMDLGGQDATESFVDIGHSDEALRLLKGLYIGDVDKTSERVSVEKVSTSENQSKGSGTLVVILAILMLGVAYYLLNE", L"P40312")}; auto myMsDataFile = Mzml::LoadAllStaticData(FileSystem::combine(TestContext::CurrentContext->TestDirectory, LR"(TopDownTestData\slicedTDYeast.mzML)")); auto searchMode = new SinglePpmAroundZeroSearchMode(5); bool DoPrecursorDeconvolution = true; bool UseProvidedPrecursorInfo = false; double DeconvolutionIntensityRatio = 4; int DeconvolutionMaxAssumedChargeState = 60; Tolerance *DeconvolutionMassTolerance = new PpmTolerance(5); CommonParameters tempVar2(); auto listOfSortedms2Scans = MetaMorpheusTask::GetMs2Scans(myMsDataFile, L"", &tempVar2).OrderBy([&] (std::any b) { b::PrecursorMass; })->ToArray(); std::vector<PeptideSpectralMatch*> allPsmsArray(listOfSortedms2Scans.size()); ClassicSearchEngine tempVar3(allPsmsArray, listOfSortedms2Scans, variableModifications, fixedModifications, proteinList, searchMode, CommonParameters, new std::vector<std::wstring>()); (&tempVar3)->Run(); auto psm = allPsmsArray.Where([&] (std::any p) { delete DeconvolutionMassTolerance; //C# TO C++ CONVERTER TODO TASK: A 'delete searchMode' statement was not added since searchMode was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete CommonParameters' statement was not added since CommonParameters was passed to a method or constructor. Handle memory management manually. return p != nullptr; }).FirstOrDefault(); Assert::That(psm->MatchedFragmentIons->Count > 50); delete DeconvolutionMassTolerance; //C# TO C++ CONVERTER TODO TASK: A 'delete searchMode' statement was not added since searchMode was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete CommonParameters' statement was not added since CommonParameters was passed to a method or constructor. Handle memory management manually. } void TestTopDown::TestModernSearchEngineTopDown() { DigestionParams tempVar(protease: L"top-down"); CommonParameters *CommonParameters = new CommonParameters(digestionParams: &tempVar, scoreCutoff: 1, assumeOrphanPeaksAreZ1Fragments: false); auto variableModifications = std::vector<Modification*>(); auto fixedModifications = std::vector<Modification*>(); auto proteinList = std::vector<Protein*> {new Protein(L"MPKVYSYQEVAEHNGPENFWIIIDDKVYDVSQFKDEHPGGDEIIMDLGGQDATESFVDIGHSDEALRLLKGLYIGDVDKTSERVSVEKVSTSENQSKGSGTLVVILAILMLGVAYYLLNE", L"P40312")}; auto myMsDataFile = Mzml::LoadAllStaticData(FileSystem::combine(TestContext::CurrentContext->TestDirectory, LR"(TopDownTestData\slicedTDYeast.mzML)")); auto searchMode = new SinglePpmAroundZeroSearchMode(5); bool DoPrecursorDeconvolution = true; bool UseProvidedPrecursorInfo = false; double DeconvolutionIntensityRatio = 4; int DeconvolutionMaxAssumedChargeState = 60; Tolerance *DeconvolutionMassTolerance = new PpmTolerance(5); CommonParameters tempVar2(); auto listOfSortedms2Scans = MetaMorpheusTask::GetMs2Scans(myMsDataFile, L"", &tempVar2).OrderBy([&] (std::any b) { b::PrecursorMass; })->ToArray(); std::vector<PeptideSpectralMatch*> allPsmsArray(listOfSortedms2Scans.size()); auto indexEngine = new IndexingEngine(proteinList, variableModifications, fixedModifications, 1, DecoyType::Reverse, CommonParameters, 30000, false, std::vector<FileInfo*>(), std::vector<std::wstring>()); auto indexResults = static_cast<IndexingResults*>(indexEngine->Run()); ModernSearchEngine tempVar3(allPsmsArray, listOfSortedms2Scans, indexResults->getPeptideIndex(), indexResults->getFragmentIndex(), 0, CommonParameters, searchMode, 0, new std::vector<std::wstring>()); (&tempVar3)->Run(); auto psm = allPsmsArray.Where([&] (std::any p) { delete indexEngine; delete DeconvolutionMassTolerance; //C# TO C++ CONVERTER TODO TASK: A 'delete searchMode' statement was not added since searchMode was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete CommonParameters' statement was not added since CommonParameters was passed to a method or constructor. Handle memory management manually. return p != nullptr; }).FirstOrDefault(); Assert::That(psm->MatchedFragmentIons->Count > 50); delete indexEngine; delete DeconvolutionMassTolerance; //C# TO C++ CONVERTER TODO TASK: A 'delete searchMode' statement was not added since searchMode was passed to a method or constructor. Handle memory management manually. //C# TO C++ CONVERTER TODO TASK: A 'delete CommonParameters' statement was not added since CommonParameters was passed to a method or constructor. Handle memory management manually. } }
52.359649
207
0.774502
[ "vector" ]
f9563f56d8f162af855fd20ffda9e6196f5ccdcf
4,232
cpp
C++
Game/Game/Sprite.cpp
nguyenlamlll/directx-game
984942291a8dda1b6814dda9fc26215f067b9228
[ "MIT" ]
1
2021-02-17T13:06:38.000Z
2021-02-17T13:06:38.000Z
Game/Game/Sprite.cpp
nguyenlamlll/directx-game
984942291a8dda1b6814dda9fc26215f067b9228
[ "MIT" ]
26
2019-09-28T09:02:09.000Z
2019-12-27T07:24:22.000Z
Game/Game/Sprite.cpp
nguyenlamlll/directx-game
984942291a8dda1b6814dda9fc26215f067b9228
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Sprite.h" bool Sprite::IsRect(RECT rect) { if (rect.left == rect.right) return false; if (rect.top == rect.bottom) return false; return true; } Sprite::Sprite() { //Default the m_sprite to m_position (0, 0, 0) m_position.x = 0; m_position.y = 0; m_position.z = 0; //When color is set to white, what you see is exactly what the image looks like. color = D3DCOLOR_ARGB(255, 255, 255, 255); //We are not initialized yet initialized = false; } Sprite::Sprite(LPCWSTR filePath) : Sprite(filePath, 0) { } Sprite::Sprite(LPCWSTR filePath, D3DCOLOR transparentColor) { //Default the m_sprite to m_position (0, 0, 0) m_position.x = 0; m_position.y = 0; m_position.z = 0; //When color is set to white, what you see is exactly what the image looks like. color = D3DCOLOR_ARGB(255, 255, 255, 255); D3DXIMAGE_INFO info; HRESULT result = D3DXGetImageInfoFromFile(filePath, &info); if (result != D3D_OK) { DebugHelper::DebugOut(L"[ERROR] GetImageInfoFromFile failed: %s\n", filePath); OutputDebugStringW(filePath); return; } m_textureWidth = info.Width; m_textureHeight = info.Height; m_sourceRect.left = 0; m_sourceRect.right = info.Width; m_sourceRect.top = 0; m_sourceRect.bottom = info.Height; result = D3DXCreateTextureFromFileEx( Global::GetInstance()->g_DirectDevice, // Pointer to Direct3D device object filePath, // Path to the image to load info.Width, // Texture width info.Height, // Texture height 1, D3DUSAGE_DYNAMIC, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, transparentColor, //D3DCOLOR_XRGB(255, 255, 255), // Transparent color &info, NULL, &m_texture); // Created texture pointer if (result != D3D_OK) { OutputDebugString(L"[ERROR] CreateTextureFromFile failed\n"); return; } DebugHelper::DebugOut(L"[INFO] Texture loaded Ok: %s \n", filePath); m_sprite = GLOBAL->g_SpriteHandler; m_center = D3DXVECTOR3((float)m_textureWidth / 2, (float)m_textureHeight / 2, 0);; } void Sprite::Draw() { if (m_sprite && m_texture) { D3DXMATRIX mt; D3DXMatrixIdentity(&mt); mt._41 = -(float)(Camera::getInstance()->getPosition().x - GLOBAL->g_ScreenWidth / 2); mt._42 = -(float)(Camera::getInstance()->getPosition().y - GLOBAL->g_ScreenHeight/2); D3DXVECTOR4 transformedPos; D3DXVECTOR3 drawingPosition((float)m_position.x, (float)m_position.y, 0); D3DXVec3Transform(&transformedPos, &drawingPosition, &mt); D3DXVECTOR3 p = { transformedPos.x, transformedPos.y, 0 }; D3DXMATRIX old, m; //temp var //D3DXMatrixIdentity(&m); Global::GetInstance()->g_SpriteHandler->GetTransform(&old); //Save the old matrix //Flip image if exist if (m_flipHorizontal) { D3DXMatrixScaling(&m, m_scale.x * -1, m_scale.y * 1, m_scale.z * 1); p.x *= -1.0f; Global::GetInstance()->g_SpriteHandler->SetTransform(&m); } else { D3DXMatrixScaling(&m, m_scale.x, m_scale.y, m_scale.z); Global::GetInstance()->g_SpriteHandler->SetTransform(&m); } if (m_flipVertical) { D3DXMatrixScaling(&m, m_scale.x * 1, m_scale.y * -1, m_scale.z * 1); p.y *= -1.0f; Global::GetInstance()->g_SpriteHandler->SetTransform(&m); } m_center.x = m_textureWidth / 2; m_center.y = m_textureHeight / 2; m_sprite->Draw( m_texture, &m_sourceRect, &m_center, &p, color); //Reset to old matrix Global::GetInstance()->g_SpriteHandler->SetTransform(&old); //m_sprite->End(); } } void Sprite::DrawOnScreen() { if (m_sprite && m_texture) { D3DXMATRIX old; //temp var Global::GetInstance()->g_SpriteHandler->GetTransform(&old); //Save the old matrix D3DXMATRIX matScale; D3DXMatrixScaling(&matScale, m_scale.x, m_scale.y, m_scale.z); Global::GetInstance()->g_SpriteHandler->SetTransform(&matScale); m_center.x = m_textureWidth / 2; m_center.y = m_textureHeight / 2; m_sprite->Draw( m_texture, &m_sourceRect, &m_center, &m_position, color); //Reset to old matrix Global::GetInstance()->g_SpriteHandler->SetTransform(&old); } } Sprite::~Sprite() { //if (m_sprite) //{ // m_sprite->Release(); // m_sprite = 0; //} if (m_texture) { m_texture->Release(); m_texture = 0; } }
22.752688
88
0.68242
[ "object" ]
f95993a995ac2efdd2be5426a5218a9c403cb7b4
1,355
cpp
C++
bfs.cpp
rakshitraj/lol
c490916f74f1bdbd4d62a86c279c496417cf2e81
[ "MIT" ]
null
null
null
bfs.cpp
rakshitraj/lol
c490916f74f1bdbd4d62a86c279c496417cf2e81
[ "MIT" ]
null
null
null
bfs.cpp
rakshitraj/lol
c490916f74f1bdbd4d62a86c279c496417cf2e81
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <queue> using namespace std; std::vector<vector<int>> vec; std::vector<bool> visited; void bfs(int node){ std::queue<int> lst; lst.push(node); visited[node] = true; while(!lst.empty()) { node = lst.front(); lst.pop(); cout << "\nVisited: " << node; for (int i = 0; i < vec[node].size(); i++) { if ( ! visited[vec[node][i]] ) { lst.push(vec[node][i]); visited[vec[node][i]] = true; } } } } void init_visited(){ // Initialize visited vector for (int i=0; i<visited.size(); i++) { visited[i] = false; } } int main() { int nodes, edges; int x[] = {1,1,2,2,3,4,4,5,5,6,6,8}; int y[] = {2,4,3,4,6,5,6,7,9,7,8,10}; // setting default values for graph nodes = 10; edges = 12; vec.resize(nodes + 1); visited.resize(nodes + 1); // Create adjacency matrix for (int i=0; i<edges; i++) { vec[x[i]].push_back(y[i]); vec[y[i]].push_back(x[i]); } init_visited(); int start; cout << "Enter starting node: "; cin >> start; if( start>0 && start <11) { cout << "\nBFS -->\n"; bfs(start); } else cout << "\nNo such node.\n"; return 0; }
17.828947
50
0.478967
[ "vector" ]
f96c289669ec0dd88bb6186099a6f6f996665179
38,081
cpp
C++
src/CameraProcessor.cpp
hamlyn-centre/daVinciToolTrack
01f1a17abbe2859b70e323780ec69a112a8c7d7c
[ "BSD-3-Clause" ]
2
2017-08-25T14:11:18.000Z
2021-09-07T11:47:34.000Z
src/CameraProcessor.cpp
magnumye/daVinciToolTrack
01f1a17abbe2859b70e323780ec69a112a8c7d7c
[ "BSD-3-Clause" ]
null
null
null
src/CameraProcessor.cpp
magnumye/daVinciToolTrack
01f1a17abbe2859b70e323780ec69a112a8c7d7c
[ "BSD-3-Clause" ]
6
2017-08-16T16:19:08.000Z
2020-08-05T06:13:20.000Z
#include "simulator.h" #include "CameraProcessor.h" #include "ShapeContextPro.h" void decompose_rotation_xyz(const cv::Mat &R, double& thetaX, double& thetaY, double& thetaZ); void compose_rotation(const double &thetaX, const double &thetaY, const double &thetaZ, cv::Mat &R); CameraProcessor::CameraProcessor(double fx, double fy, double px, double py, int w, int h, const cv::Mat& cHw_, const cv::Mat& cHw2_, const std::vector<cv::Scalar>& LND_partcolors, const std::map<std::string, int>& LND_partname2ids): Fx(fx), Fy(fy), Px(px), Py(py), width(w), height(h), show_kine (false) { tool_partcolors.resize(LND_partcolors.size()); std::copy(LND_partcolors.begin(), LND_partcolors.end(), tool_partcolors.begin()); tool_partname2ids.insert(LND_partname2ids.begin(), LND_partname2ids.end()); qgo_detector = new QGODetector(); ekFilter_psm1 = NULL; ekFilter_psm2 = NULL; camera_img_id = 0; cHw_.copyTo(cHw); cHw2_.copyTo(cHw2); corr_T = cv::Mat::eye(4, 4, CV_64F); corr_T2 = cv::Mat::eye(4, 4, CV_64F); T_cam_need_set = false; T2_cam_need_set = false; corr_T_cam = cv::Mat::eye(4, 4, CV_64F); corr_T2_cam = cv::Mat::eye(4, 4, CV_64F); low_num_threshold_psm1 = 3; high_num_threshold_psm1= 6; low_num_threshold_psm2 = 3; high_num_threshold_psm2= 6; QObject::connect(&timer_, &QTimer::timeout, this, &CameraProcessor::process); } CameraProcessor::~CameraProcessor() { if (qgo_detector != NULL) delete qgo_detector; if (ekFilter_psm1 != NULL) delete ekFilter_psm1; if (ekFilter_psm2 != NULL) delete ekFilter_psm2; } void CameraProcessor::set_simulator(Simulator* sim) { simulator_ = sim; } void CameraProcessor::start() { timer_.start(20); timer_.moveToThread(&thread_); this->moveToThread(&thread_); thread_.start(); } void CameraProcessor::show_kinematics(bool checked) { show_kine = checked; } void CameraProcessor::process() { /////////////////////////////////// // From global to local cv::Mat render_img_flip_cv_local, camera_image_local; Eigen::Matrix<double, 4, 4, Eigen::RowMajor> psm1_bHe_local, psm1_bHj4_local, psm1_bHj5_local; Eigen::Matrix<double, 4, 4, Eigen::RowMajor> psm2_bHe_local, psm2_bHj4_local, psm2_bHj5_local; float psm1_jaw_local, psm2_jaw_local; std::vector<cv::Rect> psm1_part_boxes_local; std::vector<std::string> psm1_class_names_local; std::vector<cv::Point2f> psm1_projectedKeypoints_local; std::vector<cv::Point3f> psm1_allKeypoints_no_corr_local; std::vector<cv::Rect> psm2_part_boxes_local; std::vector<std::string> psm2_class_names_local; std::vector<cv::Point2f> psm2_projectedKeypoints_local; std::vector<cv::Point3f> psm2_allKeypoints_no_corr_local; std::vector<int> psm1_template_half_sizes_local; std::vector<int> psm2_template_half_sizes_local; float psm1_slope_local; float psm2_slope_local; if(!(simulator_->ReadVirtualRenderingOutput(render_img_flip_cv_local, camera_image_local, psm1_part_boxes_local, psm1_class_names_local, psm1_projectedKeypoints_local, psm1_allKeypoints_no_corr_local, psm1_template_half_sizes_local, psm2_part_boxes_local, psm2_class_names_local, psm2_projectedKeypoints_local, psm2_allKeypoints_no_corr_local, psm2_template_half_sizes_local, psm1_bHe_local, psm1_bHj4_local, psm1_bHj5_local, psm2_bHe_local, psm2_bHj4_local, psm2_bHj5_local, psm1_jaw_local, psm2_jaw_local, psm1_slope_local, psm2_slope_local))) return; // Add templates to QGO detector. cv::Mat quantized_angle; cv::Mat magnitude; std::vector<cv::Rect> psm1_bounding_boxes, psm2_bounding_boxes; std::vector<bool> psm1_states, psm2_states; qgo_detector->addDualTemplateSet(render_img_flip_cv_local, psm2_part_boxes_local, psm2_class_names_local, psm1_part_boxes_local, psm1_class_names_local, quantized_angle, magnitude, psm2_bounding_boxes, psm1_bounding_boxes, psm2_states, psm1_states); // Perform matching using available templates. bool T_cam_set = false; bool T2_cam_set = false; process_camera(psm1_allKeypoints_no_corr_local, psm1_projectedKeypoints_local, psm2_allKeypoints_no_corr_local, psm2_projectedKeypoints_local, psm1_template_half_sizes_local, psm2_template_half_sizes_local, camera_image_local, corr_T, corr_T2, T_cam_set, T2_cam_set, camera_img_id); if (T_cam_set) { T_cam_need_set = true; corr_T.copyTo(corr_T_cam); } if (T2_cam_set) { T2_cam_need_set = true; corr_T2.copyTo(corr_T2_cam); } simulator_->WriteCameraOutput(T_cam_need_set, T2_cam_need_set, corr_T_cam, corr_T2_cam); camera_img_id++; if (show_kine) draw_skel(camera_image_local, cHw, psm1_bHj4_local, psm1_bHj5_local, psm1_bHe_local, psm1_jaw_local, false, 1); draw_skel(camera_image_local, cHw, psm1_bHj4_local, psm1_bHj5_local, psm1_bHe_local, psm1_jaw_local, corr_T, 1, psm1_slope_local); if (show_kine) draw_skel(camera_image_local, cHw2, psm2_bHj4_local, psm2_bHj5_local, psm2_bHe_local, psm2_jaw_local, false, 2); draw_skel(camera_image_local, cHw2, psm2_bHj4_local, psm2_bHj5_local, psm2_bHe_local, psm2_jaw_local, corr_T2, 2, psm2_slope_local); #ifdef __linux__ // Linux ROS specific // Framerate calculation timeval t_curr; gettimeofday(&t_curr, NULL); time_count.push_back(t_curr); // if (time_count.size() > 100) { // time_count.pop_front(); double td = time_diff(&time_count.front(), &time_count.back()); double fps = time_count.size()/td; std::stringstream str; str << setprecision(4) << fps; Q_EMIT dispFrameRate("Processing FPS: " + QString::number(fps)); cv::putText(camera_image_local, "FPS: "+str.str(), cv::Point(5,15), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0) ); } #endif #ifdef _WIN32 time_t t_curr; time(&t_curr); time_count.push_back(t_curr); if (time_count.size() > 100) { time_count.pop_front(); double td = difftime(time_count.back(), time_count.front()); Q_EMIT dispFrameRate("Processing FPS: " + QString::number(100.0/td)); } #endif QImage qtemp_camera = cvtCvMat2QImage(camera_image_local); Q_EMIT updateCameraImage(qtemp_camera); } bool CameraProcessor::process_camera(const std::vector<cv::Point3f>& psm1_allKeypoints, const std::vector<cv::Point2f>& psm1_projectedKeypoints, const std::vector<cv::Point3f>& psm2_allKeypoints, const std::vector<cv::Point2f>& psm2_projectedKeypoints, const std::vector<int>& ra_template_half_sizes, const std::vector<int>& la_template_half_sizes, cv::Mat& camera_image, cv::Mat& psm1_err_T, cv::Mat& psm2_err_T, bool& T_cam_set, bool& T2_cam_set, int img_id) { cv::Mat rectify_left; camera_image.copyTo(rectify_left); std::vector<Match> psm1_matches, psm2_matches; std::vector<std::string> psm1_class_ids, psm2_class_ids; cv::Mat quantized_angles, quantized_display, magnitude; qgo_detector->match(rectify_left, 30, psm2_matches, psm2_class_ids, psm1_matches, psm1_class_ids, quantized_angles, magnitude, img_id); //std::cout << matches.size() << " " << similarities.size() << std::endl; //qgo_detector->colormap(quantized_angles, quantized_display); //quantized_display.copyTo(camera_image); bool psm1_shaft_visible = false; bool psm2_shaft_visible = false; cv::Point psm1_shaft_centre, psm2_shaft_centre; // PSM1 { std::vector<cv::Point2f> verifiedCamerapoints_t; std::vector<std::string> verifiedNames_t; if (psm1_matches.size() > 0) shape_context_verification(camera_image, psm1_matches, psm1_projectedKeypoints, verifiedCamerapoints_t, verifiedNames_t, ra_template_half_sizes); std::cout << "PSM1: " << verifiedCamerapoints_t.size() << std::endl; std::vector<cv::Point2f> verifiedCamerapoints; std::vector<std::string> verifiedNames; for (int ci = 0; ci < verifiedCamerapoints_t.size(); ci++) { verifiedCamerapoints.push_back(verifiedCamerapoints_t[ci]); verifiedNames.push_back(verifiedNames_t[ci]); if (verifiedNames_t[ci] == "shaft_centre") { psm1_shaft_visible = true; psm1_shaft_centre = verifiedCamerapoints_t[ci]; } } if ((int)verifiedCamerapoints.size() > low_num_threshold_psm1 || img_id == 0) { if (show_kine) for (int il = 0; il < verifiedCamerapoints.size(); il++) { cv::circle(camera_image, verifiedCamerapoints[il], 5, tool_partcolors[tool_partname2ids[verifiedNames[il]]], -1, CV_AA); } // Solve pnp cv::Mat rvec, tvec; bool pose_good = false; if (ekFilter_psm1 == NULL && (int)verifiedCamerapoints.size() > high_num_threshold_psm1) { cv::Mat subP = cv::Mat::eye(3, 3, CV_32FC1); subP.at<float>(0,0) = Fx; subP.at<float>(1,1) = Fy; subP.at<float>(0,2) = Px; subP.at<float>(1,2) = Py; cv::Mat distCoeffs; std::vector<cv::Point3f> model3dPoints; for (int ci = 0; ci < verifiedCamerapoints.size(); ci++) { model3dPoints.push_back(psm1_allKeypoints[tool_partname2ids[verifiedNames[ci]]]); } pose_good = cv::solvePnP(model3dPoints, verifiedCamerapoints, subP, distCoeffs, rvec, tvec, false, CV_EPNP); //std::cout << tvec << std::endl; //cv::Mat inliers; pose_good = true; //cv::solvePnPRansac(model3dPoints, verifiedCamerapoints, subP, distCoeffs, rvec, tvec, false, 100, 3.0, 7, inliers, CV_ITERATIVE); std::vector<cv::Point2f> projected2dPoints; if (pose_good) { cv::projectPoints(psm1_allKeypoints, rvec, tvec, subP, distCoeffs, projected2dPoints); } // Experimental if (!psm1_shaft_visible) pose_good = false; // if shaft centre not exist, don't trust } if (ekFilter_psm1 == NULL) { if (pose_good) { int state_dimension = 6, measure_dimension = psm1_allKeypoints.size()*2; cv::Mat init_state = cv::Mat::zeros(state_dimension, 1, CV_64F); cv::Mat rot_mat; cv::Rodrigues(rvec, rot_mat); double theta_x, theta_y, theta_z; decompose_rotation_xyz(rot_mat, theta_x, theta_y, theta_z); init_state.at<double>(0,0) = theta_x; init_state.at<double>(1,0) = theta_y; init_state.at<double>(2,0) = theta_z; init_state.at<double>(3,0) = tvec.at<double>(0,0); init_state.at<double>(4,0) = tvec.at<double>(1,0); init_state.at<double>(5,0) = tvec.at<double>(2,0); initEKFPSM1(state_dimension, measure_dimension, state_dimension, measure_dimension, init_state); cv::Mat temp = psm1_err_T(cv::Rect(0,0,3,3)); compose_rotation(theta_x, theta_y, theta_z, temp); psm1_err_T.at<double>(0,3) = tvec.at<double>(0,0); psm1_err_T.at<double>(1,3) = tvec.at<double>(1,0); psm1_err_T.at<double>(2,3) = tvec.at<double>(2,0); std::cout<< psm1_err_T << std::endl; T_cam_set = true; } } else// EKF process { // Step 1. Estimate state ekFilter_psm1->Calc_x_estimated(); // Step 2. Estiamte error covariance ekFilter_psm1->Calc_P_estimated(); // Step 3. Compute Kalman gain std::vector<double> x_estimate; ekFilter_psm1->Get_x_estimated(x_estimate); cv::Mat H, z_estimated; calc_H_z_estiamted(psm1_allKeypoints, x_estimate, Fx, Fy, Px, Py, H, z_estimated); Eigen::MatrixXd H_ = cvMat2Eigen(H); ekFilter_psm1->Set_H(H_); ekFilter_psm1->Calc_S(); ekFilter_psm1->Calc_K(); // Step 4. Update estimate with measurement cv::Mat z = cv::Mat::zeros(psm1_allKeypoints.size()*2, 1, CV_64F); std::vector<bool> z_valid(psm1_allKeypoints.size()*2, false); //assert(psm1_allKeypoints.size() == verifiedCamerapoints_t.size()); for (int ci = 0; ci < verifiedCamerapoints_t.size(); ci++) { int vid = tool_partname2ids[verifiedNames_t[ci]] * 2; z_valid[vid] = true; z_valid[vid+1] = true; z.at<double>(vid, 0) = verifiedCamerapoints_t[ci].x; z.at<double>(vid+1, 0) = verifiedCamerapoints_t[ci].y; } //std::cout << "z_measured" << std::endl; //std::cout << z << std::endl; Eigen::MatrixXd z_ = cvMat2Eigen(z), z_estimated_ = cvMat2Eigen(z_estimated); ekFilter_psm1->Set_z(z_); ekFilter_psm1->Set_z_estimated(z_estimated_); //ekFilter->Calc_x_corrected(); ekFilter_psm1->Calc_x_corrected(z_valid); std::vector<double> x_corrected; ekFilter_psm1->Get_x_corrected(x_corrected); // Step 5. Update error covariance ekFilter_psm1->Calc_P_corrected(); // Step 6. Finish for next loop ekFilter_psm1->Finish_for_next(); cv::Mat temp = psm1_err_T(cv::Rect(0,0,3,3)); compose_rotation(x_corrected[0], x_corrected[1], x_corrected[2], temp); psm1_err_T.at<double>(0,3) = x_corrected[3]; psm1_err_T.at<double>(1,3) = x_corrected[4]; psm1_err_T.at<double>(2,3) = x_corrected[5]; } } } // PSM2 { std::vector<cv::Point2f> verifiedCamerapoints_t; std::vector<std::string> verifiedNames_t; if (psm2_matches.size() > 0) shape_context_verification(camera_image, psm2_matches, psm2_projectedKeypoints, verifiedCamerapoints_t, verifiedNames_t, la_template_half_sizes); std::cout << "PSM2: " << verifiedCamerapoints_t.size() << std::endl; std::vector<cv::Point2f> verifiedCamerapoints; std::vector<std::string> verifiedNames; for (int ci = 0; ci < verifiedCamerapoints_t.size(); ci++) { verifiedCamerapoints.push_back(verifiedCamerapoints_t[ci]); verifiedNames.push_back(verifiedNames_t[ci]); if (verifiedNames_t[ci] == "shaft_centre") { psm2_shaft_visible = true; psm2_shaft_centre = verifiedCamerapoints_t[ci]; } } if ((int)verifiedCamerapoints.size() > low_num_threshold_psm2 || img_id == 0) { if (show_kine) for (int il = 0; il < verifiedCamerapoints.size(); il++) { cv::circle(camera_image, verifiedCamerapoints[il], 5, tool_partcolors[tool_partname2ids[verifiedNames[il]]], -1, CV_AA); } // Solve pnp cv::Mat rvec, tvec; bool pose_good = false; if (ekFilter_psm2 == NULL && (int)verifiedCamerapoints.size() > high_num_threshold_psm2) { cv::Mat subP = cv::Mat::eye(3, 3, CV_32FC1); subP.at<float>(0,0) = Fx; subP.at<float>(1,1) = Fy; subP.at<float>(0,2) = Px; subP.at<float>(1,2) = Py; cv::Mat distCoeffs; std::vector<cv::Point3f> model3dPoints; for (int ci = 0; ci < verifiedCamerapoints.size(); ci++) { model3dPoints.push_back(psm2_allKeypoints[tool_partname2ids[verifiedNames[ci]]]); } pose_good = cv::solvePnP(model3dPoints, verifiedCamerapoints, subP, distCoeffs, rvec, tvec, false, CV_EPNP); //std::cout << tvec << std::endl; //cv::Mat inliers; pose_good = true; //cv::solvePnPRansac(model3dPoints, verifiedCamerapoints, subP, distCoeffs, rvec, tvec, false, 100, 3.0, 7, inliers, CV_ITERATIVE); std::vector<cv::Point2f> projected2dPoints; if (pose_good) { cv::projectPoints(psm2_allKeypoints, rvec, tvec, subP, distCoeffs, projected2dPoints); } // Experimental if (!psm2_shaft_visible) pose_good = false; // if shaft centre not exist, don't trust } if (ekFilter_psm2 == NULL) { if (pose_good) { int state_dimension = 6, measure_dimension = psm2_allKeypoints.size()*2; cv::Mat init_state = cv::Mat::zeros(state_dimension, 1, CV_64F); cv::Mat rot_mat; cv::Rodrigues(rvec, rot_mat); double theta_x, theta_y, theta_z; decompose_rotation_xyz(rot_mat, theta_x, theta_y, theta_z); init_state.at<double>(0,0) = theta_x; init_state.at<double>(1,0) = theta_y; init_state.at<double>(2,0) = theta_z; init_state.at<double>(3,0) = tvec.at<double>(0,0); init_state.at<double>(4,0) = tvec.at<double>(1,0); init_state.at<double>(5,0) = tvec.at<double>(2,0); initEKFPSM2(state_dimension, measure_dimension, state_dimension, measure_dimension, init_state); cv::Mat temp = psm2_err_T(cv::Rect(0,0,3,3)); compose_rotation(theta_x, theta_y, theta_z, temp); psm2_err_T.at<double>(0,3) = tvec.at<double>(0,0); psm2_err_T.at<double>(1,3) = tvec.at<double>(1,0); psm2_err_T.at<double>(2,3) = tvec.at<double>(2,0); std::cout<< psm2_err_T << std::endl; T2_cam_set = true; } } else// EKF process { // Step 1. Estimate state ekFilter_psm2->Calc_x_estimated(); // Step 2. Estiamte error covariance ekFilter_psm2->Calc_P_estimated(); // Step 3. Compute Kalman gain std::vector<double> x_estimate; ekFilter_psm2->Get_x_estimated(x_estimate); //std::cout << "x_estimate: " << x_estimate[3] << "," << x_estimate[4] << "," << x_estimate[5] << std::endl; cv::Mat H, z_estimated; calc_H_z_estiamted(psm2_allKeypoints, x_estimate, Fx, Fy, Px, Py, H, z_estimated); Eigen::MatrixXd H_ = cvMat2Eigen(H); ekFilter_psm2->Set_H(H_); ekFilter_psm2->Calc_S(); ekFilter_psm2->Calc_K(); // Step 4. Update estimate with measurement cv::Mat z = cv::Mat::zeros(psm2_allKeypoints.size()*2, 1, CV_64F); //assert(psm2_allKeypoints.size() == verifiedCamerapoints_t.size()); std::vector<bool> z_valid(psm2_allKeypoints.size()*2, false); for (int ci = 0; ci < verifiedCamerapoints_t.size(); ci++) { int vid = tool_partname2ids[verifiedNames_t[ci]] * 2; z_valid[vid] = true; z_valid[vid+1] = true; z.at<double>(vid, 0) = verifiedCamerapoints_t[ci].x; z.at<double>(vid+1, 0) = verifiedCamerapoints_t[ci].y; } //std::cout << "z_measured" << std::endl; //std::cout << z << std::endl; //std::cout << "z_estimated" << std::endl; //std::cout << z_estimated << std::endl; Eigen::MatrixXd z_ = cvMat2Eigen(z), z_estimated_ = cvMat2Eigen(z_estimated); ekFilter_psm2->Set_z(z_); ekFilter_psm2->Set_z_estimated(z_estimated_); //ekFilter->Calc_x_corrected(); ekFilter_psm2->Calc_x_corrected(z_valid); std::vector<double> x_corrected; ekFilter_psm2->Get_x_corrected(x_corrected); // Step 5. Update error covariance ekFilter_psm2->Calc_P_corrected(); // Step 6. Finish for next loop ekFilter_psm2->Finish_for_next(); cv::Mat temp = psm2_err_T(cv::Rect(0,0,3,3)); compose_rotation(x_corrected[0], x_corrected[1], x_corrected[2], temp); //std::cout << "x_corrected: " << x_corrected[3] << "," << x_corrected[4] << "," << x_corrected[5] << std::endl; psm2_err_T.at<double>(0,3) = x_corrected[3]; psm2_err_T.at<double>(1,3) = x_corrected[4]; psm2_err_T.at<double>(2,3) = x_corrected[5]; } } } return true; } void CameraProcessor::shape_context_verification(cv::Mat& img, const std::vector<Match>& matches, const std::vector<cv::Point2f>& projectedKeypoints, std::vector<cv::Point2f>& verifiedCamerapoints, std::vector<std::string>& verifiedNames, const std::vector<int>& template_half_sizes) { // Shape Context Verification std::vector<ProsacPoint2f> pointsA; std::vector<ProsacPoint2f> pointsB; pointsA.reserve(matches. size()); pointsB.reserve(matches.size()); std::vector<double> scores; scores.reserve(matches.size()); std::vector<int> landmarkIds; landmarkIds.reserve(matches.size()); std::vector<int> detectionIds; detectionIds.reserve(matches.size()); for (int mh = 0; mh < matches.size(); mh++) { ProsacPoint2f pt1 = {projectedKeypoints[tool_partname2ids[matches[mh].class_id]].x, projectedKeypoints[tool_partname2ids[matches[mh].class_id]].y}; ProsacPoint2f pt2 = {matches[mh].x+template_half_sizes[tool_partname2ids[matches[mh].class_id]], matches[mh].y+template_half_sizes[tool_partname2ids[matches[mh].class_id]]}; pointsA.push_back(pt1); pointsB.push_back(pt2); scores.push_back(matches[mh].similarity); landmarkIds.push_back(tool_partname2ids[matches[mh].class_id]); detectionIds.push_back(mh); } SCConfig config = {2, 500}; ShapeContextPro scp(config); scp.SetData(&pointsA, &pointsB, &landmarkIds); scp.SetDetectionIds(&detectionIds); scp.SetScores(&scores); scp.ComputeModel(); const int& numInliers = scp.GetBestNumInliers(); std::vector<bool> inliers; if (numInliers > 3) { inliers = scp.GetBestInliers(); for (int il = 0; il < inliers.size(); il++) { if (inliers[il]) { cv::Point2f pt(matches[il].x+template_half_sizes[tool_partname2ids[matches[il].class_id]], matches[il].y+template_half_sizes[tool_partname2ids[matches[il].class_id]]); verifiedCamerapoints.push_back(pt); verifiedNames.push_back(matches[il].class_id); } } } //std::cout << scp.GetBestNumInliers() << std::endl; } void CameraProcessor::calc_H_z_estiamted(const std::vector<cv::Point3f>& kpts_cstar, const std::vector<double>& state_estimated, double f_x, double f_y, double d_x, double d_y, cv::Mat& H, cv::Mat& z_estimated) { double theta_x = state_estimated[0]; double theta_y = state_estimated[1]; double theta_z = state_estimated[2]; double t_x = state_estimated[3]; double t_y = state_estimated[4]; double t_z = state_estimated[5]; double sx = sin(theta_x), sy = sin(theta_y), sz = sin(theta_z), cx = cos(theta_x), cy = cos(theta_y), cz = cos(theta_z); H = cv::Mat::zeros(2*(int)kpts_cstar.size(), (int)state_estimated.size(), CV_64F); z_estimated = cv::Mat::zeros(2*(int)kpts_cstar.size(), 1, CV_64F); for (int k = 0; k < kpts_cstar.size(); k++) { double c = kpts_cstar[k].x; double r = kpts_cstar[k].y; double m = kpts_cstar[k].z; double F = c*cy*cz - r*cy*sz + m*sy + t_x; double L = c*sx*sy*cz + c*cx*sz - r*sx*sy*sz + r*cx*cz - m*sx*cy + t_y; double G = -c*cx*sy*cz + c*sx*sz + r*cx*sy*sz + r*sx*cz + m*cx*cy + t_z; double G_2 = G*G; /////////// Calc z_estimated z_estimated.at<double>(2*k,0) = f_x*(F/G) + d_x; z_estimated.at<double>(2*k+1,0) = f_y*(L/G) + d_y; /////////// Calc H ///------------ double F_over_theta_x = 0; double G_over_theta_x = c*sx*sy*cz + c*cx*sz - r*sx*sy*sz + r*cx*cz - m*sx*cy; double u_over_theta_x = f_x*((F_over_theta_x*G - G_over_theta_x*F)/G_2); ///------------ double F_over_theta_y = -c*sy*cz + r*sy*sz + m*cy; double G_over_theta_y = -c*cx*cy*cz + r*cx*cy*sz - m*cx*sy; double u_over_theta_y = f_x*((F_over_theta_y*G - G_over_theta_y*F)/G_2); ///------------ double F_over_theta_z = -c*cy*sz - r*cy*cz; double G_over_theta_z = c*cx*sy*sz + c*sx*cz + r*cx*sy*cz - r*sx*sz; double u_over_theta_z = f_x*((F_over_theta_z*G - G_over_theta_z*F)/G_2); ///------------ double u_over_t_x = f_x/G; ///------------ double u_over_t_y = 0; ///------------ double u_over_t_z = -f_x*(F/G_2); ////////////////// ///------------ double L_over_theta_x = c*cx*sy*cz - c*sx*sz - r*cx*sy*sz - r*sx*cz - m*cx*cy; double v_over_theta_x = f_y*((L_over_theta_x*G - G_over_theta_x*L)/G_2); ///------------ double L_over_theta_y = c*sx*cy*cz - r*sx*cy*sz + m*sx*sy; double v_over_theta_y = f_y*((L_over_theta_y*G - G_over_theta_y*L)/G_2); ///------------ double L_over_theta_z = -c*sx*sy*sz + c*cx*cz - r*sx*sy*cz - r*cx*sz; double v_over_theta_z = f_y*((L_over_theta_z*G - G_over_theta_z*L)/G_2); ///------------ double v_over_t_x = 0; ///------------ double v_over_t_y = f_y/G; ///------------ double v_over_t_z = -f_y*(L/G_2); ///////////////// int rows = k*2; H.at<double>(rows, 0) = u_over_theta_x; H.at<double>(rows, 1) = u_over_theta_y; H.at<double>(rows, 2) = u_over_theta_z; H.at<double>(rows, 3) = u_over_t_x; H.at<double>(rows, 4) = u_over_t_y; H.at<double>(rows, 5) = u_over_t_z; rows = rows + 1; H.at<double>(rows, 0) = v_over_theta_x; H.at<double>(rows, 1) = v_over_theta_y; H.at<double>(rows, 2) = v_over_theta_z; H.at<double>(rows, 3) = v_over_t_x; H.at<double>(rows, 4) = v_over_t_y; H.at<double>(rows, 5) = v_over_t_z; } // //std::cout << "z_estimated from h(.)" << std::endl; //std::cout << z_estimated << std::endl; //cv::Mat state_estimated_M = cv::Mat::zeros(state_estimated.size(), 1, CV_64F); //state_estimated_M.at<double>(0,0) = state_estimated[0]; //state_estimated_M.at<double>(1,0) = state_estimated[1]; //state_estimated_M.at<double>(2,0) = state_estimated[2]; //state_estimated_M.at<double>(3,0) = state_estimated[3]; //state_estimated_M.at<double>(4,0) = state_estimated[4]; //state_estimated_M.at<double>(5,0) = state_estimated[5]; //std::cout << "Jacobian H" << std::endl; //std::cout << H << std::endl; //std::cout << "state_estimate" << std::endl; //std::cout << state_estimated_M << std::endl; //z_estimated = H * state_estimated_M; //std::cout << "z_estimated from H.x" << std::endl; //std::cout << z_estimated << std::endl; } Eigen::MatrixXd CameraProcessor::cvMat2Eigen(cv::Mat& m) { Eigen::MatrixXd eigen_mat = Eigen::MatrixXd::Zero(m.rows, m.cols); for (auto i = 0; i < m.cols; i++) { for (auto j = 0; j < m.rows; j++) { eigen_mat(j, i) = m.at<double>(j, i); } } return eigen_mat; } void CameraProcessor::initEKFPSM1(int state_dim, int measure_dim, int w_dim, int v_dim, cv::Mat& init_state) { ekFilter_psm1 = new ExtendedKalmanFilter(); ekFilter_psm1->SetDimensions(state_dim, state_dim, measure_dim, w_dim, v_dim); ekFilter_psm1->InitMatrices(); // Set initial state [theta_x, theta_y, theta_z, t_x, t_y, t_z]. Eigen::MatrixXd x = cvMat2Eigen(init_state); ekFilter_psm1->Init_x(x); // Noises Eigen::MatrixXd Q; Q.setIdentity(state_dim, w_dim); Q = Q*0.1; Eigen::MatrixXd R; R.setIdentity(measure_dim, v_dim); R = R*0.1; ekFilter_psm1->Set_NoiseCovariance(Q, R); // Error covariance ekFilter_psm1->Init_P(); // Jacobians: A, W, V. H should be calculated on-the-fly. ekFilter_psm1->Set_A(); ekFilter_psm1->Set_W(); ekFilter_psm1->Set_V(); } void CameraProcessor::initEKFPSM2(int state_dim, int measure_dim, int w_dim, int v_dim, cv::Mat& init_state) { ekFilter_psm2 = new ExtendedKalmanFilter(); ekFilter_psm2->SetDimensions(state_dim, state_dim, measure_dim, w_dim, v_dim); ekFilter_psm2->InitMatrices(); // Set initial state [theta_x, theta_y, theta_z, t_x, t_y, t_z]. Eigen::MatrixXd x = cvMat2Eigen(init_state); ekFilter_psm2->Init_x(x); // Noises Eigen::MatrixXd Q; Q.setIdentity(state_dim, w_dim); Q = Q*0.1; Eigen::MatrixXd R; R.setIdentity(measure_dim, v_dim); R = R*0.1; ekFilter_psm2->Set_NoiseCovariance(Q, R); // Error covariance ekFilter_psm2->Init_P(); // Jacobians: A, W, V. H should be calculated on-the-fly. ekFilter_psm2->Set_A(); ekFilter_psm2->Set_W(); ekFilter_psm2->Set_V(); } void CameraProcessor::draw_skel(cv::Mat &img, const cv::Mat &cHb, const Eigen::Matrix<double, 4, 4, Eigen::RowMajor> &psm_Hj4, const Eigen::Matrix<double, 4, 4, Eigen::RowMajor> &psm_Hj5, const Eigen::Matrix<double, 4, 4, Eigen::RowMajor> &psm_He, const float jaw_in, bool virt_or_cam, int psm_num) { cv::Mat subP = cv::Mat::eye(3, 3, CV_32FC1); subP.at<float>(0,0) = Fx; subP.at<float>(1,1) = Fy; if (virt_or_cam) { //subP.at<float>(0,2) = m_cam->Px_win(); subP.at<float>(1,2) = m_cam->Py_win(); } else { subP.at<float>(0,2) = Px; subP.at<float>(1,2) = Py; } std::vector<cv::Mat> bHj_vec; std::vector<cv::Point3f> cPj(7); // 1 shaft_far, 3 joint, 3 tips (cen/l/r) for (int i = 0; i < 3; i++) bHj_vec.push_back(cv::Mat(4, 4, CV_64F)); ::memcpy(bHj_vec[0].data, psm_Hj4.data(), sizeof(double)*16); ::memcpy(bHj_vec[1].data, psm_Hj5.data(), sizeof(double)*16); ::memcpy(bHj_vec[2].data, psm_He.data(), sizeof(double)*16); for (int i = 1; i <= bHj_vec.size(); i++) { // NB: bHj_vec unit in mm cv::Mat crHj_curr = cHb * bHj_vec[i-1]; cPj[i].x = crHj_curr.at<double>(0, 3); cPj[i].y = crHj_curr.at<double>(1, 3); cPj[i].z = abs(crHj_curr.at<double>(2, 3)); // abs to ensure projection make sense } // NB: Shaft line cv::Mat j2H_offset = cv::Mat::eye(4,4,CV_64FC1); j2H_offset.at<double>(0, 3) = 50; // 200mm cv::Mat temp = cHb * bHj_vec[0] * j2H_offset; cPj[0].x = temp.at<double>(0, 3); cPj[0].y = temp.at<double>(1, 3); cPj[0].z = abs(temp.at<double>(2, 3)); // abs to ensure projection make sense // Apply tip offset cv::Mat crHt; if (psm_num == 1) crHt = cHb * bHj_vec.back() * simulator_->psm1_tool->Tip_Mat(); else if (psm_num == 2) crHt = cHb * bHj_vec.back() * simulator_->psm2_tool->Tip_Mat(); cPj[4].x = crHt.at<double>(0, 3); cPj[4].y = crHt.at<double>(1, 3); cPj[4].z = crHt.at<double>(2, 3); /* Draw for extra points */ std::vector<cv::Point3f> cHpkey = simulator_->calc_keypoints(bHj_vec[0], bHj_vec[1], bHj_vec[2], jaw_in, cHb, psm_num); cPj[5] = cHpkey[12]; cPj[6] = cHpkey[13]; // cPj[0]: shaft_far end // cPj[1]: shaft // cPj[2]: logo // cPj[3]: end-effector // cPj[4]: tip central // cPj[5]: tip flat (right) // cPj[6]: tip deep (left) std::vector<cv::Point2f> projectedPoints, projectedKeypoints; cv::Mat rVec, tVec, distCoeffs; rVec = cv::Mat::zeros(3,1,CV_32FC1); tVec = cv::Mat::zeros(3,1,CV_32FC1); cv::projectPoints(cPj, rVec, tVec, subP, distCoeffs, projectedPoints); cv::projectPoints(cHpkey, rVec, tVec, subP, distCoeffs, projectedKeypoints); cv::circle(img, projectedPoints[2], 5, cv::Scalar(0,0,200), -1); // logo cv::circle(img, projectedPoints[3], 5, cv::Scalar(0,0,200), -1); // jaw // cv::circle(img, projectedPoints[4], 5, cv::Scalar(0,0,200), -1); // tip central cv::circle(img, projectedPoints[5], 3, cv::Scalar(0,0,200), -1); // tip left (deep) cv::circle(img, projectedPoints[6], 3, cv::Scalar(0,0,200), -1); // tip right (flat) float slope = (projectedPoints[1].y - projectedPoints[0].y) / (projectedPoints[1].x - projectedPoints[0].x); cv::Point p(0,0), q(img.cols,img.rows); if (psm_num == 2)//projectedPoints[0].x < projectedPoints[1].x) { p.y = -(projectedPoints[1].x - p.x) * slope + projectedPoints[1].y; cv::line(img, projectedPoints[1], p, cv::Scalar(0,0,200), 2); // shaft -> shaft_far } else { q.y = -(projectedPoints[1].x - q.x) * slope + projectedPoints[1].y; cv::line(img, projectedPoints[1], q, cv::Scalar(0,0,200), 2); // shaft -> shaft_far } cv::line(img, projectedPoints[3], projectedPoints[2], cv::Scalar(0,0,200), 2); // end -> logo // cv::line(img, projectedPoints[4], projectedPoints[3], cv::Scalar(0,0,200), 2); // tip -> jaw cv::line(img, projectedPoints[5], projectedPoints[3], cv::Scalar(0,0,200), 2); // tip_flat -> jaw cv::line(img, projectedPoints[6], projectedPoints[3], cv::Scalar(0,0,200), 2); // tip_deep -> jaw // cv::circle(img, projectedKeypoints[1], 3, cv::Scalar(0,255,255), -1); // yellow shaft_pivot //cv::circle(img, projectedKeypoints[3], 3, cv::Scalar(255,255,0), -1); // cyan logo_pin //cv::circle(img, projectedKeypoints[5], 3, cv::Scalar(0,255,255), -1); // yellow logo_wheel //cv::circle(img, projectedKeypoints[7], 3, cv::Scalar(255,255,0), -1); // cyan logo_s //cv::circle(img, projectedKeypoints[11], 3, cv::Scalar(255,255,0), -1); // cyan logo_pivot // TEST cloud // std::cout << cHpkey[7] << "; " << cHpkey[11] << std::endl; // std::cout << cloud_.at<cv::Vec3f>(projectedKeypoints[7].y, projectedKeypoints[7].x) // << cloud_.at<cv::Vec3f>(projectedKeypoints[11].y, projectedKeypoints[11].x)<< std::endl; // std::cout << "==================================================================" << std::endl; } void CameraProcessor::draw_skel(cv::Mat &img, const cv::Mat &cHb, const Eigen::Matrix<double, 4, 4, Eigen::RowMajor> &psm_Hj4, const Eigen::Matrix<double, 4, 4, Eigen::RowMajor> &psm_Hj5, const Eigen::Matrix<double, 4, 4, Eigen::RowMajor> &psm_He, const float jaw_in, const cv::Mat& err_T, int psm_num, float slope) { cv::Mat subP = cv::Mat::eye(3, 3, CV_32FC1); subP.at<float>(0,0) = Fx; subP.at<float>(1,1) = Fy; subP.at<float>(0,2) = Px; subP.at<float>(1,2) = Py; std::vector<cv::Mat> bHj_vec; std::vector<cv::Point3f> cPj(7); // 1 shaft_far, 3 joint, 3 tips (cen/l/r) for (int i = 0; i < 3; i++) bHj_vec.push_back(cv::Mat(4, 4, CV_64F)); ::memcpy(bHj_vec[0].data, psm_Hj4.data(), sizeof(double)*16); ::memcpy(bHj_vec[1].data, psm_Hj5.data(), sizeof(double)*16); ::memcpy(bHj_vec[2].data, psm_He.data(), sizeof(double)*16); cv::Mat corr_cHb = err_T * cHb; for (int i = 1; i <= bHj_vec.size(); i++) { // NB: bHj_vec unit in mm cv::Mat crHj_curr = corr_cHb * bHj_vec[i-1]; cPj[i].x = crHj_curr.at<double>(0, 3); cPj[i].y = crHj_curr.at<double>(1, 3); cPj[i].z = abs(crHj_curr.at<double>(2, 3)); // abs to ensure projection make sense } // NB: Shaft line cv::Mat j2H_offset = cv::Mat::eye(4,4,CV_64FC1); j2H_offset.at<double>(0, 3) = 50; // 200mm cv::Mat temp = corr_cHb * bHj_vec[0] * j2H_offset; cPj[0].x = temp.at<double>(0, 3); cPj[0].y = temp.at<double>(1, 3); cPj[0].z = abs(temp.at<double>(2, 3)); // abs to ensure projection make sense // Apply tip offset cv::Mat crHt; if (psm_num == 1) crHt = corr_cHb * bHj_vec.back() * simulator_->psm1_tool->Tip_Mat(); else if (psm_num == 2) crHt = corr_cHb * bHj_vec.back() * simulator_->psm2_tool->Tip_Mat(); cPj[4].x = crHt.at<double>(0, 3); cPj[4].y = crHt.at<double>(1, 3); cPj[4].z = crHt.at<double>(2, 3); /* Draw for extra points */ std::vector<cv::Point3f> cHpkey = simulator_->calc_keypoints(bHj_vec[0], bHj_vec[1], bHj_vec[2], jaw_in, corr_cHb, psm_num); cPj[5] = cHpkey[12]; cPj[6] = cHpkey[13]; // cPj[0]: shaft_far end // cPj[1]: shaft // cPj[2]: logo // cPj[3]: end-effector // cPj[4]: tip central // cPj[5]: tip flat (right) // cPj[6]: tip deep (left) std::vector<cv::Point2f> projectedPoints; cv::Mat rVec, tVec; cv::Mat distCoeffs; rVec = cv::Mat::zeros(3,1,CV_32FC1); tVec = cv::Mat::zeros(3,1,CV_32FC1); cv::projectPoints(cPj, rVec, tVec, subP, distCoeffs, projectedPoints); //float slope = (projectedPoints[1].y - projectedPoints[0].y) / (projectedPoints[1].x - projectedPoints[0].x); cv::Point p(0,0), q(img.cols,img.rows); if (psm_num == 2)//projectedPoints[0].x < projectedPoints[1].x) { p.y = -(projectedPoints[1].x - p.x) * slope + projectedPoints[1].y; cv::line(img, projectedPoints[1], p, cv::Scalar(0,255,128), 2); // shaft -> shaft_far } else { q.y = -(projectedPoints[1].x - q.x) * slope + projectedPoints[1].y; cv::line(img, projectedPoints[1], q, cv::Scalar(0,255,128), 2); // shaft -> shaft_far } //cv::line(img, projectedPoints[1], projectedPoints[0], cv::Scalar(0,255,128), 2); // shaft -> shaft_far cv::line(img, projectedPoints[3], projectedPoints[2], cv::Scalar(0,255,128), 2); // end -> logo //cv::line(img, projectedPoints[4], projectedPoints[3], cv::Scalar(0,255,128), 2); // tip -> jaw cv::line(img, projectedPoints[5], projectedPoints[3], cv::Scalar(0,255,128), 2); // tip_flat -> jaw cv::line(img, projectedPoints[6], projectedPoints[3], cv::Scalar(0,255,128), 2); // tip_deep -> jaw cv::circle(img, projectedPoints[2], 5, cv::Scalar(0,200,0), -1); // logo cv::circle(img, projectedPoints[3], 5, cv::Scalar(0,200,0), -1); // jaw //cv::circle(img, projectedPoints[4], 5, cv::Scalar(0,200,0), -1); // tip central cv::circle(img, projectedPoints[5], 3, cv::Scalar(255,0,255), -1); // tip left (deep) cv::circle(img, projectedPoints[6], 3, cv::Scalar(0,255,0), -1); // tip right (flat) //cv::circle(img, projectedPoints[2], 10, cv::Scalar(0,255,0), -1); // logo //cv::circle(img, projectedPoints[3], 10, cv::Scalar(0,0,255), -1); // jaw //cv::circle(img, projectedPoints[4], 5, cv::Scalar(255,0,0), -1); // tip central //cv::circle(img, projectedPoints[5], 3, cv::Scalar(0,255,0), -1); // tip left (deep) //cv::circle(img, projectedPoints[6], 3, cv::Scalar(0,0,255), -1); // tip right (flat) //cv::line(img, projectedPoints[1], projectedPoints[0], cv::Scalar(0,255,0), 2); // shaft -> shaft_far //cv::line(img, projectedPoints[3], projectedPoints[2], cv::Scalar(0,0,255), 2); // end -> logo //cv::line(img, projectedPoints[4], projectedPoints[3], cv::Scalar(255,0,0), 2); // tip -> jaw //cv::line(img, projectedPoints[5], projectedPoints[3], cv::Scalar(255,0,0), 2); // tip_flat -> jaw //cv::line(img, projectedPoints[6], projectedPoints[3], cv::Scalar(255,0,0), 2); // tip_deep -> jaw } void decompose_rotation_xyz(const cv::Mat &R, double& thetaX, double& thetaY, double& thetaZ) { // R = Rx * Ry * Rz order. R is CV_64F. thetaX = atan2(-R.at<double>(1, 2), R.at<double>(2, 2)); thetaY = atan2(R.at<double>(0, 2), sqrt(R.at<double>(1, 2) * R.at<double>(1, 2) + R.at<double>(2, 2) * R.at<double>(2, 2))); thetaZ = atan2(-R.at<double>(0, 1), R.at<double>(0, 0)); // MATLAB: //x = atan2(-R(2,3), R(3,3)); //y = atan2(R(1,3), sqrt(R(2,3)*R(2,3) + R(3,3)*R(3,3))); //z = atan2(-R(1,2), R(1,1)); } void compose_rotation(const double &thetaX, const double &thetaY, const double &thetaZ, cv::Mat &R) { cv::Mat X = cv::Mat::eye(3, 3, CV_64F); cv::Mat Y = cv::Mat::eye(3, 3, CV_64F); cv::Mat Z = cv::Mat::eye(3, 3, CV_64F); X.at<double>(1, 1) = cos(thetaX); X.at<double>(1, 2) = -sin(thetaX); X.at<double>(2, 1) = sin(thetaX); X.at<double>(2, 2) = cos(thetaX); Y.at<double>(0, 0) = cos(thetaY); Y.at<double>(0, 2) = sin(thetaY); Y.at<double>(2, 0) = -sin(thetaY); Y.at<double>(2, 2) = cos(thetaY); Z.at<double>(0, 0) = cos(thetaZ); Z.at<double>(0, 1) = -sin(thetaZ); Z.at<double>(1, 0) = sin(thetaZ); Z.at<double>(1, 1) = cos(thetaZ); R = X * Y * Z; // R is CV_64F. } QImage CameraProcessor::cvtCvMat2QImage(const cv::Mat & image) { QImage qtemp; if(!image.empty() && image.depth() == CV_8U) { const unsigned char * data = image.data; qtemp = QImage(image.cols, image.rows, QImage::Format_RGB32); for(int y = 0; y < image.rows; ++y, data += image.cols*image.elemSize()) { for(int x = 0; x < image.cols; ++x) { QRgb * p = ((QRgb*)qtemp.scanLine (y)) + x; *p = qRgb(data[x * image.channels()+2], data[x * image.channels()+1], data[x * image.channels()]); } } } else if(!image.empty() && image.depth() != CV_8U) { printf("Wrong image format, must be 8_bits\n"); } return qtemp; } #ifdef __linux__ // Framerate calculation double CameraProcessor::time_to_double(timeval *t) { return (t->tv_sec + (t->tv_usec/1000000.0)); } double CameraProcessor::time_diff(timeval *t1, timeval *t2) { return time_to_double(t2) - time_to_double(t1); } #endif
34.904675
135
0.664373
[ "shape", "vector" ]
f97348efcf5fef7c0957425e533f9969df0e18c4
15,054
cc
C++
src/off_trans.cc
antiprism/antiprism
c1bc8cc44a92773dd42540de26d578b1e2c831c7
[ "MIT" ]
45
2016-04-11T19:21:10.000Z
2022-03-30T08:47:43.000Z
src/off_trans.cc
CyberSpock/antiprism
0a3278d8285d308e21d0aa660b860fe2b803a562
[ "MIT" ]
null
null
null
src/off_trans.cc
CyberSpock/antiprism
0a3278d8285d308e21d0aa660b860fe2b803a562
[ "MIT" ]
7
2016-04-12T11:35:53.000Z
2022-03-30T08:47:46.000Z
/* Copyright (c) 2003-2016, Adrian Rossiter Antiprism - http://www.antiprism.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. */ /* Name: off_trans.cc Description: transformations for OFF files Project: Antiprism - http://www.antiprism.com */ #include "../base/antiprism.h" #include <cmath> #include <cstdio> #include <cstdlib> #include <string> #include <utility> #include <vector> using std::map; using std::pair; using std::string; using std::vector; using namespace anti; class trans_opts : public ProgramOpts { public: Trans3d trans_m; Geometry geom; string ifile; string ofile; trans_opts() : ProgramOpts("off_trans") {} void process_command_line(int argc, char **argv); void usage(); }; void trans_opts::usage() { fprintf(stdout, R"( Usage: %s [options] [input_file] Read a file in OFF format and apply transformations to it. If input_file is not given the program reads from standard input. Options %s -T <tran> translate, three numbers separated by commas which are used as the x, y and z displacements -R <rot> rotate about an axis, three, four or six numbers separated by commas. If three numbers these are angles (degrees) to rotate about the x, y and z axes. If four numbers, the first three are a direction vector for the axis, the last number is the angle (degrees) to rotate. If six numbers, these are two vectors (from,to) and rotate to carry the first to the second. If twelve numbers these are four vectors (from1,from2,to1,to2) and rotate to carry the first onto the third then rotate around the third to carry the second onto the fourth -M <norm> reflect in a plane, three numbers separated by commas which give a vector normal to the plane of reflection. -S <scal> scale, one, three or four numbers separated by commas. If one number then scale by this factor in all directions. If three numbers these are the factors to scale along the x, y and z axes. If four numbers, the first three are a direction vector for the scaling, the last number is the factor to scale -I inversion -A <crds> transformation that will align two sets of three points (18 numbers coordinates of from1,from2,from3,to1,to2,to3) -a <angs> transformation that makes particular angles between the mapped axes, angles in degrees in form yz_ang,zx_ang,xy_ang (corresponding to the angles opposite the x-, y- and z-axis) -X <mtrx> transformation matrix of 9 or 12 values, given left-to-right top-to-bottom, used to premultipy each coordinate -C translation that carries the centroid to the origin -y align geometry with the standard alignment for a symmetry type, up to three comma separated parts: symmetry subgroup (Schoenflies notation) or 'full', conjugation type (integer), realignment (colon separated list of an integer then decimal numbers) -Y align standard alignment of a symmetry type with its position as a subgroup of another symmetry type, up to four comma separated parts: main symmetry (Schoenflies notation) or file name, subgroup (Schoenflies notation), conjugation type (integer), realignment (colon separated list of an integer then decimal numbers) -s <type> relative scaling, scale so a measure has a value of 1. VAa need an oriented polyhedron, V needs a closed polyhedron. A - area a - average face area E - perimeter (sum of edges) e - average edge length V - volume r - radius, from centroid to furthest vertex -i replace the current combined transformation by its inverse -o <file> write output to file (default: write to standard output) )", prog_name(), help_ver_text); } Status rel_scale_val(Geometry &geom, char rel_scale, double *scale) { GeometryInfo info(geom); if (strchr("VAa", rel_scale)) { if (!geom.faces().size()) return Status::error( "scaling type is V, A or a but there is no face data"); if (!info.is_oriented()) return Status::error( "scaling type is V, A or a but polyhedron is not oriented"); if (strchr("V", rel_scale) && !info.is_closed()) return Status::error("scaling type is V but polyhedron is not closed"); } if (strchr("Ee", rel_scale) && (!info.num_edges() && !info.num_iedges())) return Status::error("scaling type is E or e but there is no edge data"); switch (rel_scale) { case 'V': *scale = pow(fabs(info.volume()), 1.0 / 3.0); break; case 'A': *scale = sqrt(info.face_areas().sum); break; case 'a': *scale = sqrt(fabs(info.face_areas().sum) / info.num_faces()); break; case 'E': if (info.num_edges()) // use explicit edges, if present *scale = info.edge_length_lims().sum; else *scale = info.iedge_length_lims().sum; break; case 'e': if (info.num_edges()) // use explicit edges, if present *scale = info.edge_length_lims().sum / info.num_edges(); else *scale = info.iedge_length_lims().sum / info.num_iedges(); break; case 'r': info.set_center(geom.centroid()); *scale = info.vert_dist_lims().max; break; } return Status::ok(); } void trans_opts::process_command_line(int argc, char **argv) { Status stat; opterr = 0; int c; vector<pair<char, char *>> args; handle_long_opts(argc, argv); while ((c = getopt(argc, argv, ":hT:R:M:S:IX:A:a:CY:y:s:io:")) != -1) { if (common_opts(c, optopt)) continue; switch (c) { // Keep switch for consistency/maintainability default: args.push_back(pair<char, char *>(c, optarg)); } } if (argc - optind > 1) error("too many arguments"); if (argc - optind == 1) ifile = argv[optind]; read_or_error(geom, ifile); vector<double> nums; Trans3d trans_m2; for (auto &arg : args) { c = arg.first; char *optarg = arg.second; switch (c) { case 'R': print_status_or_exit(read_double_list(optarg, nums), c); if (nums.size() == 3) trans_m2 = Trans3d::rotate(deg2rad(nums[0]), deg2rad(nums[1]), deg2rad(nums[2])); else if (nums.size() == 4) trans_m2 = Trans3d::rotate(Vec3d(nums[0], nums[1], nums[2]), deg2rad(nums[3])); else if (nums.size() == 6) trans_m2 = Trans3d::rotate(Vec3d(nums[0], nums[1], nums[2]), Vec3d(nums[3], nums[4], nums[5])); else if (nums.size() == 12) trans_m2 = Trans3d::align(Vec3d(nums[0], nums[1], nums[2]), Vec3d(nums[3], nums[4], nums[5]), Vec3d(nums[6], nums[7], nums[8]), Vec3d(nums[9], nums[10], nums[11])); else error(msg_str("must give 3, 4, 6 of 12 numbers (%lu were given)", (unsigned long)nums.size()), c); trans_m = trans_m2 * trans_m; break; case 'S': print_status_or_exit(read_double_list(optarg, nums), c); if (nums.size() == 1) trans_m2 = Trans3d::scale(nums[0]); else if (nums.size() == 3) trans_m2 = Trans3d::scale(nums[0], nums[1], nums[2]); else if (nums.size() == 4) trans_m2 = Trans3d::scale(Vec3d(nums[0], nums[1], nums[2]), nums[3]); else error(msg_str("must give 1, 3 or 4 numbers (%lu were given)", (unsigned long)nums.size()), c); trans_m = trans_m2 * trans_m; break; case 'T': print_status_or_exit(read_double_list(optarg, nums), c); if (nums.size() != 3) error(msg_str("must give exactly three numbers (%lu were " "given)", (unsigned long)nums.size()), c); trans_m2 = Trans3d::translate(Vec3d(nums[0], nums[1], nums[2])); trans_m = trans_m2 * trans_m; break; case 'M': print_status_or_exit(read_double_list(optarg, nums), c); if (nums.size() != 3) error(msg_str("must give exactly three numbers (%lu were " "given)", (unsigned long)nums.size()), c); trans_m2 = Trans3d::reflection(Vec3d(nums[0], nums[1], nums[2])); trans_m = trans_m2 * trans_m; break; case 'I': trans_m = Trans3d::inversion() * trans_m; break; case 'A': print_status_or_exit(read_double_list(optarg, nums), c); if (nums.size() == 18) trans_m2 = Trans3d::align(Vec3d(nums[0], nums[1], nums[2]), Vec3d(nums[3], nums[4], nums[5]), Vec3d(nums[6], nums[7], nums[8]), Vec3d(nums[9], nums[10], nums[11]), Vec3d(nums[12], nums[13], nums[14]), Vec3d(nums[15], nums[16], nums[17])); else error(msg_str("must give 18 numbers (%lu were given)", (unsigned long)nums.size()), c); trans_m = trans_m2 * trans_m; break; case 'a': print_status_or_exit(read_double_list(optarg, nums), c); if (nums.size() != 3) error(msg_str("must give exactly three numbers (%lu were " "given)", (unsigned long)nums.size()), c); bool valid; trans_m2 = Trans3d::angles_between_axes( deg2rad(nums[0]), deg2rad(nums[1]), deg2rad(nums[2]), &valid); if (!valid) error("the sum of any two angles must be greater than the third", c); trans_m = trans_m2 * trans_m; break; case 'X': print_status_or_exit(read_double_list(optarg, nums), c); trans_m2 = Trans3d::unit(); if (nums.size() == 9) { trans_m2[0] = nums[0]; trans_m2[1] = nums[1]; trans_m2[2] = nums[2]; trans_m2[4] = nums[3]; trans_m2[5] = nums[4]; trans_m2[6] = nums[5]; trans_m2[8] = nums[6]; trans_m2[9] = nums[7]; trans_m2[10] = nums[8]; } else if (nums.size() == 12) { for (int i = 0; i < 12; i++) trans_m2[i] = nums[i]; } else error(msg_str("must give 9 or 12 numbers (%lu were given)", (unsigned long)nums.size()), c); trans_m = trans_m2 * trans_m; break; case 'C': trans_m = Trans3d::translate(-(trans_m * geom.centroid())) * trans_m; break; case 'Y': { Split parts(optarg, ","); if (parts.size() < 1 || parts.size() > 4) error("argument should have 1-4 comma separated parts", c); Symmetry sym; Geometry sgeom; if (sgeom.read(parts[0])) sym.init(sgeom); else if (!(stat = sym.init(parts[0], Trans3d()))) error( msg_str("invalid filename or symmetry type name: %s", stat.c_msg()), c); Symmetry sub_sym = sym; if (parts.size() > 1 && !(stat = sub_sym.init(parts[1], Trans3d()))) error(msg_str("sub-symmetry type: %s", stat.c_msg()), c); int sub_sym_conj = 0; if (parts.size() > 2 && !(stat = read_int(parts[2], &sub_sym_conj))) error(msg_str("sub-symmetry conjugation number: %s", stat.c_msg()), c); Symmetry final_sym; if (!(stat = sym.get_sub_sym(sub_sym, &final_sym, sub_sym_conj))) error(msg_str("sub-symmetry: %s", stat.c_msg()), c); if (parts.size() > 3 && !(stat = final_sym.get_autos().set_realignment(parts[3]))) error(msg_str("sub-symmetry realignment: %s", stat.c_msg()), c); trans_m = (final_sym.get_autos().get_realignment() * final_sym.get_to_std()) .inverse() * trans_m; break; } case 'y': { Geometry geom_cur = geom; geom_cur.transform(trans_m); Symmetry full_sym(geom_cur); Split parts(optarg, ","); if (parts.size() == 0 || parts.size() > 3) error("argument should have 1-3 comma separated parts", c); Symmetry sub_sym; if (strncmp(parts[0], "full", strlen(optarg)) == 0) sub_sym = full_sym; else if (!(stat = sub_sym.init(parts[0], Trans3d()))) error(msg_str("sub-symmetry type: %s", stat.c_msg()), c); int sub_sym_conj = 0; if (parts.size() > 1 && !(stat = read_int(parts[1], &sub_sym_conj))) error(msg_str("sub-symmetry conjugation number: %s", stat.c_msg()), c); Symmetry sym; if (!(stat = full_sym.get_sub_sym(sub_sym, &sym, sub_sym_conj))) error(msg_str("sub-symmetry: %s", stat.c_msg()), c); if (parts.size() > 2 && !(stat = sym.get_autos().set_realignment(parts[2]))) error(msg_str("sub-symmetry realignment: %s", stat.c_msg()), c); trans_m = sym.get_autos().get_realignment() * sym.get_to_std() * trans_m; break; } case 's': { char rel_scale = '\0'; if (strlen(optarg) == 1 && strchr("VAaEer", *optarg)) rel_scale = *optarg; else error("relative scale must be V,A,a,E,e or r", c); Geometry geom_cur = geom; geom_cur.transform(trans_m); double scale; print_status_or_exit(rel_scale_val(geom_cur, rel_scale, &scale), c); trans_m = Trans3d::scale(1 / scale) * trans_m; break; } case 'i': trans_m = trans_m.inverse(); break; case 'o': ofile = optarg; break; default: error("unknown command line error"); } } } int main(int argc, char *argv[]) { trans_opts opts; opts.process_command_line(argc, argv); opts.geom.transform(opts.trans_m); opts.write_or_error(opts.geom, opts.ofile); return 0; }
34.527523
80
0.589611
[ "geometry", "vector", "transform" ]
f994655a0bc38664fc0bc6bf1fe73e0f4e563fcc
1,705
cpp
C++
Codeforces/378/c.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
14
2019-08-14T00:43:10.000Z
2021-12-16T05:43:31.000Z
Codeforces/378/c.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
null
null
null
Codeforces/378/c.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
6
2020-12-30T03:30:17.000Z
2022-03-11T03:40:02.000Z
#include <bits/stdc++.h> #define f first #define s second using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; template <typename T1, typename T2> ostream &operator <<(ostream &os, pair<T1, T2> p){os << p.first << " " << p.second; return os;} template <typename T> ostream &operator <<(ostream &os, vector<T> &v){for(T i : v)os << i << ", "; return os;} template <typename T> ostream &operator <<(ostream &os, set<T> s){for(T i : s) os << i << ", "; return os;} template <typename T1, typename T2> ostream &operator <<(ostream &os, map<T1, T2> m){for(pair<T1, T2> i : m) os << i << endl; return os;} int main(){ int n, m, k; cin >> n >> m >> k; string b[n]; int reached = 0; for(int i = 0; i < n; i++){ cin >> b[i]; for(int j = 0; j < m; j++){ if(b[i][j] == '.'){ b[i][j] = 'X'; reached++; } } } queue<pii> bfs; for(int i = 0; i < n * m; i++){ int x = i / m; int y = i % m; if(b[x][y] == 'X'){ bfs.push(pii(x, y)); break; } } while(!bfs.empty()){ pii idx = bfs.front(); bfs.pop(); if(idx.f < 0 || idx.f > n-1 || idx.s < 0 || idx.s > m-1 || b[idx.f][idx.s] != 'X'){ continue; } if(reached <= k){ break; } reached--; b[idx.f][idx.s] = '.'; bfs.push(pii(idx.f + 1, idx.s)); bfs.push(pii(idx.f - 1, idx.s)); bfs.push(pii(idx.f, idx.s + 1)); bfs.push(pii(idx.f, idx.s - 1)); } for(int i = 0; i < n; i++){ cout << b[i] << endl; } return 0; }
26.230769
101
0.447507
[ "vector" ]
f99d9b8ae05f96c46e13145caf4cfb23a7780139
18,934
cpp
C++
bindings/bindings.cpp
shamanDevel/Ray-Splitting-for-DVR
1747a01271d753739697fc9532894955d8c887fd
[ "MIT" ]
1
2021-09-23T20:45:22.000Z
2021-09-23T20:45:22.000Z
bindings/bindings.cpp
shamanDevel/Ray-Splitting-for-DVR
1747a01271d753739697fc9532894955d8c887fd
[ "MIT" ]
null
null
null
bindings/bindings.cpp
shamanDevel/Ray-Splitting-for-DVR
1747a01271d753739697fc9532894955d8c887fd
[ "MIT" ]
2
2021-06-03T14:04:16.000Z
2021-06-03T14:16:02.000Z
#include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <json.hpp> #include <fstream> #include <json.hpp> #include <tinyformat.h> #include <lib.h> #include <renderer_settings.cuh> #ifdef WIN32 #ifndef NOMINMAX #define NOMINMAX 1 #endif #include <Windows.h> #endif namespace py = pybind11; using namespace renderer; //helpers OutputTensor allocateOutput(int width, int height, RendererArgs::RenderMode type) { int channels; if (type == RendererArgs::RenderMode::ISO) channels = IsoRendererOutputChannels; else if (type == RendererArgs::RenderMode::DVR) channels = DvrRendererOutputChannels; else throw std::invalid_argument("'type' must be either 'iso' or 'dvr'"); if (width <= 0) throw std::invalid_argument("'width' must be positive"); if (height <= 0) throw std::invalid_argument("'height' must be positive"); return OutputTensor(height, width, channels); } std::filesystem::path getCacheDir() { //suffix and default (if default, it is a relative path) static const std::filesystem::path SUFFIX{ "kernel_cache" }; #ifdef WIN32 //get the path to this dll as base path char path[MAX_PATH]; HMODULE hm = NULL; if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR)&getCacheDir, &hm) == 0) { int ret = GetLastError(); fprintf(stderr, "GetModuleHandle failed, error = %d\n", ret); return SUFFIX; } if (GetModuleFileName(hm, path, sizeof(path)) == 0) { int ret = GetLastError(); fprintf(stderr, "GetModuleFileName failed, error = %d\n", ret); return SUFFIX; } std::filesystem::path out = path; out = out.parent_path(); const auto out_str = out.string(); fprintf(stdout, "This DLL is located at %s, use that as cache dir\n", out_str.c_str()); out /= SUFFIX; return out; #else return SUFFIX //default #endif } class OutputTensorCPU { public: size_t height, width, channels; std::vector<float> data; OutputTensorCPU(const OutputTensor& gpu) : height(gpu.rows()), width(gpu.cols()), channels(gpu.batches()) , data(gpu.rows()*gpu.cols()*gpu.batches()) { gpu.copyToHost(&data[0]); } }; //class InstrumentationCPU //{ //public: // size_t height, width; // std::vector<kernel::Instrumentation> data; // InstrumentationCPU(size_t height, size_t width) // : height(height), width(width), data(width* height) // {} //}; class GPUTimer { cudaEvent_t start_, stop_; public: GPUTimer() : start_(0), stop_(0) { CUMAT_SAFE_CALL(cudaEventCreate(&start_)); CUMAT_SAFE_CALL(cudaEventCreate(&stop_)); } ~GPUTimer() { CUMAT_SAFE_CALL(cudaEventDestroy(start_)); CUMAT_SAFE_CALL(cudaEventDestroy(stop_)); } void start() { CUMAT_SAFE_CALL(cudaEventRecord(start_)); } void stop() { CUMAT_SAFE_CALL(cudaEventRecord(stop_)); } float getElapsedMilliseconds() { CUMAT_SAFE_CALL(cudaEventSynchronize(stop_)); float ms; CUMAT_SAFE_CALL(cudaEventElapsedTime(&ms, start_, stop_)); return ms; } }; auto loadFromJson(const std::string& jsonFileName, const std::string& basePath) { std::ifstream i(jsonFileName); if (!i.is_open()) throw std::exception("Unable to load settings file"); nlohmann::json settings; i >> settings; i.close(); RendererArgs rendererArgs; Camera camera; std::string volumeFileName; RendererArgs::load(settings, basePath, rendererArgs, camera, volumeFileName); return std::make_tuple(rendererArgs, camera, volumeFileName); } // initialize context cuMat::Context& ctx = cuMat::Context::current(); cuMat::DevicePointer<float> dummyMemory; bool contextInitialized = false; //BINDINGS PYBIND11_MODULE(pyrenderer, m) { m.doc() = "python bindings for the analytic volume renderer"; // initialize context dummyMemory = cuMat::DevicePointer<float>(1, ctx); contextInitialized = true; auto cleanup_callback = []() { if (contextInitialized) { contextInitialized = false; dummyMemory = {}; ctx.destroy(); std::cout << "cuMat context destroyed" << std::endl; } }; m.def("cleanup", cleanup_callback, py::doc("Explicit cleanup of all CUDA references")); m.add_object("_cleanup", py::capsule(cleanup_callback)); py::enum_<RendererArgs::RenderMode>(m, "RenderMode") .value("Iso", RendererArgs::RenderMode::ISO) .value("Dvr", RendererArgs::RenderMode::DVR); py::enum_<RendererArgs::VolumeFilterMode>(m, "VolumeFilterMode") .value("Trilinear", RendererArgs::VolumeFilterMode::TRILINEAR) .value("Tricubic", RendererArgs::VolumeFilterMode::TRICUBIC); py::enum_<RendererArgs::DvrTfMode>(m, "DvrTfMode") .value("Linear", RendererArgs::DvrTfMode::PiecewiseLinear) .value("MultiIso", RendererArgs::DvrTfMode::MultipleIsosurfaces) .value("Hybrid", RendererArgs::DvrTfMode::Hybrid); //py::enum_<RendererArgs::TfPreintegration>(m, "TfPreintegration") // .value("Off", RendererArgs::TfPreintegration::OFF) // .value("OneD", RendererArgs::TfPreintegration::ONE_D) // .value("TwoD", RendererArgs::TfPreintegration::TWO_D); py::enum_<Camera::Orientation>(m, "Orientation") .value("Xp", Camera::Orientation::Xp) .value("Xm", Camera::Orientation::Xm) .value("Yp", Camera::Orientation::Yp) .value("Ym", Camera::Orientation::Ym) .value("Zp", Camera::Orientation::Zp) .value("Zm", Camera::Orientation::Zm); py::class_<float3>(m, "float3") .def(py::init<>()) .def(py::init([](float x, float y, float z) {return make_float3(x, y, z); })) .def_readwrite("x", &float3::x) .def_readwrite("y", &float3::y) .def_readwrite("z", &float3::z) .def("__str__", [](const float3& v) { return tinyformat::format("(%f, %f, %f)", v.x, v.y, v.z); }); py::class_<float4>(m, "float4") .def(py::init<>()) .def(py::init([](float x, float y, float z, float w) { return make_float4(x, y, z, w); })) .def_readwrite("x", &float4::x) .def_readwrite("y", &float4::y) .def_readwrite("z", &float4::z) .def_readwrite("w", &float4::w) .def("__str__", [](const float4& v) { return tinyformat::format("(%f, %f, %f, %f)", v.x, v.y, v.z, v.w); }); py::class_<int3>(m, "int3") .def(py::init<>()) .def_readwrite("x", &int3::x) .def_readwrite("y", &int3::y) .def_readwrite("z", &int3::z) .def("__str__", [](const int3& v) { return tinyformat::format("(%d, %d, %d)", v.x, v.y, v.z); }); m.def("labToXyz", &kernel::labToXyz); m.def("xyzToLab", &kernel::xyzToLab); py::class_<Camera>(m, "Camera") .def(py::init<>()) .def("clone", [](const Camera& args)->Camera {return args; }) .def("update_render_args", &Camera::updateRenderArgs) .def("screen_to_world", &Camera::screenToWorld) .def_property("orientation", &Camera::orientation, &Camera::setOrientation) .def_property("look_at", &Camera::lookAt, &Camera::setLookAt) .def_property("fov", &Camera::fov, &Camera::setFov) .def_property_readonly("base_distance", &Camera::baseDistance) .def_property("pitch", &Camera::currentPitch, &Camera::setCurrentPitch) .def_property("yaw", &Camera::currentYaw, &Camera::setCurrentYaw) .def_property("zoom", &Camera::zoomvalue, &Camera::setZoomvalue); py::class_<ShadingSettings>(m, "ShadingSettings") .def(py::init<>()) .def_readwrite("ambient_light_color", &ShadingSettings::ambientLightColor) .def_readwrite("diffuse_light_color", &ShadingSettings::diffuseLightColor) .def_readwrite("specular_light_color", &ShadingSettings::specularLightColor) .def_readwrite("specular_exponent", &ShadingSettings::specularExponent) .def_readwrite("material_color", &ShadingSettings::materialColor) .def_readwrite("ao_strength", &ShadingSettings::aoStrength) .def_readwrite("light_direction", &ShadingSettings::lightDirection); //colors in Lab py::class_<RendererArgs::TfLinear>(m, "TfLinear") .def(py::init<>()) .def_readwrite("density_axis_opacity", &RendererArgs::TfLinear::densityAxisOpacity) .def_readwrite("opacity_axis", &RendererArgs::TfLinear::opacityAxis) .def_readwrite("opacity_extra_color_axis", &RendererArgs::TfLinear::opacityExtraColorAxis) .def_readwrite("density_axis_color", &RendererArgs::TfLinear::densityAxisColor) .def_readwrite("color_axis", &RendererArgs::TfLinear::colorAxis); //colors in XYZ py::class_<RendererArgs::TfMultiIso>(m, "TfMultiIso") .def(py::init<>()) .def_readwrite("densities", &RendererArgs::TfMultiIso::densities) .def_readwrite("colors", &RendererArgs::TfMultiIso::colors); py::class_<RendererArgs>(m, "RendererArgs") .def(py::init<>()) .def("clone", [](const RendererArgs& args)->RendererArgs {return args; }) .def_readwrite("mipmap_level", &RendererArgs::mipmapLevel) .def_readwrite("render_mode", &RendererArgs::renderMode) .def_readwrite("width", &RendererArgs::cameraResolutionX) .def_readwrite("height", &RendererArgs::cameraResolutionY) .def_readwrite("isovalue", &RendererArgs::isovalue) .def_readwrite("stepsize", &RendererArgs::stepsize) .def_readwrite("volume_filter_mode", &RendererArgs::volumeFilterMode) .def_readwrite("shading", &RendererArgs::shading) .def_readwrite("dvr_use_shading", &RendererArgs::dvrUseShading) .def_readwrite("opacity_scaling", &RendererArgs::opacityScaling) .def_readwrite("min_density", &RendererArgs::minDensity) .def_readwrite("max_density", &RendererArgs::maxDensity) .def_readwrite("enable_clip_plane", &RendererArgs::enableClipPlane) .def_readwrite("clip_plane", &RendererArgs::clipPlane) .def_readonly("dvr_tf_mode", &RendererArgs::dvrTfMode) .def("get_linear_tf", [](const RendererArgs& args) { if (args.dvrTfMode != kernel::DvrTfMode::PiecewiseLinear) throw std::invalid_argument("TF mode is not 'Linear'"); return std::get<RendererArgs::TfLinear>(args.tf); }) .def("get_multiiso_tf", [](const RendererArgs& args) { if (args.dvrTfMode != kernel::DvrTfMode::MultipleIsosurfaces) throw std::invalid_argument("TF mode is not 'MultiIso'"); return std::get<RendererArgs::TfMultiIso>(args.tf); }) .def("get_hybrid_tf", [](const RendererArgs& args) { if (args.dvrTfMode != kernel::DvrTfMode::Hybrid) throw std::invalid_argument("TF mode is not 'Hybrid'"); return std::get<RendererArgs::TfLinear>(args.tf); }) .def("set_linear_tf", [](RendererArgs& args, const RendererArgs::TfLinear& tf) { args.dvrTfMode = kernel::DvrTfMode::PiecewiseLinear; args.tf = tf; }) .def("set_multiiso_tf", [](RendererArgs& args, const RendererArgs::TfMultiIso& tf) { args.dvrTfMode = kernel::DvrTfMode::MultipleIsosurfaces; args.tf = tf; }) .def("set_hybrid_tf", [](RendererArgs& args, const RendererArgs::TfLinear& tf) { args.dvrTfMode = kernel::DvrTfMode::Hybrid; args.tf = tf; }) //.def_readwrite("tf_preintegration", &RendererArgs::tfPreintegration) .def("dumps", [](const RendererArgs& args) { const auto json = args.toJson(); return json.dump(-1); }, "dumps the settings to a json string"); m.def("load_from_json", &loadFromJson, "Loads a json file with the settings.\n" "Parameters: file name of the json, base path for volume path resolution.\n" "Returns:\n" " RendererArgs instance\n" " Camera instance\n" " file name of the volume as string"); py::enum_<Volume::ImplicitEquation>(m, "ImplicitEquation") .value("MarschnerLobb", Volume::ImplicitEquation::MARSCHNER_LOBB) .value("Cube", Volume::ImplicitEquation::CUBE) .value("Sphere", Volume::ImplicitEquation::SPHERE) .value("InverseSphere", Volume::ImplicitEquation::INVERSE_SPHERE) .value("DingDong", Volume::ImplicitEquation::DING_DONG) .value("Endrass", Volume::ImplicitEquation::ENDRASS) .value("Barth", Volume::ImplicitEquation::BARTH) .value("Heart", Volume::ImplicitEquation::HEART) .value("Kleine", Volume::ImplicitEquation::KLEINE) .value("Cassini", Volume::ImplicitEquation::CASSINI) .value("Steiner", Volume::ImplicitEquation::STEINER) .value("CrossCap", Volume::ImplicitEquation::CROSS_CAP) .value("Kummer", Volume::ImplicitEquation::KUMMER) .value("Blobbly", Volume::ImplicitEquation::BLOBBY) .value("Tube", Volume::ImplicitEquation::TUBE); py::class_<Volume, std::shared_ptr<Volume>>(m, "Volume") .def(py::init<std::string>()) .def("create_mipmap_level", &Volume::createMipmapLevel) .def_property_readonly("world_size", &Volume::worldSize) .def_property_readonly("resolution", &Volume::baseResolution) .def_static("create_implicit", [](Volume::ImplicitEquation name, int resolution, py::kwargs kwargs) { std::unordered_map<std::string, float> args; for (const auto& e : kwargs) args.insert({ e.first.cast<std::string>(), e.second.cast<float>() }); return std::shared_ptr<Volume>(Volume::createImplicitDataset(resolution, name, args)); }) .def("copy_to_gpu", [](std::shared_ptr<Volume> v) { for (int i = 0; v->getLevel(i); ++i) v->getLevel(i)->copyCpuToGpu(); }) .def("save", [](std::shared_ptr<Volume> v, const std::string& filename) { v->save(filename); }) .def("resample", [](std::shared_ptr<Volume> v, int x, int y, int z, const std::string& mode) { Volume::VolumeFilterMode m; if (mode == "nearest") m = Volume::NEAREST; else if (mode == "linear") m = Volume::TRILINEAR; else if (mode == "cubic") m = Volume::TRICUBIC; else throw std::runtime_error("Unknown resampling mode, must be 'nearest', 'linear' or 'cubic'"); return std::shared_ptr<Volume>(v->resample(make_int3(x, y, z), m)); }); m.def("reload_kernels", []( bool enableDebugging, bool enableInstrumentation, const std::vector<std::string>& otherPreprocessorArguments) { return KernelLauncher::Instance().reload( std::cout, enableDebugging, enableInstrumentation, otherPreprocessorArguments); }, py::arg("enableDebugging")=true, py::arg("enableInstrumentation")=false, py::arg("otherPreprocessorArguments")=std::vector<std::string>(), "(re)loads the kernels"); m.def("iso_kernel_names", []() { return KernelLauncher::Instance().getKernelNames(KernelLauncher::KernelTypes::Iso); }, "returns a list of the names of the isosurface kernels"); m.def("dvr_kernel_names", []() { return KernelLauncher::Instance().getKernelNames(KernelLauncher::KernelTypes::Dvr); }, "returns a list of the names of the DVR kernels"); m.def("multiiso_kernel_names", []() { return KernelLauncher::Instance().getKernelNames(KernelLauncher::KernelTypes::MultiIso); }, "returns a list of the names of the DVR kernels"); m.def("sync", []() {CUMAT_SAFE_CALL(cudaDeviceSynchronize()); }); py::class_<OutputTensor>(m, "OutputTensor") .def("copy_to_cpu", [](const OutputTensor& gpu) { return std::make_shared<OutputTensorCPU>(gpu); }, "copies the output tensor to the CPU. Use it in combination with numpy: 'np.array(output.copy_to_cpu())'"); py::class_<OutputTensorCPU, std::shared_ptr<OutputTensorCPU>>(m, "OutputTensorCPU", py::buffer_protocol()) .def_buffer([](OutputTensorCPU& m) -> py::buffer_info { return py::buffer_info( m.data.data(), sizeof(float), py::format_descriptor<float>::format(), 3, { m.height, m.width, m.channels }, { sizeof(float), sizeof(float) * m.height, sizeof(float)* m.width* m.height } ); }); m.def("allocate_output", &allocateOutput, "Allocates the output tensor"); m.def("render", []( const std::string& kernelName, std::shared_ptr<Volume> volume, const RendererArgs& args, OutputTensor& output) { renderer::render_gpu(kernelName, volume.get(), &args, output, 0); }); #if KERNEL_INSTRUMENTATION==1 PYBIND11_NUMPY_DTYPE(kernel::PerPixelInstrumentation, densityFetches, tfFetches, ddaSteps, isoIntersections, intervalEval, intervalStep, intervalMaxStep, timeDensityFetch, timeDensityFetch_NumSamples, timePolynomialCreation, timePolynomialCreation_NumSamples, timePolynomialSolution, timePolynomialSolution_NumSamples, timeTotal); py::class_<GlobalInstrumentation>(m, "GlobalInstrumentation") .def(py::init<>()) .def_readwrite("numControlPoints", &GlobalInstrumentation::numControlPoints) .def_readwrite("numTriangles", &GlobalInstrumentation::numTriangles) .def_readwrite("numFragments", &GlobalInstrumentation::numFragments); m.def("render_with_instrumentation", []( const std::string& kernelName, std::shared_ptr<Volume> volume, const RendererArgs& args, OutputTensor& output) { size_t size = args.cameraResolutionX * args.cameraResolutionY; kernel::PerPixelInstrumentation* instrumentationHost = new kernel::PerPixelInstrumentation[size]; kernel::PerPixelInstrumentation* instrumentationDevice; CUMAT_SAFE_CALL(cudaMalloc(&instrumentationDevice, size * sizeof(kernel::PerPixelInstrumentation))); GlobalInstrumentation globalInstrumentation; renderer::render_gpu(kernelName, volume.get(), &args, output, 0, instrumentationDevice, &globalInstrumentation); CUMAT_SAFE_CALL(cudaMemcpy(instrumentationHost, instrumentationDevice, size * sizeof(kernel::PerPixelInstrumentation), cudaMemcpyDeviceToHost)); CUMAT_SAFE_CALL(cudaFree(instrumentationDevice)); py::capsule free_when_done(instrumentationHost, [](void* f) { kernel::PerPixelInstrumentation* foo = static_cast<kernel::PerPixelInstrumentation*>(f); delete[] foo; }); return py::make_tuple(py::array_t<kernel::PerPixelInstrumentation>( { args.cameraResolutionX, args.cameraResolutionY }, { args.cameraResolutionY * sizeof(kernel::PerPixelInstrumentation), sizeof(kernel::PerPixelInstrumentation) }, instrumentationHost, free_when_done), globalInstrumentation); }); #endif py::class_<GPUTimer>(m, "GpuTimer") .def(py::init<>()) .def("start", &GPUTimer::start) .def("stop", &GPUTimer::stop) .def("elapsed_ms", &GPUTimer::getElapsedMilliseconds); //OpenGL / OIT auto mOit = m.def_submodule("oit"); mOit.def("setup_offscreen_context", []() { OpenGLRasterization::Instance().setupOffscreenContext(); }); mOit.def("delete_offscreen_context", []() { OpenGLRasterization::Instance().cleanup(); OpenGLRasterization::Instance().deleteOffscreenContext(); }); mOit.def("set_fragment_buffer_size", [](int size) { OpenGLRasterization::Instance().setFragmentBufferSize(size); }); py::enum_<OpenGLRasterization::MarchingCubesComputationMode>(mOit, "MarchingCubesComputationMode") .value("PreDevice", OpenGLRasterization::MarchingCubesComputationMode::PRE_DEVICE) .value("PreHost", OpenGLRasterization::MarchingCubesComputationMode::PRE_HOST) .value("OnTheFly", OpenGLRasterization::MarchingCubesComputationMode::ON_THE_FLY); mOit.def("set_marching_cubes_mode", [](OpenGLRasterization::MarchingCubesComputationMode mode) { OpenGLRasterization::Instance().setMarchingCubesComputationMode(mode); }); mOit.def("set_max_fragments_per_pixel", [](int size) { OpenGLRasterization::Instance().setMaxFragmentsPerPixel(size); }); mOit.def("set_tile_size", [](int size) { OpenGLRasterization::Instance().setTileSize(size); }); //Initialization KernelLauncher::SetCacheDir(getCacheDir()); m.def("init", []() { OpenGLRasterization::Register(); KernelLauncher::Instance().init(); }); }
36.064762
146
0.718073
[ "render", "vector" ]
f9a31ad8894c44393ddc569ccf84b980ffd2ce1d
9,376
hpp
C++
include/util/datastream/sketch/Level2Sketch.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
31
2015-03-03T19:13:42.000Z
2020-09-03T08:11:56.000Z
include/util/datastream/sketch/Level2Sketch.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
1
2016-12-24T00:12:11.000Z
2016-12-24T00:12:11.000Z
include/util/datastream/sketch/Level2Sketch.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
8
2015-09-06T01:55:21.000Z
2021-12-20T02:16:13.000Z
#ifndef IZENELIB_UTIL_bucket_LEVEL2SKETCH_H_ #define IZENELIB_UTIL_bucket_LEVEL2SKETCH_H_ #include <util/hashFunction.h> #include <vector> #include <iostream> NS_IZENELIB_UTIL_BEGIN template <typename ElemType> class Level2Bucket { public: typedef ElemType DataTypeT; private: typedef std::vector<uint32_t> Level2BucketT; typedef Level2Bucket<DataTypeT> ThisType; public: Level2Bucket() : total_cnt_(0) { bucket_.resize(sizeof(DataTypeT)*8); } const uint32_t& getBitCnt(size_t index) const { return bucket_[index]; } void load(std::istream& is) { is.read((char*)&total_cnt_, sizeof(total_cnt_)); size_t bit_cnt_num = 0; is.read((char*)&bit_cnt_num, sizeof(bit_cnt_num)); if(bit_cnt_num != sizeof(DataTypeT)*8) { cout << "load Level2Bucket failed. The DataTypeT is not compatible with current." << endl; return; } bucket_.resize(bit_cnt_num); for(size_t i = 0; i < bit_cnt_num; ++i) { uint32_t data; is.read((char*)&data, sizeof(data)); bucket_[i] = data; } } void save(std::ostream& os) const { os.write((const char*)&total_cnt_, sizeof(total_cnt_)); size_t bit_cnt_num = bucket_.size(); os.write((const char*)&bit_cnt_num, sizeof(bit_cnt_num)); for(size_t i = 0; i < bit_cnt_num; ++i) { const uint32_t& data = bucket_[i]; os.write((const char*)&data, sizeof(data)); } } void updateBucket(const DataTypeT& data) { total_cnt_++; for(size_t i = 0; i < bucket_.size(); ++i) { bucket_[i] += (data & ((DataTypeT)1 << i)) == 0?0:1; } } void unionBucket(const ThisType& other) { total_cnt_ += other.total_cnt_; for(size_t i = 0; i < bucket_.size(); ++i) { bucket_[i] += other.bucket_[i]; } } bool emptyBucket() const { return total_cnt_ == 0; } bool singletonBucket() const { if(total_cnt_ == 0) return false; for(size_t j = 0; j < bucket_.size(); ++j) { if(bucket_[j] > 0 && total_cnt_ > bucket_[j]) return false; } return true; } bool identicalSingletonBucket(const ThisType& other) const { if(!singletonBucket() || !other.singletonBucket()) return false; for(size_t j = 0; j < bucket_.size(); ++j) { if( (bucket_[j] > 0 && other.bucket_[j] == 0) || (bucket_[j] == 0 && other.bucket_[j] > 0)) return false; } return true; } bool singletonUnionBucket(const ThisType& other) const { if((singletonBucket() && other.emptyBucket()) || (other.singletonBucket() && emptyBucket()) ) return true; return identicalSingletonBucket(other); } private: Level2BucketT bucket_; uint32_t total_cnt_; }; template <typename ElemType> class Level2Sketch { public: typedef ElemType DataTypeT; private: typedef Level2Bucket<DataTypeT> Level2BucketType; typedef Level2Sketch<DataTypeT> ThisType; public: Level2Sketch() { } Level2Sketch(size_t bucket_num) { level2sketch_.resize(bucket_num); } void resize(size_t bucket_num) { level2sketch_.resize(bucket_num); } size_t size() const { return level2sketch_.size(); } const Level2BucketType& getBucket(size_t index) const { return level2sketch_[index]; } void load(std::istream& is) { size_t bucket_num = 0; is.read((char*)&bucket_num, sizeof(bucket_num)); if(bucket_num != level2sketch_.size()) { cout << "load Level2Sketch failed. The size is not compatible with current." << endl; return; } for(size_t i = 0; i < bucket_num; ++i) { level2sketch_[i].load(is); } } void save(std::ostream& os) const { const size_t bucket_num = level2sketch_.size(); os.write((const char*)&bucket_num, sizeof(bucket_num)); for(size_t i = 0; i < bucket_num; ++i) { level2sketch_[i].save(os); } } void updateBucket(size_t index, const DataTypeT& data) { assert(index < level2sketch_.size()); level2sketch_[index].updateBucket(data); } void unionBucket(size_t index, const ThisType& other) { level2sketch_[index].unionBucket(other.level2sketch_[index]); } void unionLevel2Sketch(const ThisType& other) { for(size_t i = 0; i < level2sketch_.size(); ++i) unionBucket(i, other); } bool emptyBucket(size_t index) const { assert(index < level2sketch_.size()); return level2sketch_[index].emptyBucket(); } bool singletonBucket(size_t index) const { assert(index < level2sketch_.size()); return level2sketch_[index].singletonBucket(); } bool identicalSingletonBucket(size_t index, const ThisType& other) const { assert(index < level2sketch_.size()); assert(index < other.size()); return level2sketch_[index].identicalSingletonBucket(other.level2sketch_[index]); } bool singletonUnionBucket(size_t index, const ThisType& other) const { assert(index < level2sketch_.size()); assert(index < other.size()); return level2sketch_[index].singletonUnionBucket(other.level2sketch_[index]); } int atomicIntersectEstimator(size_t index, const ThisType& other) const { if(!singletonUnionBucket(index, other)) return -1; int estimate = 0; if( singletonBucket(index) && other.singletonBucket(index) ) estimate = 1; return estimate; } int atomicDiffEstimator(size_t index, const ThisType& other) const { if(!singletonUnionBucket(index, other)) return -1; int estimate = 0; if( singletonBucket(index) && other.emptyBucket(index) ) estimate = 1; return estimate; } private: std::vector<Level2BucketType> level2sketch_; }; template <typename ElemType> bool identicalSingletonBucket(const std::vector<Level2Sketch<ElemType> >& sketches, size_t index) { if(sketches.empty()) return false; for(size_t i = 0; i < sketches.size(); ++i) { if(!sketches[i].singletonBucket(index)) return false; } for(size_t bit_cnt_num = 0; bit_cnt_num < sizeof(ElemType)*8; ++bit_cnt_num) { uint32_t cur_cnt = sketches[0].getBucket(index).getBitCnt(bit_cnt_num); for(size_t sketch_i = 1; sketch_i < sketches.size(); ++sketch_i) { uint32_t other_cnt = sketches[sketch_i].getBucket(index).getBitCnt(bit_cnt_num); if( (cur_cnt > 0 && other_cnt == 0) || (cur_cnt == 0 && other_cnt > 0) ) return false; } } return true; } template <typename ElemType> bool singletonUnionBucket(const std::vector<Level2Sketch<ElemType> >& union_sketches, size_t index) { std::vector<Level2Sketch<ElemType> > non_empty_sketches; for(size_t i = 0; i < union_sketches.size(); ++i) { if(!union_sketches[i].emptyBucket(index)) non_empty_sketches.push_back(union_sketches[i]); } if(non_empty_sketches.size() == 1) { return non_empty_sketches[0].singletonBucket(index); } return identicalSingletonBucket(non_empty_sketches, index); } // do (and (or (union_sketches)) (or (union_sketches_2))) template <typename ElemType> int atomicUnionWithIntersectBucketEstimator(size_t index, const std::vector<Level2Sketch<ElemType> >& union_sketches, const std::vector<Level2Sketch<ElemType> >& union_sketches_2) { std::vector<Level2Sketch<ElemType> > all_sketches = union_sketches; all_sketches.insert(all_sketches.end(), union_sketches_2.begin(), union_sketches_2.end()); if(!singletonUnionBucket(all_sketches, index)) return -1; int estimate = 0; for(size_t i = 0; i < union_sketches.size(); ++i) { if(!union_sketches[i].emptyBucket(index)) { estimate = 1; break; } } if(estimate == 0) return 0; for(size_t i = 0; i < union_sketches_2.size(); ++i) { if(!union_sketches_2[i].emptyBucket(index)) { return 1; } } return 0; } template <typename ElemType> int atomicIntersectBucketEstimator(size_t index, const std::vector<Level2Sketch<ElemType> >& level2sketches) { if(!singletonUnionBucket(level2sketches, index)) return -1; for(size_t i = 0; i < level2sketches.size(); ++i) { if(level2sketches[i].emptyBucket(index)) { return 0; } } return 1; } template <typename ElemType> int atomicUnionBucketEstimator(size_t index, const std::vector<Level2Sketch<ElemType> >& level2sketches) { for(size_t i = 0; i < level2sketches.size(); ++i) { if(!level2sketches[i].emptyBucket(index)) { return 1; } } return 0; } NS_IZENELIB_UTIL_END #endif
26.636364
117
0.597483
[ "vector" ]
f9a8aeb1665b41621526ae72810c1825757026fa
39,773
cpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/IP_FORWARD_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/IP_FORWARD_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/IP_FORWARD_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "IP_FORWARD_MIB.hpp" using namespace ydk; namespace cisco_ios_xe { namespace IP_FORWARD_MIB { IPFORWARDMIB::IPFORWARDMIB() : ipforward(std::make_shared<IPFORWARDMIB::IpForward>()) , ipforwardtable(std::make_shared<IPFORWARDMIB::IpForwardTable>()) , ipcidrroutetable(std::make_shared<IPFORWARDMIB::IpCidrRouteTable>()) { ipforward->parent = this; ipforwardtable->parent = this; ipcidrroutetable->parent = this; yang_name = "IP-FORWARD-MIB"; yang_parent_name = "IP-FORWARD-MIB"; is_top_level_class = true; has_list_ancestor = false; } IPFORWARDMIB::~IPFORWARDMIB() { } bool IPFORWARDMIB::has_data() const { if (is_presence_container) return true; return (ipforward != nullptr && ipforward->has_data()) || (ipforwardtable != nullptr && ipforwardtable->has_data()) || (ipcidrroutetable != nullptr && ipcidrroutetable->has_data()); } bool IPFORWARDMIB::has_operation() const { return is_set(yfilter) || (ipforward != nullptr && ipforward->has_operation()) || (ipforwardtable != nullptr && ipforwardtable->has_operation()) || (ipcidrroutetable != nullptr && ipcidrroutetable->has_operation()); } std::string IPFORWARDMIB::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "IP-FORWARD-MIB:IP-FORWARD-MIB"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPFORWARDMIB::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPFORWARDMIB::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipForward") { if(ipforward == nullptr) { ipforward = std::make_shared<IPFORWARDMIB::IpForward>(); } return ipforward; } if(child_yang_name == "ipForwardTable") { if(ipforwardtable == nullptr) { ipforwardtable = std::make_shared<IPFORWARDMIB::IpForwardTable>(); } return ipforwardtable; } if(child_yang_name == "ipCidrRouteTable") { if(ipcidrroutetable == nullptr) { ipcidrroutetable = std::make_shared<IPFORWARDMIB::IpCidrRouteTable>(); } return ipcidrroutetable; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPFORWARDMIB::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(ipforward != nullptr) { _children["ipForward"] = ipforward; } if(ipforwardtable != nullptr) { _children["ipForwardTable"] = ipforwardtable; } if(ipcidrroutetable != nullptr) { _children["ipCidrRouteTable"] = ipcidrroutetable; } return _children; } void IPFORWARDMIB::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPFORWARDMIB::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> IPFORWARDMIB::clone_ptr() const { return std::make_shared<IPFORWARDMIB>(); } std::string IPFORWARDMIB::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string IPFORWARDMIB::get_bundle_name() const { return "cisco_ios_xe"; } augment_capabilities_function IPFORWARDMIB::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> IPFORWARDMIB::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool IPFORWARDMIB::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipForward" || name == "ipForwardTable" || name == "ipCidrRouteTable") return true; return false; } IPFORWARDMIB::IpForward::IpForward() : ipforwardnumber{YType::uint32, "ipForwardNumber"}, ipcidrroutenumber{YType::uint32, "ipCidrRouteNumber"} { yang_name = "ipForward"; yang_parent_name = "IP-FORWARD-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPFORWARDMIB::IpForward::~IpForward() { } bool IPFORWARDMIB::IpForward::has_data() const { if (is_presence_container) return true; return ipforwardnumber.is_set || ipcidrroutenumber.is_set; } bool IPFORWARDMIB::IpForward::has_operation() const { return is_set(yfilter) || ydk::is_set(ipforwardnumber.yfilter) || ydk::is_set(ipcidrroutenumber.yfilter); } std::string IPFORWARDMIB::IpForward::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-FORWARD-MIB:IP-FORWARD-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPFORWARDMIB::IpForward::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipForward"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPFORWARDMIB::IpForward::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipforwardnumber.is_set || is_set(ipforwardnumber.yfilter)) leaf_name_data.push_back(ipforwardnumber.get_name_leafdata()); if (ipcidrroutenumber.is_set || is_set(ipcidrroutenumber.yfilter)) leaf_name_data.push_back(ipcidrroutenumber.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPFORWARDMIB::IpForward::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPFORWARDMIB::IpForward::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPFORWARDMIB::IpForward::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipForwardNumber") { ipforwardnumber = value; ipforwardnumber.value_namespace = name_space; ipforwardnumber.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteNumber") { ipcidrroutenumber = value; ipcidrroutenumber.value_namespace = name_space; ipcidrroutenumber.value_namespace_prefix = name_space_prefix; } } void IPFORWARDMIB::IpForward::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipForwardNumber") { ipforwardnumber.yfilter = yfilter; } if(value_path == "ipCidrRouteNumber") { ipcidrroutenumber.yfilter = yfilter; } } bool IPFORWARDMIB::IpForward::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipForwardNumber" || name == "ipCidrRouteNumber") return true; return false; } IPFORWARDMIB::IpForwardTable::IpForwardTable() : ipforwardentry(this, {"ipforwarddest", "ipforwardproto", "ipforwardpolicy", "ipforwardnexthop"}) { yang_name = "ipForwardTable"; yang_parent_name = "IP-FORWARD-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPFORWARDMIB::IpForwardTable::~IpForwardTable() { } bool IPFORWARDMIB::IpForwardTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipforwardentry.len(); index++) { if(ipforwardentry[index]->has_data()) return true; } return false; } bool IPFORWARDMIB::IpForwardTable::has_operation() const { for (std::size_t index=0; index<ipforwardentry.len(); index++) { if(ipforwardentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPFORWARDMIB::IpForwardTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-FORWARD-MIB:IP-FORWARD-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPFORWARDMIB::IpForwardTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipForwardTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPFORWARDMIB::IpForwardTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPFORWARDMIB::IpForwardTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipForwardEntry") { auto ent_ = std::make_shared<IPFORWARDMIB::IpForwardTable::IpForwardEntry>(); ent_->parent = this; ipforwardentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPFORWARDMIB::IpForwardTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipforwardentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPFORWARDMIB::IpForwardTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPFORWARDMIB::IpForwardTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPFORWARDMIB::IpForwardTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipForwardEntry") return true; return false; } IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardEntry() : ipforwarddest{YType::str, "ipForwardDest"}, ipforwardproto{YType::enumeration, "ipForwardProto"}, ipforwardpolicy{YType::int32, "ipForwardPolicy"}, ipforwardnexthop{YType::str, "ipForwardNextHop"}, ipforwardmask{YType::str, "ipForwardMask"}, ipforwardifindex{YType::int32, "ipForwardIfIndex"}, ipforwardtype{YType::enumeration, "ipForwardType"}, ipforwardage{YType::int32, "ipForwardAge"}, ipforwardinfo{YType::str, "ipForwardInfo"}, ipforwardnexthopas{YType::int32, "ipForwardNextHopAS"}, ipforwardmetric1{YType::int32, "ipForwardMetric1"}, ipforwardmetric2{YType::int32, "ipForwardMetric2"}, ipforwardmetric3{YType::int32, "ipForwardMetric3"}, ipforwardmetric4{YType::int32, "ipForwardMetric4"}, ipforwardmetric5{YType::int32, "ipForwardMetric5"} { yang_name = "ipForwardEntry"; yang_parent_name = "ipForwardTable"; is_top_level_class = false; has_list_ancestor = false; } IPFORWARDMIB::IpForwardTable::IpForwardEntry::~IpForwardEntry() { } bool IPFORWARDMIB::IpForwardTable::IpForwardEntry::has_data() const { if (is_presence_container) return true; return ipforwarddest.is_set || ipforwardproto.is_set || ipforwardpolicy.is_set || ipforwardnexthop.is_set || ipforwardmask.is_set || ipforwardifindex.is_set || ipforwardtype.is_set || ipforwardage.is_set || ipforwardinfo.is_set || ipforwardnexthopas.is_set || ipforwardmetric1.is_set || ipforwardmetric2.is_set || ipforwardmetric3.is_set || ipforwardmetric4.is_set || ipforwardmetric5.is_set; } bool IPFORWARDMIB::IpForwardTable::IpForwardEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipforwarddest.yfilter) || ydk::is_set(ipforwardproto.yfilter) || ydk::is_set(ipforwardpolicy.yfilter) || ydk::is_set(ipforwardnexthop.yfilter) || ydk::is_set(ipforwardmask.yfilter) || ydk::is_set(ipforwardifindex.yfilter) || ydk::is_set(ipforwardtype.yfilter) || ydk::is_set(ipforwardage.yfilter) || ydk::is_set(ipforwardinfo.yfilter) || ydk::is_set(ipforwardnexthopas.yfilter) || ydk::is_set(ipforwardmetric1.yfilter) || ydk::is_set(ipforwardmetric2.yfilter) || ydk::is_set(ipforwardmetric3.yfilter) || ydk::is_set(ipforwardmetric4.yfilter) || ydk::is_set(ipforwardmetric5.yfilter); } std::string IPFORWARDMIB::IpForwardTable::IpForwardEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-FORWARD-MIB:IP-FORWARD-MIB/ipForwardTable/" << get_segment_path(); return path_buffer.str(); } std::string IPFORWARDMIB::IpForwardTable::IpForwardEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipForwardEntry"; ADD_KEY_TOKEN(ipforwarddest, "ipForwardDest"); ADD_KEY_TOKEN(ipforwardproto, "ipForwardProto"); ADD_KEY_TOKEN(ipforwardpolicy, "ipForwardPolicy"); ADD_KEY_TOKEN(ipforwardnexthop, "ipForwardNextHop"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPFORWARDMIB::IpForwardTable::IpForwardEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipforwarddest.is_set || is_set(ipforwarddest.yfilter)) leaf_name_data.push_back(ipforwarddest.get_name_leafdata()); if (ipforwardproto.is_set || is_set(ipforwardproto.yfilter)) leaf_name_data.push_back(ipforwardproto.get_name_leafdata()); if (ipforwardpolicy.is_set || is_set(ipforwardpolicy.yfilter)) leaf_name_data.push_back(ipforwardpolicy.get_name_leafdata()); if (ipforwardnexthop.is_set || is_set(ipforwardnexthop.yfilter)) leaf_name_data.push_back(ipforwardnexthop.get_name_leafdata()); if (ipforwardmask.is_set || is_set(ipforwardmask.yfilter)) leaf_name_data.push_back(ipforwardmask.get_name_leafdata()); if (ipforwardifindex.is_set || is_set(ipforwardifindex.yfilter)) leaf_name_data.push_back(ipforwardifindex.get_name_leafdata()); if (ipforwardtype.is_set || is_set(ipforwardtype.yfilter)) leaf_name_data.push_back(ipforwardtype.get_name_leafdata()); if (ipforwardage.is_set || is_set(ipforwardage.yfilter)) leaf_name_data.push_back(ipforwardage.get_name_leafdata()); if (ipforwardinfo.is_set || is_set(ipforwardinfo.yfilter)) leaf_name_data.push_back(ipforwardinfo.get_name_leafdata()); if (ipforwardnexthopas.is_set || is_set(ipforwardnexthopas.yfilter)) leaf_name_data.push_back(ipforwardnexthopas.get_name_leafdata()); if (ipforwardmetric1.is_set || is_set(ipforwardmetric1.yfilter)) leaf_name_data.push_back(ipforwardmetric1.get_name_leafdata()); if (ipforwardmetric2.is_set || is_set(ipforwardmetric2.yfilter)) leaf_name_data.push_back(ipforwardmetric2.get_name_leafdata()); if (ipforwardmetric3.is_set || is_set(ipforwardmetric3.yfilter)) leaf_name_data.push_back(ipforwardmetric3.get_name_leafdata()); if (ipforwardmetric4.is_set || is_set(ipforwardmetric4.yfilter)) leaf_name_data.push_back(ipforwardmetric4.get_name_leafdata()); if (ipforwardmetric5.is_set || is_set(ipforwardmetric5.yfilter)) leaf_name_data.push_back(ipforwardmetric5.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPFORWARDMIB::IpForwardTable::IpForwardEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPFORWARDMIB::IpForwardTable::IpForwardEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPFORWARDMIB::IpForwardTable::IpForwardEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipForwardDest") { ipforwarddest = value; ipforwarddest.value_namespace = name_space; ipforwarddest.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardProto") { ipforwardproto = value; ipforwardproto.value_namespace = name_space; ipforwardproto.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardPolicy") { ipforwardpolicy = value; ipforwardpolicy.value_namespace = name_space; ipforwardpolicy.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardNextHop") { ipforwardnexthop = value; ipforwardnexthop.value_namespace = name_space; ipforwardnexthop.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardMask") { ipforwardmask = value; ipforwardmask.value_namespace = name_space; ipforwardmask.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardIfIndex") { ipforwardifindex = value; ipforwardifindex.value_namespace = name_space; ipforwardifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardType") { ipforwardtype = value; ipforwardtype.value_namespace = name_space; ipforwardtype.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardAge") { ipforwardage = value; ipforwardage.value_namespace = name_space; ipforwardage.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardInfo") { ipforwardinfo = value; ipforwardinfo.value_namespace = name_space; ipforwardinfo.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardNextHopAS") { ipforwardnexthopas = value; ipforwardnexthopas.value_namespace = name_space; ipforwardnexthopas.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardMetric1") { ipforwardmetric1 = value; ipforwardmetric1.value_namespace = name_space; ipforwardmetric1.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardMetric2") { ipforwardmetric2 = value; ipforwardmetric2.value_namespace = name_space; ipforwardmetric2.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardMetric3") { ipforwardmetric3 = value; ipforwardmetric3.value_namespace = name_space; ipforwardmetric3.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardMetric4") { ipforwardmetric4 = value; ipforwardmetric4.value_namespace = name_space; ipforwardmetric4.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwardMetric5") { ipforwardmetric5 = value; ipforwardmetric5.value_namespace = name_space; ipforwardmetric5.value_namespace_prefix = name_space_prefix; } } void IPFORWARDMIB::IpForwardTable::IpForwardEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipForwardDest") { ipforwarddest.yfilter = yfilter; } if(value_path == "ipForwardProto") { ipforwardproto.yfilter = yfilter; } if(value_path == "ipForwardPolicy") { ipforwardpolicy.yfilter = yfilter; } if(value_path == "ipForwardNextHop") { ipforwardnexthop.yfilter = yfilter; } if(value_path == "ipForwardMask") { ipforwardmask.yfilter = yfilter; } if(value_path == "ipForwardIfIndex") { ipforwardifindex.yfilter = yfilter; } if(value_path == "ipForwardType") { ipforwardtype.yfilter = yfilter; } if(value_path == "ipForwardAge") { ipforwardage.yfilter = yfilter; } if(value_path == "ipForwardInfo") { ipforwardinfo.yfilter = yfilter; } if(value_path == "ipForwardNextHopAS") { ipforwardnexthopas.yfilter = yfilter; } if(value_path == "ipForwardMetric1") { ipforwardmetric1.yfilter = yfilter; } if(value_path == "ipForwardMetric2") { ipforwardmetric2.yfilter = yfilter; } if(value_path == "ipForwardMetric3") { ipforwardmetric3.yfilter = yfilter; } if(value_path == "ipForwardMetric4") { ipforwardmetric4.yfilter = yfilter; } if(value_path == "ipForwardMetric5") { ipforwardmetric5.yfilter = yfilter; } } bool IPFORWARDMIB::IpForwardTable::IpForwardEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipForwardDest" || name == "ipForwardProto" || name == "ipForwardPolicy" || name == "ipForwardNextHop" || name == "ipForwardMask" || name == "ipForwardIfIndex" || name == "ipForwardType" || name == "ipForwardAge" || name == "ipForwardInfo" || name == "ipForwardNextHopAS" || name == "ipForwardMetric1" || name == "ipForwardMetric2" || name == "ipForwardMetric3" || name == "ipForwardMetric4" || name == "ipForwardMetric5") return true; return false; } IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteTable() : ipcidrrouteentry(this, {"ipcidrroutedest", "ipcidrroutemask", "ipcidrroutetos", "ipcidrroutenexthop"}) { yang_name = "ipCidrRouteTable"; yang_parent_name = "IP-FORWARD-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPFORWARDMIB::IpCidrRouteTable::~IpCidrRouteTable() { } bool IPFORWARDMIB::IpCidrRouteTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipcidrrouteentry.len(); index++) { if(ipcidrrouteentry[index]->has_data()) return true; } return false; } bool IPFORWARDMIB::IpCidrRouteTable::has_operation() const { for (std::size_t index=0; index<ipcidrrouteentry.len(); index++) { if(ipcidrrouteentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPFORWARDMIB::IpCidrRouteTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-FORWARD-MIB:IP-FORWARD-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPFORWARDMIB::IpCidrRouteTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipCidrRouteTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPFORWARDMIB::IpCidrRouteTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPFORWARDMIB::IpCidrRouteTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipCidrRouteEntry") { auto ent_ = std::make_shared<IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry>(); ent_->parent = this; ipcidrrouteentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPFORWARDMIB::IpCidrRouteTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipcidrrouteentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPFORWARDMIB::IpCidrRouteTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPFORWARDMIB::IpCidrRouteTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPFORWARDMIB::IpCidrRouteTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipCidrRouteEntry") return true; return false; } IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteEntry() : ipcidrroutedest{YType::str, "ipCidrRouteDest"}, ipcidrroutemask{YType::str, "ipCidrRouteMask"}, ipcidrroutetos{YType::int32, "ipCidrRouteTos"}, ipcidrroutenexthop{YType::str, "ipCidrRouteNextHop"}, ipcidrrouteifindex{YType::int32, "ipCidrRouteIfIndex"}, ipcidrroutetype{YType::enumeration, "ipCidrRouteType"}, ipcidrrouteproto{YType::enumeration, "ipCidrRouteProto"}, ipcidrrouteage{YType::int32, "ipCidrRouteAge"}, ipcidrrouteinfo{YType::str, "ipCidrRouteInfo"}, ipcidrroutenexthopas{YType::int32, "ipCidrRouteNextHopAS"}, ipcidrroutemetric1{YType::int32, "ipCidrRouteMetric1"}, ipcidrroutemetric2{YType::int32, "ipCidrRouteMetric2"}, ipcidrroutemetric3{YType::int32, "ipCidrRouteMetric3"}, ipcidrroutemetric4{YType::int32, "ipCidrRouteMetric4"}, ipcidrroutemetric5{YType::int32, "ipCidrRouteMetric5"}, ipcidrroutestatus{YType::enumeration, "ipCidrRouteStatus"} { yang_name = "ipCidrRouteEntry"; yang_parent_name = "ipCidrRouteTable"; is_top_level_class = false; has_list_ancestor = false; } IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::~IpCidrRouteEntry() { } bool IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::has_data() const { if (is_presence_container) return true; return ipcidrroutedest.is_set || ipcidrroutemask.is_set || ipcidrroutetos.is_set || ipcidrroutenexthop.is_set || ipcidrrouteifindex.is_set || ipcidrroutetype.is_set || ipcidrrouteproto.is_set || ipcidrrouteage.is_set || ipcidrrouteinfo.is_set || ipcidrroutenexthopas.is_set || ipcidrroutemetric1.is_set || ipcidrroutemetric2.is_set || ipcidrroutemetric3.is_set || ipcidrroutemetric4.is_set || ipcidrroutemetric5.is_set || ipcidrroutestatus.is_set; } bool IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipcidrroutedest.yfilter) || ydk::is_set(ipcidrroutemask.yfilter) || ydk::is_set(ipcidrroutetos.yfilter) || ydk::is_set(ipcidrroutenexthop.yfilter) || ydk::is_set(ipcidrrouteifindex.yfilter) || ydk::is_set(ipcidrroutetype.yfilter) || ydk::is_set(ipcidrrouteproto.yfilter) || ydk::is_set(ipcidrrouteage.yfilter) || ydk::is_set(ipcidrrouteinfo.yfilter) || ydk::is_set(ipcidrroutenexthopas.yfilter) || ydk::is_set(ipcidrroutemetric1.yfilter) || ydk::is_set(ipcidrroutemetric2.yfilter) || ydk::is_set(ipcidrroutemetric3.yfilter) || ydk::is_set(ipcidrroutemetric4.yfilter) || ydk::is_set(ipcidrroutemetric5.yfilter) || ydk::is_set(ipcidrroutestatus.yfilter); } std::string IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-FORWARD-MIB:IP-FORWARD-MIB/ipCidrRouteTable/" << get_segment_path(); return path_buffer.str(); } std::string IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipCidrRouteEntry"; ADD_KEY_TOKEN(ipcidrroutedest, "ipCidrRouteDest"); ADD_KEY_TOKEN(ipcidrroutemask, "ipCidrRouteMask"); ADD_KEY_TOKEN(ipcidrroutetos, "ipCidrRouteTos"); ADD_KEY_TOKEN(ipcidrroutenexthop, "ipCidrRouteNextHop"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipcidrroutedest.is_set || is_set(ipcidrroutedest.yfilter)) leaf_name_data.push_back(ipcidrroutedest.get_name_leafdata()); if (ipcidrroutemask.is_set || is_set(ipcidrroutemask.yfilter)) leaf_name_data.push_back(ipcidrroutemask.get_name_leafdata()); if (ipcidrroutetos.is_set || is_set(ipcidrroutetos.yfilter)) leaf_name_data.push_back(ipcidrroutetos.get_name_leafdata()); if (ipcidrroutenexthop.is_set || is_set(ipcidrroutenexthop.yfilter)) leaf_name_data.push_back(ipcidrroutenexthop.get_name_leafdata()); if (ipcidrrouteifindex.is_set || is_set(ipcidrrouteifindex.yfilter)) leaf_name_data.push_back(ipcidrrouteifindex.get_name_leafdata()); if (ipcidrroutetype.is_set || is_set(ipcidrroutetype.yfilter)) leaf_name_data.push_back(ipcidrroutetype.get_name_leafdata()); if (ipcidrrouteproto.is_set || is_set(ipcidrrouteproto.yfilter)) leaf_name_data.push_back(ipcidrrouteproto.get_name_leafdata()); if (ipcidrrouteage.is_set || is_set(ipcidrrouteage.yfilter)) leaf_name_data.push_back(ipcidrrouteage.get_name_leafdata()); if (ipcidrrouteinfo.is_set || is_set(ipcidrrouteinfo.yfilter)) leaf_name_data.push_back(ipcidrrouteinfo.get_name_leafdata()); if (ipcidrroutenexthopas.is_set || is_set(ipcidrroutenexthopas.yfilter)) leaf_name_data.push_back(ipcidrroutenexthopas.get_name_leafdata()); if (ipcidrroutemetric1.is_set || is_set(ipcidrroutemetric1.yfilter)) leaf_name_data.push_back(ipcidrroutemetric1.get_name_leafdata()); if (ipcidrroutemetric2.is_set || is_set(ipcidrroutemetric2.yfilter)) leaf_name_data.push_back(ipcidrroutemetric2.get_name_leafdata()); if (ipcidrroutemetric3.is_set || is_set(ipcidrroutemetric3.yfilter)) leaf_name_data.push_back(ipcidrroutemetric3.get_name_leafdata()); if (ipcidrroutemetric4.is_set || is_set(ipcidrroutemetric4.yfilter)) leaf_name_data.push_back(ipcidrroutemetric4.get_name_leafdata()); if (ipcidrroutemetric5.is_set || is_set(ipcidrroutemetric5.yfilter)) leaf_name_data.push_back(ipcidrroutemetric5.get_name_leafdata()); if (ipcidrroutestatus.is_set || is_set(ipcidrroutestatus.yfilter)) leaf_name_data.push_back(ipcidrroutestatus.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipCidrRouteDest") { ipcidrroutedest = value; ipcidrroutedest.value_namespace = name_space; ipcidrroutedest.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteMask") { ipcidrroutemask = value; ipcidrroutemask.value_namespace = name_space; ipcidrroutemask.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteTos") { ipcidrroutetos = value; ipcidrroutetos.value_namespace = name_space; ipcidrroutetos.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteNextHop") { ipcidrroutenexthop = value; ipcidrroutenexthop.value_namespace = name_space; ipcidrroutenexthop.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteIfIndex") { ipcidrrouteifindex = value; ipcidrrouteifindex.value_namespace = name_space; ipcidrrouteifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteType") { ipcidrroutetype = value; ipcidrroutetype.value_namespace = name_space; ipcidrroutetype.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteProto") { ipcidrrouteproto = value; ipcidrrouteproto.value_namespace = name_space; ipcidrrouteproto.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteAge") { ipcidrrouteage = value; ipcidrrouteage.value_namespace = name_space; ipcidrrouteage.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteInfo") { ipcidrrouteinfo = value; ipcidrrouteinfo.value_namespace = name_space; ipcidrrouteinfo.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteNextHopAS") { ipcidrroutenexthopas = value; ipcidrroutenexthopas.value_namespace = name_space; ipcidrroutenexthopas.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteMetric1") { ipcidrroutemetric1 = value; ipcidrroutemetric1.value_namespace = name_space; ipcidrroutemetric1.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteMetric2") { ipcidrroutemetric2 = value; ipcidrroutemetric2.value_namespace = name_space; ipcidrroutemetric2.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteMetric3") { ipcidrroutemetric3 = value; ipcidrroutemetric3.value_namespace = name_space; ipcidrroutemetric3.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteMetric4") { ipcidrroutemetric4 = value; ipcidrroutemetric4.value_namespace = name_space; ipcidrroutemetric4.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteMetric5") { ipcidrroutemetric5 = value; ipcidrroutemetric5.value_namespace = name_space; ipcidrroutemetric5.value_namespace_prefix = name_space_prefix; } if(value_path == "ipCidrRouteStatus") { ipcidrroutestatus = value; ipcidrroutestatus.value_namespace = name_space; ipcidrroutestatus.value_namespace_prefix = name_space_prefix; } } void IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipCidrRouteDest") { ipcidrroutedest.yfilter = yfilter; } if(value_path == "ipCidrRouteMask") { ipcidrroutemask.yfilter = yfilter; } if(value_path == "ipCidrRouteTos") { ipcidrroutetos.yfilter = yfilter; } if(value_path == "ipCidrRouteNextHop") { ipcidrroutenexthop.yfilter = yfilter; } if(value_path == "ipCidrRouteIfIndex") { ipcidrrouteifindex.yfilter = yfilter; } if(value_path == "ipCidrRouteType") { ipcidrroutetype.yfilter = yfilter; } if(value_path == "ipCidrRouteProto") { ipcidrrouteproto.yfilter = yfilter; } if(value_path == "ipCidrRouteAge") { ipcidrrouteage.yfilter = yfilter; } if(value_path == "ipCidrRouteInfo") { ipcidrrouteinfo.yfilter = yfilter; } if(value_path == "ipCidrRouteNextHopAS") { ipcidrroutenexthopas.yfilter = yfilter; } if(value_path == "ipCidrRouteMetric1") { ipcidrroutemetric1.yfilter = yfilter; } if(value_path == "ipCidrRouteMetric2") { ipcidrroutemetric2.yfilter = yfilter; } if(value_path == "ipCidrRouteMetric3") { ipcidrroutemetric3.yfilter = yfilter; } if(value_path == "ipCidrRouteMetric4") { ipcidrroutemetric4.yfilter = yfilter; } if(value_path == "ipCidrRouteMetric5") { ipcidrroutemetric5.yfilter = yfilter; } if(value_path == "ipCidrRouteStatus") { ipcidrroutestatus.yfilter = yfilter; } } bool IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipCidrRouteDest" || name == "ipCidrRouteMask" || name == "ipCidrRouteTos" || name == "ipCidrRouteNextHop" || name == "ipCidrRouteIfIndex" || name == "ipCidrRouteType" || name == "ipCidrRouteProto" || name == "ipCidrRouteAge" || name == "ipCidrRouteInfo" || name == "ipCidrRouteNextHopAS" || name == "ipCidrRouteMetric1" || name == "ipCidrRouteMetric2" || name == "ipCidrRouteMetric3" || name == "ipCidrRouteMetric4" || name == "ipCidrRouteMetric5" || name == "ipCidrRouteStatus") return true; return false; } const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::other {1, "other"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::local {2, "local"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::netmgmt {3, "netmgmt"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::icmp {4, "icmp"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::egp {5, "egp"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::ggp {6, "ggp"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::hello {7, "hello"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::rip {8, "rip"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::is_is {9, "is-is"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::es_is {10, "es-is"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::ciscoIgrp {11, "ciscoIgrp"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::bbnSpfIgp {12, "bbnSpfIgp"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::ospf {13, "ospf"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::bgp {14, "bgp"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardProto::idpr {15, "idpr"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardType::other {1, "other"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardType::invalid {2, "invalid"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardType::local {3, "local"}; const Enum::YLeaf IPFORWARDMIB::IpForwardTable::IpForwardEntry::IpForwardType::remote {4, "remote"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteType::other {1, "other"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteType::reject {2, "reject"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteType::local {3, "local"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteType::remote {4, "remote"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::other {1, "other"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::local {2, "local"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::netmgmt {3, "netmgmt"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::icmp {4, "icmp"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::egp {5, "egp"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::ggp {6, "ggp"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::hello {7, "hello"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::rip {8, "rip"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::isIs {9, "isIs"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::esIs {10, "esIs"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::ciscoIgrp {11, "ciscoIgrp"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::bbnSpfIgp {12, "bbnSpfIgp"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::ospf {13, "ospf"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::bgp {14, "bgp"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::idpr {15, "idpr"}; const Enum::YLeaf IPFORWARDMIB::IpCidrRouteTable::IpCidrRouteEntry::IpCidrRouteProto::ciscoEigrp {16, "ciscoEigrp"}; } }
36.589696
495
0.723204
[ "vector" ]
3911127d6c46e470308b7277de6b010a89d1a0ed
12,978
cpp
C++
OpenGLSandbox/src/Engine/Rendering/Mesh.cpp
conholo/OpenGLSandbox
c8c35f275dacd9c873c78aa003b840822db719a8
[ "MIT" ]
null
null
null
OpenGLSandbox/src/Engine/Rendering/Mesh.cpp
conholo/OpenGLSandbox
c8c35f275dacd9c873c78aa003b840822db719a8
[ "MIT" ]
null
null
null
OpenGLSandbox/src/Engine/Rendering/Mesh.cpp
conholo/OpenGLSandbox
c8c35f275dacd9c873c78aa003b840822db719a8
[ "MIT" ]
null
null
null
#include "Engine/Rendering/Mesh.h" #include "Engine/Core/Math.h" #include <iostream> #include <unordered_map> namespace Engine { #define PI 3.14159265359 Mesh::Mesh(float* vertices, uint32_t vertexCount, uint32_t* indices, uint32_t indexCount) { m_Vertices.resize(vertexCount); memcpy(m_Vertices.data(), vertices, vertexCount * sizeof(Vertex)); m_Indices.resize(indexCount); memcpy(m_Indices.data(), indices, indexCount * sizeof(uint32_t)); } Mesh::Mesh() { } void Mesh::ResetVertices(float* vertices, uint32_t vertexCount) { m_Vertices.clear(); m_Vertices.resize(vertexCount); memcpy(m_Vertices.data(), vertices, vertexCount * sizeof(Vertex)); } void Mesh::ResetIndices(uint32_t* indices, uint32_t indexCount) { m_Indices.clear(); m_Indices.resize(indexCount); memcpy(m_Indices.data(), indices, indexCount * sizeof(uint32_t)); } Ref<Mesh> MeshFactory::Create(PrimitiveType primitiveType) { switch (primitiveType) { case PrimitiveType::Plane: return Plane(); case PrimitiveType::Quad: return Quad(); case PrimitiveType::FullScreenQuad: return FullScreenQuad(); case PrimitiveType::Triangle: return Triangle(); case PrimitiveType::Cube: return Cube(); case PrimitiveType::Sphere: return Sphere(1.0f); case PrimitiveType::TessellatedQuad: return TessellatedQuad(10); } return nullptr; } Ref<Mesh> MeshFactory::Plane() { std::vector<Vertex> vertices = { Vertex{ {-0.5f, 0.0f, 0.5f}, {0.0f, 0.0f}, {0.0f, 1.0f, 0.0f} }, Vertex{ { 0.5f, 0.0f, 0.5f}, {1.0f, 0.0f}, {0.0f, 1.0f, 0.0f} }, Vertex{ { 0.5f, 0.0f, -0.5f}, {1.0f, 1.0f}, {0.0f, 1.0f, 0.0f} }, Vertex{ {-0.5f, 0.0f, -0.5f}, {0.0f, 1.0f}, {0.0f, 1.0f, 0.0f} }, }; std::vector<uint32_t> indices = { 0, 1, 2, 2, 3, 0 }; return CreateRef<Mesh>(vertices, indices); } Ref<Mesh> MeshFactory::Triangle() { std::vector<Vertex> vertices = { // Front Face Vertex{ {-0.5f, -0.5f, 0.0f}, {0.0f, 0.0f}, { 0.0f, 0.0f, 1.0f } }, // 0 0 Vertex{ { 0.5f, -0.5f, 0.0f}, {1.0f, 0.0f}, { 0.0f, 0.0f, 1.0f } }, // 1 1 Vertex{ { 0.0f, 0.5f, 0.0f}, {0.5f, 1.0f}, { 0.0f, 0.0f, 1.0f } }, // 2 2 }; std::vector<uint32_t> indices = { 0, 1, 2 }; return CreateRef<Mesh>(vertices, indices); } Ref<Mesh> MeshFactory::Quad() { std::vector<Vertex> vertices = { Vertex{ {-0.5f, -0.5f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f} }, Vertex{ { 0.5f, -0.5f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f} }, Vertex{ { 0.5f, 0.5f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f} }, Vertex{ {-0.5f, 0.5f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f} }, }; std::vector<uint32_t> indices = { 0, 1, 2, 2, 3, 0 }; return CreateRef<Mesh>(vertices, indices); } Ref<Mesh> MeshFactory::FullScreenQuad() { std::vector<Vertex> vertices = { Vertex{ {-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f} }, Vertex{ { 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f} }, Vertex{ { 1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f} }, Vertex{ {-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f} }, }; std::vector<uint32_t> indices = { 0, 1, 2, 2, 3, 0 }; return CreateRef<Mesh>(vertices, indices); } Ref<Mesh> MeshFactory::Cube() { std::vector<Vertex> vertices = { // Front Face Vertex{ {-0.5f, -0.5f, 0.5f}, {0.0f, 0.0f}, { 0.0f, 0.0f, 1.0f } }, // 0 0 Vertex{ { 0.5f, -0.5f, 0.5f}, {1.0f, 0.0f}, { 0.0f, 0.0f, 1.0f } }, // 1 1 Vertex{ { 0.5f, 0.5f, 0.5f}, {1.0f, 1.0f}, { 0.0f, 0.0f, 1.0f } }, // 2 2 Vertex{ {-0.5f, 0.5f, 0.5f}, {0.0f, 1.0f}, { 0.0f, 0.0f, 1.0f } }, // 3 3 // Right Face Vertex{ { 0.5f, -0.5f, 0.5f}, {0.0f, 0.0f}, { 1.0f, 0.0f, 0.0f } }, // 1 4 Vertex{ { 0.5f, -0.5f, -0.5f}, {1.0f, 0.0f}, { 1.0f, 0.0f, 0.0f } }, // 5 5 Vertex{ { 0.5f, 0.5f, -0.5f}, {1.0f, 1.0f}, { 1.0f, 0.0f, 0.0f } }, // 6 6 Vertex{ { 0.5f, 0.5f, 0.5f}, {0.0f, 1.0f}, { 1.0f, 0.0f, 0.0f } }, // 2 7 // Back Face Vertex{ { 0.5f, -0.5f, -0.5f}, {0.0f, 0.0f}, { 0.0f, 0.0f, -1.0f } }, // 4 8 Vertex{ {-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f}, { 0.0f, 0.0f, -1.0f } }, // 5 9 Vertex{ {-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f}, { 0.0f, 0.0f, -1.0f } }, // 6 10 Vertex{ { 0.5f, 0.5f, -0.5f}, {0.0f, 1.0f}, { 0.0f, 0.0f, -1.0f } }, // 7 11 // Left Face Vertex{ {-0.5f, -0.5f, -0.5f}, {0.0f, 0.0f}, { -1.0f, 0.0f, 0.0f } }, // 0 12 Vertex{ {-0.5f, -0.5f, 0.5f}, {1.0f, 0.0f}, { -1.0f, 0.0f, 0.0f } }, // 4 13 Vertex{ {-0.5f, 0.5f, 0.5f}, {1.0f, 1.0f}, { -1.0f, 0.0f, 0.0f } }, // 7 14 Vertex{ {-0.5f, 0.5f, -0.5f}, {0.0f, 1.0f}, { -1.0f, 0.0f, 0.0f } }, // 3 15 // Bottom Face Vertex{ { 0.5f, -0.5f, 0.5f}, {0.0f, 0.0f}, { 0.0f, -1.0f, 0.0f } }, // 0 16 Vertex{ {-0.5f, -0.5f, 0.5f}, {1.0f, 0.0f}, { 0.0f, -1.0f, 0.0f } }, // 1 17 Vertex{ {-0.5f, -0.5f, -0.5f}, {1.0f, 1.0f}, { 0.0f, -1.0f, 0.0f } }, // 5 18 Vertex{ { 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f}, { 0.0f, -1.0f, 0.0f } }, // 4 19 // Top Face Vertex{ {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f}, { 0.0f, 1.0f, 0.0f } }, // 3 20 Vertex{ { 0.5f, 0.5f, 0.5f}, {1.0f, 0.0f}, { 0.0f, 1.0f, 0.0f } }, // 2 21 Vertex{ { 0.5f, 0.5f, -0.5f}, {1.0f, 1.0f}, { 0.0f, 1.0f, 0.0f } }, // 6 22 Vertex{ {-0.5f, 0.5f, -0.5f}, {0.0f, 1.0f}, { 0.0f, 1.0f, 0.0f } } // 7 23 }; std::vector<uint32_t> indices = { // front 0, 1, 2, 2, 3, 0, // right 4, 5, 6, 6, 7, 4, // back 8, 9, 10, 10, 11, 8, // left 12, 13, 14, 14, 15, 12, // bottom 16, 17, 18, 18, 19, 16, // top 20, 21, 22, 22, 23, 20 }; return CreateRef<Mesh>(vertices, indices); } Ref<Mesh> MeshFactory::Sphere(float radius) { std::vector<Vertex> vertices; std::vector<uint32_t> indices; constexpr float latitudeBands = 30; constexpr float longitudeBands = 30; for (float latitude = 0.0f; latitude <= latitudeBands; latitude++) { const float theta = latitude * (float)PI / latitudeBands; const float sinTheta = glm::sin(theta); const float cosTheta = glm::cos(theta); float texT = 1.0f - theta / PI; for (float longitude = 0.0f; longitude <= longitudeBands; longitude++) { const float phi = longitude * 2.0f * (float)PI / longitudeBands; const float sinPhi = glm::sin(phi); const float cosPhi = glm::cos(phi); float texS = 1.0f - (phi / (2 * PI)); Vertex vertex; vertex.Normal = { cosPhi * sinTheta, cosTheta, sinPhi * sinTheta }; vertex.TexCoord = { texS, texT }; vertex.Position = { radius * vertex.Normal.x, radius * vertex.Normal.y, radius * vertex.Normal.z }; vertices.push_back(vertex); } } for (uint32_t latitude = 0; latitude < (uint32_t)latitudeBands; latitude++) { for (uint32_t longitude = 0; longitude < (uint32_t)longitudeBands; longitude++) { const uint32_t first = (latitude * ((uint32_t)longitudeBands + 1)) + longitude; const uint32_t second = first + (uint32_t)longitudeBands + 1; indices.push_back(first); indices.push_back(first + 1); indices.push_back(second); indices.push_back(second); indices.push_back(first + 1); indices.push_back(second + 1); } } return CreateRef<Mesh>(vertices, indices); } static int AddIcosphereVertex(const glm::vec3& v, std::vector<Vertex>& vertices, uint32_t* index) { float length = glm::length(v); glm::vec3 unitSphereV = v / length; vertices.push_back({ {unitSphereV.x, unitSphereV.y, unitSphereV.z}, {0.0f, 0.0f}, {unitSphereV.x, unitSphereV.y, unitSphereV.z} }); return (*(index))++; } static uint32_t GetIcosphereMidpoint(int p1, int p2, std::unordered_map<uint64_t, int>& midpointCache, std::vector<Vertex>& vertices, uint32_t* index) { bool firstIsSmaller = p1 < p2; uint64_t smallerIndex = firstIsSmaller ? p1 : p2; uint64_t largerIndex = firstIsSmaller ? p2 : p1; uint64_t key = (smallerIndex << 32) + largerIndex; if (midpointCache.find(key) != midpointCache.end()) return midpointCache[key]; Vertex v1 = vertices[p1]; Vertex v2 = vertices[p2]; glm::vec3 mid = (v1.Position + v2.Position) / 2.0f; int vertexIndex = AddIcosphereVertex(mid, vertices, index); midpointCache[key] = vertexIndex; return vertexIndex; } Ref<Mesh> MeshFactory::Icosphere(uint32_t level, float radius) { float t = (1.0f + glm::sqrt(5.0f)) / 2.0f; uint32_t vertexIndex = 0; std::vector<Vertex> vertices; AddIcosphereVertex({ -1.0f, t, 0.0f }, vertices, &vertexIndex); AddIcosphereVertex({ 1.0f, t, 0.0f }, vertices, &vertexIndex); AddIcosphereVertex({ -1.0f, -t, 0.0f }, vertices, &vertexIndex); AddIcosphereVertex({ 1.0f, -t, 0.0f }, vertices, &vertexIndex); AddIcosphereVertex({ -0.0f, -1.0f, t }, vertices, &vertexIndex); AddIcosphereVertex({ -0.0f, 1.0f, t }, vertices, &vertexIndex); AddIcosphereVertex({ -0.0f, -1.0f, -t }, vertices, &vertexIndex); AddIcosphereVertex({ -0.0f, 1.0f, -t }, vertices, &vertexIndex); AddIcosphereVertex({ t, 0.0f, -1.0f }, vertices, &vertexIndex); AddIcosphereVertex({ t, 0.0f, 1.0f }, vertices, &vertexIndex); AddIcosphereVertex({ -t, 0.0f, -1.0f }, vertices, &vertexIndex); AddIcosphereVertex({ -t, 0.0f, 1.0f }, vertices, &vertexIndex); struct Triangle { uint32_t A, B, C; }; std::vector<Triangle> facesOne; facesOne.push_back({ 0, 11, 5 }); facesOne.push_back({ 0, 5, 1 }); facesOne.push_back({ 0, 1, 7 }); facesOne.push_back({ 0, 7, 10 }); facesOne.push_back({ 0, 10, 11 }); // 5 adjacent faces facesOne.push_back({ 1, 5, 9 }); facesOne.push_back({ 5, 11, 4 }); facesOne.push_back({ 11, 10, 2 }); facesOne.push_back({ 10, 7, 6 }); facesOne.push_back({ 7, 1, 8 });; // 5 faces around point 3 facesOne.push_back({ 3, 9, 4 }); facesOne.push_back({ 3, 4, 2 }); facesOne.push_back({ 3, 2, 6 }); facesOne.push_back({ 3, 6, 8 }); facesOne.push_back({ 3, 8, 9 }); // 5 adjacent faces facesOne.push_back({ 4, 9, 5 }); facesOne.push_back({ 2, 4, 11 }); facesOne.push_back({ 6, 2, 10 }); facesOne.push_back({ 8, 6, 7 }); facesOne.push_back({ 9, 8, 1 }); std::unordered_map<uint64_t, int> midpointCache; for (uint32_t i = 0; i < level; i++) { std::vector<Triangle> facesTwo; for (auto triangle : facesOne) { uint32_t a = GetIcosphereMidpoint(triangle.A, triangle.B, midpointCache, vertices, &vertexIndex); uint32_t b = GetIcosphereMidpoint(triangle.B, triangle.C, midpointCache, vertices, &vertexIndex); uint32_t c = GetIcosphereMidpoint(triangle.C, triangle.A, midpointCache, vertices, &vertexIndex); facesTwo.push_back({ triangle.A, a, c }); facesTwo.push_back({ triangle.B, b, a }); facesTwo.push_back({ triangle.C, c, b }); facesTwo.push_back({ a, b, c }); } facesOne = facesTwo; } std::vector<uint32_t> indices; for (auto triangle : facesOne) { indices.push_back(triangle.A); indices.push_back(triangle.B); indices.push_back(triangle.C); } return CreateRef<Mesh>(vertices, indices); } std::string MeshFactory::PrimitiveTypeToString(PrimitiveType type) { switch (type) { case PrimitiveType::Cube: return "Cube"; case PrimitiveType::Sphere: return "Sphere"; case PrimitiveType::Quad: return "Quad"; case PrimitiveType::Plane: return "Plane"; case PrimitiveType::FullScreenQuad: return "Full Screen Quad"; case PrimitiveType::TessellatedQuad: return "Tessellated Quad"; } return ""; } static glm::vec3 RemapVector3(const glm::vec3& inVector) { float x = Remap(inVector.x, -0.5f, 0.5f, 0.0f, 1.0f); float y = Remap(inVector.y, -0.5f, 0.5f, 0.0f, 1.0f); float z = Remap(inVector.z, -0.5f, 0.5f, 0.0f, 1.0f); return { x, y, z }; } Ref<Mesh> MeshFactory::TessellatedQuad(uint32_t resolution) { std::vector<Vertex> vertices; std::vector<uint32_t> indices; // Space between each vertex. This is for a unit quad (-0.5f, -0.5f) - (0.5f, 0.5). float spacing = 1.0f / (float)resolution; glm::vec3 bottomLeft{ -0.5f, -0.5f, 0.0f }; for (uint32_t y = 0; y < resolution; y++) { for (uint32_t x = 0; x < resolution; x++) { glm::vec3 position{ bottomLeft.x + (float)x * spacing, bottomLeft.y + (float)y * spacing, 0.0f }; glm::vec2 texCoord{ (float)x / resolution, (float)y / resolution }; glm::vec3 normal{ 0.0f, 0.0f, 1.0f }; vertices.push_back({ position, texCoord, normal }); if (x == resolution - 1 || y == resolution - 1) continue; uint32_t a = y * resolution + x; uint32_t b = y * resolution + x + resolution; uint32_t c = y * resolution + x + resolution + 1; indices.push_back(a); indices.push_back(b); indices.push_back(c); uint32_t d = a; uint32_t e = y * resolution + x + resolution + 1; uint32_t f = a + 1; indices.push_back(d); indices.push_back(e); indices.push_back(f); } } return CreateRef<Mesh>(vertices, indices); } }
30.753555
151
0.588766
[ "mesh", "vector" ]
39225b5df5bc054f3445754172c730620a682076
266
cpp
C++
cpp/cpp_primer/chapter10/ex_10_34.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
2
2019-12-21T00:53:47.000Z
2020-01-01T10:36:30.000Z
cpp/cpp_primer/chapter10/ex_10_34.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
cpp/cpp_primer/chapter10/ex_10_34.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
// // Created by kaiser on 18-12-17. // #include <cstdint> #include <iostream> #include <vector> int main() { std::vector<std::int32_t> vi{1, 2, 3}; for (auto begin{std::crbegin(vi)}; begin != std::crend(vi); ++begin) { std::cout << *begin << '\n'; } }
16.625
72
0.575188
[ "vector" ]
392546ddffe6c44a24aacc98f75798d3a96fdf5f
1,484
cpp
C++
tests/test_dbuf.cpp
Conservify/phylum
c091e84cf6b5ae1760c086f73731c7180afb58f0
[ "BSD-3-Clause" ]
10
2019-11-26T11:35:56.000Z
2021-07-03T07:21:38.000Z
tests/test_dbuf.cpp
conservify/phylum
9e81f86d1ee1c4a1625182ca96296fa216063831
[ "BSD-3-Clause" ]
1
2019-07-03T06:27:21.000Z
2019-09-06T09:21:27.000Z
tests/test_dbuf.cpp
conservify/phylum
9e81f86d1ee1c4a1625182ca96296fa216063831
[ "BSD-3-Clause" ]
1
2019-09-23T18:13:51.000Z
2019-09-23T18:13:51.000Z
#include <data_chain.h> #include "phylum_tests.h" #include "geometry.h" using namespace phylum; template <typename T> class DelimitedBufferFixture : public PhylumFixture {}; typedef ::testing::Types<layout_256, layout_4096, layout_4096> Implementations; TYPED_TEST_SUITE(DelimitedBufferFixture, Implementations); TYPED_TEST(DelimitedBufferFixture, SeekEnd_SkipsTerminator) { using layout_type = TypeParam; layout_type layout; standard_library_malloc buffer_memory; working_buffers buffers{ &buffer_memory, layout.sector_size, 32 }; delimited_buffer db{ buffers.allocate(layout.sector_size) }; db.emplace<data_chain_header_t>(); db.terminate(); auto position_before = db.position(); db.rewind(); db.seek_end(); auto position_after = db.position(); ASSERT_EQ(position_before, position_after); } struct test_data { uint32_t value{ 0x123456 }; }; TYPED_TEST(DelimitedBufferFixture, SeekEnd_IgnoresAfterTerminator) { using layout_type = TypeParam; layout_type layout; standard_library_malloc buffer_memory; working_buffers buffers{ &buffer_memory, layout.sector_size, 32 }; delimited_buffer db{ buffers.allocate(layout.sector_size) }; db.emplace<data_chain_header_t>(); db.terminate(); auto position_before = db.position(); db.emplace<test_data>(); db.rewind(); db.seek_end(); auto position_after = db.position(); ASSERT_EQ(position_before, position_after); }
22.830769
79
0.737871
[ "geometry" ]
3927f2b7a378f0b097525d897aae1685afa81ece
138,118
cpp
C++
Temp/StagingArea/Il2Cpp/il2cppOutput/UnityEngine.ParticleSystemModule.cpp
UtkayF/Ekonomiyi-Kurtar
4567ece8dcff8cf323fb97950ddc79eb75b4f96e
[ "Apache-2.0" ]
null
null
null
Temp/StagingArea/Il2Cpp/il2cppOutput/UnityEngine.ParticleSystemModule.cpp
UtkayF/Ekonomiyi-Kurtar
4567ece8dcff8cf323fb97950ddc79eb75b4f96e
[ "Apache-2.0" ]
null
null
null
Temp/StagingArea/Il2Cpp/il2cppOutput/UnityEngine.ParticleSystemModule.cpp
UtkayF/Ekonomiyi-Kurtar
4567ece8dcff8cf323fb97950ddc79eb75b4f96e
[ "Apache-2.0" ]
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 "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.Char[] struct CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2; // System.Collections.Generic.List`1<UnityEngine.ParticleCollisionEvent> struct List_1_t2762C811E470D336E31761384C6E5382164DA4C7; // System.String struct String_t; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017; // UnityEngine.AnimationCurve struct AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C; // UnityEngine.Component struct Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621; // UnityEngine.GameObject struct GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F; // UnityEngine.Mesh struct Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C; // UnityEngine.Mesh[] struct MeshU5BU5D_tDD9C723AA6F0225B35A93D871CDC2CEFF7F8CB89; // UnityEngine.ParticleCollisionEvent[] struct ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9; // UnityEngine.ParticleSystem struct ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D; // UnityEngine.ParticleSystemRenderer struct ParticleSystemRenderer_t86E4ED2C0ADF5D2E7FA3D636B6B070600D05C459; IL2CPP_EXTERN_C RuntimeClass* Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C const uint32_t ParticleSystem_Emit_m8C3FCE4F94165CDF0B86326DDB5DB886C1D7B0CF_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t Particle_set_angularVelocity3D_m0F282D7EE110DF290E04B2B99FEC697ED89BF4EF_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t Particle_set_rotation3D_m46DB39BFDEEF27C6119F5EEE2C0B1CA9093FC834_MetadataUsageId; struct MeshU5BU5D_tDD9C723AA6F0225B35A93D871CDC2CEFF7F8CB89; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_tAA355D8AE5C7E9492E77ED0BEF24E3CD28D275D9 { public: public: }; // System.Object struct Il2CppArrayBounds; // System.Array // System.Collections.Generic.List`1<UnityEngine.ParticleCollisionEvent> struct List_1_t2762C811E470D336E31761384C6E5382164DA4C7 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7, ____items_1)); } inline ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* get__items_1() const { return ____items_1; } inline ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7, ____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((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t2762C811E470D336E31761384C6E5382164DA4C7_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7_StaticFields, ____emptyArray_5)); } inline ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* get__emptyArray_5() const { return ____emptyArray_5; } inline ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com { }; // UnityEngine.ParticlePhysicsExtensions struct ParticlePhysicsExtensions_t06495FE0C5097A4BD1A67E3FAA126D77BE13CFCC : public RuntimeObject { public: public: }; // UnityEngine.ParticleSystemExtensionsImpl struct ParticleSystemExtensionsImpl_t510E79A12AE8C1513008528A41BA850BD8A7994C : public RuntimeObject { public: public: }; // System.Boolean struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C { public: // System.Boolean System.Boolean::m_value bool ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C, ___m_value_0)); } inline bool get_m_value_0() const { return ___m_value_0; } inline bool* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(bool value) { ___m_value_0 = value; } }; struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields { public: // System.String System.Boolean::TrueString String_t* ___TrueString_5; // System.String System.Boolean::FalseString String_t* ___FalseString_6; public: inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___TrueString_5)); } inline String_t* get_TrueString_5() const { return ___TrueString_5; } inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; } inline void set_TrueString_5(String_t* value) { ___TrueString_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value); } inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___FalseString_6)); } inline String_t* get_FalseString_6() const { return ___FalseString_6; } inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; } inline void set_FalseString_6(String_t* value) { ___FalseString_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value); } }; // System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521 : public ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF { public: public: }; struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value); } }; // Native definition for P/Invoke marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_com { }; // System.Int32 struct Int32_t585191389E07734F19F3156FF88FB3EF4800D102 { 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_t585191389E07734F19F3156FF88FB3EF4800D102, ___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; } }; // 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; } }; // System.Single struct Single_tDDDA9169C4E4E308AC6D7A824F9B28DC82204AE1 { public: // System.Single System.Single::m_value float ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Single_tDDDA9169C4E4E308AC6D7A824F9B28DC82204AE1, ___m_value_0)); } inline float get_m_value_0() const { return ___m_value_0; } inline float* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(float value) { ___m_value_0 = value; } }; // System.UInt32 struct UInt32_t4980FA09003AFAAB5A6E361BA2748EA9A005709B { public: // System.UInt32 System.UInt32::m_value uint32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt32_t4980FA09003AFAAB5A6E361BA2748EA9A005709B, ___m_value_0)); } inline uint32_t get_m_value_0() const { return ___m_value_0; } inline uint32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(uint32_t value) { ___m_value_0 = value; } }; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017 { public: union { struct { }; uint8_t Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017__padding[1]; }; public: }; // UnityEngine.Color32 struct Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 { public: union { #pragma pack(push, tp, 1) struct { // System.Int32 UnityEngine.Color32::rgba int32_t ___rgba_0; }; #pragma pack(pop, tp) struct { int32_t ___rgba_0_forAlignmentOnly; }; #pragma pack(push, tp, 1) struct { // System.Byte UnityEngine.Color32::r uint8_t ___r_1; }; #pragma pack(pop, tp) struct { uint8_t ___r_1_forAlignmentOnly; }; #pragma pack(push, tp, 1) struct { char ___g_2_OffsetPadding[1]; // System.Byte UnityEngine.Color32::g uint8_t ___g_2; }; #pragma pack(pop, tp) struct { char ___g_2_OffsetPadding_forAlignmentOnly[1]; uint8_t ___g_2_forAlignmentOnly; }; #pragma pack(push, tp, 1) struct { char ___b_3_OffsetPadding[2]; // System.Byte UnityEngine.Color32::b uint8_t ___b_3; }; #pragma pack(pop, tp) struct { char ___b_3_OffsetPadding_forAlignmentOnly[2]; uint8_t ___b_3_forAlignmentOnly; }; #pragma pack(push, tp, 1) struct { char ___a_4_OffsetPadding[3]; // System.Byte UnityEngine.Color32::a uint8_t ___a_4; }; #pragma pack(pop, tp) struct { char ___a_4_OffsetPadding_forAlignmentOnly[3]; uint8_t ___a_4_forAlignmentOnly; }; }; public: inline static int32_t get_offset_of_rgba_0() { return static_cast<int32_t>(offsetof(Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23, ___rgba_0)); } inline int32_t get_rgba_0() const { return ___rgba_0; } inline int32_t* get_address_of_rgba_0() { return &___rgba_0; } inline void set_rgba_0(int32_t value) { ___rgba_0 = value; } inline static int32_t get_offset_of_r_1() { return static_cast<int32_t>(offsetof(Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23, ___r_1)); } inline uint8_t get_r_1() const { return ___r_1; } inline uint8_t* get_address_of_r_1() { return &___r_1; } inline void set_r_1(uint8_t value) { ___r_1 = value; } inline static int32_t get_offset_of_g_2() { return static_cast<int32_t>(offsetof(Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23, ___g_2)); } inline uint8_t get_g_2() const { return ___g_2; } inline uint8_t* get_address_of_g_2() { return &___g_2; } inline void set_g_2(uint8_t value) { ___g_2 = value; } inline static int32_t get_offset_of_b_3() { return static_cast<int32_t>(offsetof(Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23, ___b_3)); } inline uint8_t get_b_3() const { return ___b_3; } inline uint8_t* get_address_of_b_3() { return &___b_3; } inline void set_b_3(uint8_t value) { ___b_3 = value; } inline static int32_t get_offset_of_a_4() { return static_cast<int32_t>(offsetof(Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23, ___a_4)); } inline uint8_t get_a_4() const { return ___a_4; } inline uint8_t* get_address_of_a_4() { return &___a_4; } inline void set_a_4(uint8_t value) { ___a_4 = value; } }; // UnityEngine.ParticleSystem/EmissionModule struct EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 { public: // UnityEngine.ParticleSystem UnityEngine.ParticleSystem/EmissionModule::m_ParticleSystem ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; public: inline static int32_t get_offset_of_m_ParticleSystem_0() { return static_cast<int32_t>(offsetof(EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1, ___m_ParticleSystem_0)); } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * get_m_ParticleSystem_0() const { return ___m_ParticleSystem_0; } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D ** get_address_of_m_ParticleSystem_0() { return &___m_ParticleSystem_0; } inline void set_m_ParticleSystem_0(ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * value) { ___m_ParticleSystem_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_ParticleSystem_0), (void*)value); } }; // Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/EmissionModule struct EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_pinvoke { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; }; // Native definition for COM marshalling of UnityEngine.ParticleSystem/EmissionModule struct EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_com { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; }; // UnityEngine.ParticleSystem/MainModule struct MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 { public: // UnityEngine.ParticleSystem UnityEngine.ParticleSystem/MainModule::m_ParticleSystem ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; public: inline static int32_t get_offset_of_m_ParticleSystem_0() { return static_cast<int32_t>(offsetof(MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7, ___m_ParticleSystem_0)); } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * get_m_ParticleSystem_0() const { return ___m_ParticleSystem_0; } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D ** get_address_of_m_ParticleSystem_0() { return &___m_ParticleSystem_0; } inline void set_m_ParticleSystem_0(ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * value) { ___m_ParticleSystem_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_ParticleSystem_0), (void*)value); } }; // Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/MainModule struct MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_pinvoke { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; }; // Native definition for COM marshalling of UnityEngine.ParticleSystem/MainModule struct MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_com { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; }; // UnityEngine.Vector3 struct Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 { public: // System.Single UnityEngine.Vector3::x float ___x_2; // System.Single UnityEngine.Vector3::y float ___y_3; // System.Single UnityEngine.Vector3::z float ___z_4; public: inline static int32_t get_offset_of_x_2() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___x_2)); } inline float get_x_2() const { return ___x_2; } inline float* get_address_of_x_2() { return &___x_2; } inline void set_x_2(float value) { ___x_2 = value; } inline static int32_t get_offset_of_y_3() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___y_3)); } inline float get_y_3() const { return ___y_3; } inline float* get_address_of_y_3() { return &___y_3; } inline void set_y_3(float value) { ___y_3 = value; } inline static int32_t get_offset_of_z_4() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___z_4)); } inline float get_z_4() const { return ___z_4; } inline float* get_address_of_z_4() { return &___z_4; } inline void set_z_4(float value) { ___z_4 = value; } }; struct Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields { public: // UnityEngine.Vector3 UnityEngine.Vector3::zeroVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___zeroVector_5; // UnityEngine.Vector3 UnityEngine.Vector3::oneVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___oneVector_6; // UnityEngine.Vector3 UnityEngine.Vector3::upVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___upVector_7; // UnityEngine.Vector3 UnityEngine.Vector3::downVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___downVector_8; // UnityEngine.Vector3 UnityEngine.Vector3::leftVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___leftVector_9; // UnityEngine.Vector3 UnityEngine.Vector3::rightVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___rightVector_10; // UnityEngine.Vector3 UnityEngine.Vector3::forwardVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___forwardVector_11; // UnityEngine.Vector3 UnityEngine.Vector3::backVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___backVector_12; // UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___positiveInfinityVector_13; // UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___negativeInfinityVector_14; public: inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___zeroVector_5)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_zeroVector_5() const { return ___zeroVector_5; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_zeroVector_5() { return &___zeroVector_5; } inline void set_zeroVector_5(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___zeroVector_5 = value; } inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___oneVector_6)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_oneVector_6() const { return ___oneVector_6; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_oneVector_6() { return &___oneVector_6; } inline void set_oneVector_6(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___oneVector_6 = value; } inline static int32_t get_offset_of_upVector_7() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___upVector_7)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_upVector_7() const { return ___upVector_7; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_upVector_7() { return &___upVector_7; } inline void set_upVector_7(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___upVector_7 = value; } inline static int32_t get_offset_of_downVector_8() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___downVector_8)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_downVector_8() const { return ___downVector_8; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_downVector_8() { return &___downVector_8; } inline void set_downVector_8(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___downVector_8 = value; } inline static int32_t get_offset_of_leftVector_9() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___leftVector_9)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_leftVector_9() const { return ___leftVector_9; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_leftVector_9() { return &___leftVector_9; } inline void set_leftVector_9(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___leftVector_9 = value; } inline static int32_t get_offset_of_rightVector_10() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___rightVector_10)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_rightVector_10() const { return ___rightVector_10; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_rightVector_10() { return &___rightVector_10; } inline void set_rightVector_10(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___rightVector_10 = value; } inline static int32_t get_offset_of_forwardVector_11() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___forwardVector_11)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_forwardVector_11() const { return ___forwardVector_11; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_forwardVector_11() { return &___forwardVector_11; } inline void set_forwardVector_11(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___forwardVector_11 = value; } inline static int32_t get_offset_of_backVector_12() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___backVector_12)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_backVector_12() const { return ___backVector_12; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_backVector_12() { return &___backVector_12; } inline void set_backVector_12(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___backVector_12 = value; } inline static int32_t get_offset_of_positiveInfinityVector_13() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___positiveInfinityVector_13)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_positiveInfinityVector_13() const { return ___positiveInfinityVector_13; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_positiveInfinityVector_13() { return &___positiveInfinityVector_13; } inline void set_positiveInfinityVector_13(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___positiveInfinityVector_13 = value; } inline static int32_t get_offset_of_negativeInfinityVector_14() { return static_cast<int32_t>(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___negativeInfinityVector_14)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_negativeInfinityVector_14() const { return ___negativeInfinityVector_14; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_negativeInfinityVector_14() { return &___negativeInfinityVector_14; } inline void set_negativeInfinityVector_14(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___negativeInfinityVector_14 = value; } }; // UnityEngine.AnimationCurve struct AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C : public RuntimeObject { public: // System.IntPtr UnityEngine.AnimationCurve::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.AnimationCurve struct AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.AnimationCurve struct AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C_marshaled_com { intptr_t ___m_Ptr_0; }; // UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_marshaled_com { intptr_t ___m_CachedPtr_0; }; // UnityEngine.ParticleCollisionEvent struct ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 { public: // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::m_Intersection Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Intersection_0; // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::m_Normal Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Normal_1; // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::m_Velocity Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Velocity_2; // System.Int32 UnityEngine.ParticleCollisionEvent::m_ColliderInstanceID int32_t ___m_ColliderInstanceID_3; public: inline static int32_t get_offset_of_m_Intersection_0() { return static_cast<int32_t>(offsetof(ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47, ___m_Intersection_0)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Intersection_0() const { return ___m_Intersection_0; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Intersection_0() { return &___m_Intersection_0; } inline void set_m_Intersection_0(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Intersection_0 = value; } inline static int32_t get_offset_of_m_Normal_1() { return static_cast<int32_t>(offsetof(ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47, ___m_Normal_1)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Normal_1() const { return ___m_Normal_1; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Normal_1() { return &___m_Normal_1; } inline void set_m_Normal_1(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Normal_1 = value; } inline static int32_t get_offset_of_m_Velocity_2() { return static_cast<int32_t>(offsetof(ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47, ___m_Velocity_2)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Velocity_2() const { return ___m_Velocity_2; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Velocity_2() { return &___m_Velocity_2; } inline void set_m_Velocity_2(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Velocity_2 = value; } inline static int32_t get_offset_of_m_ColliderInstanceID_3() { return static_cast<int32_t>(offsetof(ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47, ___m_ColliderInstanceID_3)); } inline int32_t get_m_ColliderInstanceID_3() const { return ___m_ColliderInstanceID_3; } inline int32_t* get_address_of_m_ColliderInstanceID_3() { return &___m_ColliderInstanceID_3; } inline void set_m_ColliderInstanceID_3(int32_t value) { ___m_ColliderInstanceID_3 = value; } }; // UnityEngine.ParticleSystem/Particle struct Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E { public: // UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_Position Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Position_0; // UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_Velocity Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Velocity_1; // UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_AnimatedVelocity Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_AnimatedVelocity_2; // UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_InitialVelocity Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_InitialVelocity_3; // UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_AxisOfRotation Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_AxisOfRotation_4; // UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_Rotation Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Rotation_5; // UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_AngularVelocity Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_AngularVelocity_6; // UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_StartSize Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_StartSize_7; // UnityEngine.Color32 UnityEngine.ParticleSystem/Particle::m_StartColor Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 ___m_StartColor_8; // System.UInt32 UnityEngine.ParticleSystem/Particle::m_RandomSeed uint32_t ___m_RandomSeed_9; // System.UInt32 UnityEngine.ParticleSystem/Particle::m_ParentRandomSeed uint32_t ___m_ParentRandomSeed_10; // System.Single UnityEngine.ParticleSystem/Particle::m_Lifetime float ___m_Lifetime_11; // System.Single UnityEngine.ParticleSystem/Particle::m_StartLifetime float ___m_StartLifetime_12; // System.Int32 UnityEngine.ParticleSystem/Particle::m_MeshIndex int32_t ___m_MeshIndex_13; // System.Single UnityEngine.ParticleSystem/Particle::m_EmitAccumulator0 float ___m_EmitAccumulator0_14; // System.Single UnityEngine.ParticleSystem/Particle::m_EmitAccumulator1 float ___m_EmitAccumulator1_15; // System.UInt32 UnityEngine.ParticleSystem/Particle::m_Flags uint32_t ___m_Flags_16; public: inline static int32_t get_offset_of_m_Position_0() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_Position_0)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Position_0() const { return ___m_Position_0; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Position_0() { return &___m_Position_0; } inline void set_m_Position_0(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Position_0 = value; } inline static int32_t get_offset_of_m_Velocity_1() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_Velocity_1)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Velocity_1() const { return ___m_Velocity_1; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Velocity_1() { return &___m_Velocity_1; } inline void set_m_Velocity_1(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Velocity_1 = value; } inline static int32_t get_offset_of_m_AnimatedVelocity_2() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_AnimatedVelocity_2)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_AnimatedVelocity_2() const { return ___m_AnimatedVelocity_2; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_AnimatedVelocity_2() { return &___m_AnimatedVelocity_2; } inline void set_m_AnimatedVelocity_2(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_AnimatedVelocity_2 = value; } inline static int32_t get_offset_of_m_InitialVelocity_3() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_InitialVelocity_3)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_InitialVelocity_3() const { return ___m_InitialVelocity_3; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_InitialVelocity_3() { return &___m_InitialVelocity_3; } inline void set_m_InitialVelocity_3(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_InitialVelocity_3 = value; } inline static int32_t get_offset_of_m_AxisOfRotation_4() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_AxisOfRotation_4)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_AxisOfRotation_4() const { return ___m_AxisOfRotation_4; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_AxisOfRotation_4() { return &___m_AxisOfRotation_4; } inline void set_m_AxisOfRotation_4(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_AxisOfRotation_4 = value; } inline static int32_t get_offset_of_m_Rotation_5() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_Rotation_5)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Rotation_5() const { return ___m_Rotation_5; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Rotation_5() { return &___m_Rotation_5; } inline void set_m_Rotation_5(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Rotation_5 = value; } inline static int32_t get_offset_of_m_AngularVelocity_6() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_AngularVelocity_6)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_AngularVelocity_6() const { return ___m_AngularVelocity_6; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_AngularVelocity_6() { return &___m_AngularVelocity_6; } inline void set_m_AngularVelocity_6(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_AngularVelocity_6 = value; } inline static int32_t get_offset_of_m_StartSize_7() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_StartSize_7)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_StartSize_7() const { return ___m_StartSize_7; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_StartSize_7() { return &___m_StartSize_7; } inline void set_m_StartSize_7(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_StartSize_7 = value; } inline static int32_t get_offset_of_m_StartColor_8() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_StartColor_8)); } inline Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 get_m_StartColor_8() const { return ___m_StartColor_8; } inline Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 * get_address_of_m_StartColor_8() { return &___m_StartColor_8; } inline void set_m_StartColor_8(Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 value) { ___m_StartColor_8 = value; } inline static int32_t get_offset_of_m_RandomSeed_9() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_RandomSeed_9)); } inline uint32_t get_m_RandomSeed_9() const { return ___m_RandomSeed_9; } inline uint32_t* get_address_of_m_RandomSeed_9() { return &___m_RandomSeed_9; } inline void set_m_RandomSeed_9(uint32_t value) { ___m_RandomSeed_9 = value; } inline static int32_t get_offset_of_m_ParentRandomSeed_10() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_ParentRandomSeed_10)); } inline uint32_t get_m_ParentRandomSeed_10() const { return ___m_ParentRandomSeed_10; } inline uint32_t* get_address_of_m_ParentRandomSeed_10() { return &___m_ParentRandomSeed_10; } inline void set_m_ParentRandomSeed_10(uint32_t value) { ___m_ParentRandomSeed_10 = value; } inline static int32_t get_offset_of_m_Lifetime_11() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_Lifetime_11)); } inline float get_m_Lifetime_11() const { return ___m_Lifetime_11; } inline float* get_address_of_m_Lifetime_11() { return &___m_Lifetime_11; } inline void set_m_Lifetime_11(float value) { ___m_Lifetime_11 = value; } inline static int32_t get_offset_of_m_StartLifetime_12() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_StartLifetime_12)); } inline float get_m_StartLifetime_12() const { return ___m_StartLifetime_12; } inline float* get_address_of_m_StartLifetime_12() { return &___m_StartLifetime_12; } inline void set_m_StartLifetime_12(float value) { ___m_StartLifetime_12 = value; } inline static int32_t get_offset_of_m_MeshIndex_13() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_MeshIndex_13)); } inline int32_t get_m_MeshIndex_13() const { return ___m_MeshIndex_13; } inline int32_t* get_address_of_m_MeshIndex_13() { return &___m_MeshIndex_13; } inline void set_m_MeshIndex_13(int32_t value) { ___m_MeshIndex_13 = value; } inline static int32_t get_offset_of_m_EmitAccumulator0_14() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_EmitAccumulator0_14)); } inline float get_m_EmitAccumulator0_14() const { return ___m_EmitAccumulator0_14; } inline float* get_address_of_m_EmitAccumulator0_14() { return &___m_EmitAccumulator0_14; } inline void set_m_EmitAccumulator0_14(float value) { ___m_EmitAccumulator0_14 = value; } inline static int32_t get_offset_of_m_EmitAccumulator1_15() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_EmitAccumulator1_15)); } inline float get_m_EmitAccumulator1_15() const { return ___m_EmitAccumulator1_15; } inline float* get_address_of_m_EmitAccumulator1_15() { return &___m_EmitAccumulator1_15; } inline void set_m_EmitAccumulator1_15(float value) { ___m_EmitAccumulator1_15 = value; } inline static int32_t get_offset_of_m_Flags_16() { return static_cast<int32_t>(offsetof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E, ___m_Flags_16)); } inline uint32_t get_m_Flags_16() const { return ___m_Flags_16; } inline uint32_t* get_address_of_m_Flags_16() { return &___m_Flags_16; } inline void set_m_Flags_16(uint32_t value) { ___m_Flags_16 = value; } }; // UnityEngine.ParticleSystemCurveMode struct ParticleSystemCurveMode_tD8A2390BB482B39C0C0714F3DDE715386BC7D48D { public: // System.Int32 UnityEngine.ParticleSystemCurveMode::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ParticleSystemCurveMode_tD8A2390BB482B39C0C0714F3DDE715386BC7D48D, ___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; } }; // UnityEngine.Component struct Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 : public Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 { public: public: }; // UnityEngine.GameObject struct GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F : public Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 { public: public: }; // UnityEngine.Mesh struct Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C : public Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 { public: public: }; // UnityEngine.ParticleSystem/EmitParams struct EmitParams_t03557E552852EC6B71876CD05C4098733702A219 { public: // UnityEngine.ParticleSystem/Particle UnityEngine.ParticleSystem/EmitParams::m_Particle Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E ___m_Particle_0; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_PositionSet bool ___m_PositionSet_1; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_VelocitySet bool ___m_VelocitySet_2; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_AxisOfRotationSet bool ___m_AxisOfRotationSet_3; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_RotationSet bool ___m_RotationSet_4; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_AngularVelocitySet bool ___m_AngularVelocitySet_5; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_StartSizeSet bool ___m_StartSizeSet_6; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_StartColorSet bool ___m_StartColorSet_7; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_RandomSeedSet bool ___m_RandomSeedSet_8; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_StartLifetimeSet bool ___m_StartLifetimeSet_9; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_MeshIndexSet bool ___m_MeshIndexSet_10; // System.Boolean UnityEngine.ParticleSystem/EmitParams::m_ApplyShapeToPosition bool ___m_ApplyShapeToPosition_11; public: inline static int32_t get_offset_of_m_Particle_0() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_Particle_0)); } inline Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E get_m_Particle_0() const { return ___m_Particle_0; } inline Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * get_address_of_m_Particle_0() { return &___m_Particle_0; } inline void set_m_Particle_0(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E value) { ___m_Particle_0 = value; } inline static int32_t get_offset_of_m_PositionSet_1() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_PositionSet_1)); } inline bool get_m_PositionSet_1() const { return ___m_PositionSet_1; } inline bool* get_address_of_m_PositionSet_1() { return &___m_PositionSet_1; } inline void set_m_PositionSet_1(bool value) { ___m_PositionSet_1 = value; } inline static int32_t get_offset_of_m_VelocitySet_2() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_VelocitySet_2)); } inline bool get_m_VelocitySet_2() const { return ___m_VelocitySet_2; } inline bool* get_address_of_m_VelocitySet_2() { return &___m_VelocitySet_2; } inline void set_m_VelocitySet_2(bool value) { ___m_VelocitySet_2 = value; } inline static int32_t get_offset_of_m_AxisOfRotationSet_3() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_AxisOfRotationSet_3)); } inline bool get_m_AxisOfRotationSet_3() const { return ___m_AxisOfRotationSet_3; } inline bool* get_address_of_m_AxisOfRotationSet_3() { return &___m_AxisOfRotationSet_3; } inline void set_m_AxisOfRotationSet_3(bool value) { ___m_AxisOfRotationSet_3 = value; } inline static int32_t get_offset_of_m_RotationSet_4() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_RotationSet_4)); } inline bool get_m_RotationSet_4() const { return ___m_RotationSet_4; } inline bool* get_address_of_m_RotationSet_4() { return &___m_RotationSet_4; } inline void set_m_RotationSet_4(bool value) { ___m_RotationSet_4 = value; } inline static int32_t get_offset_of_m_AngularVelocitySet_5() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_AngularVelocitySet_5)); } inline bool get_m_AngularVelocitySet_5() const { return ___m_AngularVelocitySet_5; } inline bool* get_address_of_m_AngularVelocitySet_5() { return &___m_AngularVelocitySet_5; } inline void set_m_AngularVelocitySet_5(bool value) { ___m_AngularVelocitySet_5 = value; } inline static int32_t get_offset_of_m_StartSizeSet_6() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_StartSizeSet_6)); } inline bool get_m_StartSizeSet_6() const { return ___m_StartSizeSet_6; } inline bool* get_address_of_m_StartSizeSet_6() { return &___m_StartSizeSet_6; } inline void set_m_StartSizeSet_6(bool value) { ___m_StartSizeSet_6 = value; } inline static int32_t get_offset_of_m_StartColorSet_7() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_StartColorSet_7)); } inline bool get_m_StartColorSet_7() const { return ___m_StartColorSet_7; } inline bool* get_address_of_m_StartColorSet_7() { return &___m_StartColorSet_7; } inline void set_m_StartColorSet_7(bool value) { ___m_StartColorSet_7 = value; } inline static int32_t get_offset_of_m_RandomSeedSet_8() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_RandomSeedSet_8)); } inline bool get_m_RandomSeedSet_8() const { return ___m_RandomSeedSet_8; } inline bool* get_address_of_m_RandomSeedSet_8() { return &___m_RandomSeedSet_8; } inline void set_m_RandomSeedSet_8(bool value) { ___m_RandomSeedSet_8 = value; } inline static int32_t get_offset_of_m_StartLifetimeSet_9() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_StartLifetimeSet_9)); } inline bool get_m_StartLifetimeSet_9() const { return ___m_StartLifetimeSet_9; } inline bool* get_address_of_m_StartLifetimeSet_9() { return &___m_StartLifetimeSet_9; } inline void set_m_StartLifetimeSet_9(bool value) { ___m_StartLifetimeSet_9 = value; } inline static int32_t get_offset_of_m_MeshIndexSet_10() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_MeshIndexSet_10)); } inline bool get_m_MeshIndexSet_10() const { return ___m_MeshIndexSet_10; } inline bool* get_address_of_m_MeshIndexSet_10() { return &___m_MeshIndexSet_10; } inline void set_m_MeshIndexSet_10(bool value) { ___m_MeshIndexSet_10 = value; } inline static int32_t get_offset_of_m_ApplyShapeToPosition_11() { return static_cast<int32_t>(offsetof(EmitParams_t03557E552852EC6B71876CD05C4098733702A219, ___m_ApplyShapeToPosition_11)); } inline bool get_m_ApplyShapeToPosition_11() const { return ___m_ApplyShapeToPosition_11; } inline bool* get_address_of_m_ApplyShapeToPosition_11() { return &___m_ApplyShapeToPosition_11; } inline void set_m_ApplyShapeToPosition_11(bool value) { ___m_ApplyShapeToPosition_11 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/EmitParams struct EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshaled_pinvoke { Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E ___m_Particle_0; int32_t ___m_PositionSet_1; int32_t ___m_VelocitySet_2; int32_t ___m_AxisOfRotationSet_3; int32_t ___m_RotationSet_4; int32_t ___m_AngularVelocitySet_5; int32_t ___m_StartSizeSet_6; int32_t ___m_StartColorSet_7; int32_t ___m_RandomSeedSet_8; int32_t ___m_StartLifetimeSet_9; int32_t ___m_MeshIndexSet_10; int32_t ___m_ApplyShapeToPosition_11; }; // Native definition for COM marshalling of UnityEngine.ParticleSystem/EmitParams struct EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshaled_com { Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E ___m_Particle_0; int32_t ___m_PositionSet_1; int32_t ___m_VelocitySet_2; int32_t ___m_AxisOfRotationSet_3; int32_t ___m_RotationSet_4; int32_t ___m_AngularVelocitySet_5; int32_t ___m_StartSizeSet_6; int32_t ___m_StartColorSet_7; int32_t ___m_RandomSeedSet_8; int32_t ___m_StartLifetimeSet_9; int32_t ___m_MeshIndexSet_10; int32_t ___m_ApplyShapeToPosition_11; }; // UnityEngine.ParticleSystem/MinMaxCurve struct MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 { public: // UnityEngine.ParticleSystemCurveMode UnityEngine.ParticleSystem/MinMaxCurve::m_Mode int32_t ___m_Mode_0; // System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMultiplier float ___m_CurveMultiplier_1; // UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMin AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * ___m_CurveMin_2; // UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMax AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * ___m_CurveMax_3; // System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_ConstantMin float ___m_ConstantMin_4; // System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_ConstantMax float ___m_ConstantMax_5; public: inline static int32_t get_offset_of_m_Mode_0() { return static_cast<int32_t>(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_Mode_0)); } inline int32_t get_m_Mode_0() const { return ___m_Mode_0; } inline int32_t* get_address_of_m_Mode_0() { return &___m_Mode_0; } inline void set_m_Mode_0(int32_t value) { ___m_Mode_0 = value; } inline static int32_t get_offset_of_m_CurveMultiplier_1() { return static_cast<int32_t>(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_CurveMultiplier_1)); } inline float get_m_CurveMultiplier_1() const { return ___m_CurveMultiplier_1; } inline float* get_address_of_m_CurveMultiplier_1() { return &___m_CurveMultiplier_1; } inline void set_m_CurveMultiplier_1(float value) { ___m_CurveMultiplier_1 = value; } inline static int32_t get_offset_of_m_CurveMin_2() { return static_cast<int32_t>(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_CurveMin_2)); } inline AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * get_m_CurveMin_2() const { return ___m_CurveMin_2; } inline AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C ** get_address_of_m_CurveMin_2() { return &___m_CurveMin_2; } inline void set_m_CurveMin_2(AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * value) { ___m_CurveMin_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_CurveMin_2), (void*)value); } inline static int32_t get_offset_of_m_CurveMax_3() { return static_cast<int32_t>(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_CurveMax_3)); } inline AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * get_m_CurveMax_3() const { return ___m_CurveMax_3; } inline AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C ** get_address_of_m_CurveMax_3() { return &___m_CurveMax_3; } inline void set_m_CurveMax_3(AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * value) { ___m_CurveMax_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_CurveMax_3), (void*)value); } inline static int32_t get_offset_of_m_ConstantMin_4() { return static_cast<int32_t>(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_ConstantMin_4)); } inline float get_m_ConstantMin_4() const { return ___m_ConstantMin_4; } inline float* get_address_of_m_ConstantMin_4() { return &___m_ConstantMin_4; } inline void set_m_ConstantMin_4(float value) { ___m_ConstantMin_4 = value; } inline static int32_t get_offset_of_m_ConstantMax_5() { return static_cast<int32_t>(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_ConstantMax_5)); } inline float get_m_ConstantMax_5() const { return ___m_ConstantMax_5; } inline float* get_address_of_m_ConstantMax_5() { return &___m_ConstantMax_5; } inline void set_m_ConstantMax_5(float value) { ___m_ConstantMax_5 = value; } }; // UnityEngine.ParticleSystem struct ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.Renderer struct Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.ParticleSystemRenderer struct ParticleSystemRenderer_t86E4ED2C0ADF5D2E7FA3D636B6B070600D05C459 : public Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // UnityEngine.Mesh[] struct MeshU5BU5D_tDD9C723AA6F0225B35A93D871CDC2CEFF7F8CB89 : public RuntimeArray { public: ALIGN_FIELD (8) Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C * m_Items[1]; public: inline Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } inline Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Mesh_t6106B8D8E4C691321581AB0445552EC78B947B8C * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } }; // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::get_velocity() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ParticleCollisionEvent_get_velocity_m60BCDF44F8F345C3534705CBA2BD5E69346021A3 (ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * __this, const RuntimeMethod* method); // UnityEngine.Component UnityEngine.ParticleCollisionEvent::InstanceIDToColliderComponent(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * ParticleCollisionEvent_InstanceIDToColliderComponent_m910880B728D5E4C69F257379ADA56A59E29B4F40 (int32_t ___instanceID0, const RuntimeMethod* method); // UnityEngine.Component UnityEngine.ParticleCollisionEvent::get_colliderComponent() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * ParticleCollisionEvent_get_colliderComponent_mE4A94CAC6A2875588395DCB76FB7978A72796B82 (ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * __this, const RuntimeMethod* method); // System.Int32 UnityEngine.ParticleSystemExtensionsImpl::GetCollisionEvents(UnityEngine.ParticleSystem,UnityEngine.GameObject,System.Collections.Generic.List`1<UnityEngine.ParticleCollisionEvent>) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t ParticleSystemExtensionsImpl_GetCollisionEvents_mADDEE9247E3C74C2227B14242968B2531AFCF0DE (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___ps0, GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * ___go1, List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * ___collisionEvents2, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_position(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_position_m3E99F891841E8B03490433FAFF5B601A6D12BDEF (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_velocity(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_velocity_mD0476C793611AD570296960FB0CB8FECD387E99C (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_lifetime(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_lifetime_m0DB60575386F2D365BCCCAB07538FC2BFF81EC17 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, float ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_startLifetime(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_startLifetime_mEEB2B63599B1E4D1B8B2CEE25F13A50F1BCE7BBE (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, float ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_startSize(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_startSize_m45B6CD1480219E30A96317D654B9439C8DB2DF87 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, float ___value0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::get_zero() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_get_zero_m3CDDCAE94581DF3BB16C4B40A100E28E9C6649C2 (const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_rotation3D(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_rotation3D_m46DB39BFDEEF27C6119F5EEE2C0B1CA9093FC834 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_angularVelocity3D(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_angularVelocity3D_m0F282D7EE110DF290E04B2B99FEC697ED89BF4EF (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_startColor(UnityEngine.Color32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_startColor_m67807C44D14862EBD8C030C1FE094E8438384AA6 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_randomSeed(System.UInt32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_randomSeed_m1311237E65918DDD765FC4D6BAE85047D8B8CBCE (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, uint32_t ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem::EmitOld_Internal(UnityEngine.ParticleSystem/Particle&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_EmitOld_Internal_m4313E5BD80E21011786EA12F2D2D9EFE9186320E (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * ___particle0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem::Play(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Play_mBB238026E6389F44C76498D31038FE7A8C47E3AA (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, bool ___withChildren0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem::Clear(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Clear_mA140B248D89675286ADAE837E9B82A65F0507164 (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, bool ___withChildren0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem::Emit_Internal(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Emit_Internal_m1857956B7219B8232C1777E515706F8075C8B925 (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, int32_t ___count0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem::Emit_Injected(UnityEngine.ParticleSystem/EmitParams&,System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Emit_Injected_mB34A23399928EDC3111C060A2346A1EF63E1B9CC (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, EmitParams_t03557E552852EC6B71876CD05C4098733702A219 * ___emitParams0, int32_t ___count1, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::.ctor(UnityEngine.ParticleSystem) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule__ctor_m10DC65291ACEC243EC5302404E059717B552BA7A (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___particleSystem0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/EmissionModule::.ctor(UnityEngine.ParticleSystem) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EmissionModule__ctor_mD6B4029B58ECFECE0567E7FD67962FEF52B15843 (EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * __this, ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___particleSystem0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/EmissionModule::set_enabled_Injected(UnityEngine.ParticleSystem/EmissionModule&,System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EmissionModule_set_enabled_Injected_m80C70B60E49D3ADE643B12579CE8CD119BD7D5F4 (EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * ____unity_self0, bool ___value1, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/EmissionModule::set_enabled(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EmissionModule_set_enabled_m3896B441BDE0F0752A6D113012B20D5D31B16D36 (EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * __this, bool ___value0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startLifetimeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startLifetimeMultiplier_Injected_m595857A88FC82240A13F2A2B9EC4262CB2360EEC (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startLifetimeMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startLifetimeMultiplier_m0D425E7689C0B99C5B9E8F8C4AE205600C1EA529 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startLifetimeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startLifetimeMultiplier_Injected_mDB91EC13ABF1C788DA5565D493F0DF896A45B2B4 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, float ___value1, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startLifetimeMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startLifetimeMultiplier_mCD094E55BD574ECF3A8F5D616A2287130B6EC67B (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeed_Injected(UnityEngine.ParticleSystem/MainModule&,UnityEngine.ParticleSystem/MinMaxCurve&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeed_Injected_m8E60F6BB2068411A562524F8F57FBFB6E3539D77 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 * ___value1, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeed(UnityEngine.ParticleSystem/MinMaxCurve) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeed_m32CD8968F2B5572112DE22CC7B6E2B502222B4AE (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 ___value0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startSpeedMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSpeedMultiplier_Injected_mFEF854F99A621D3A4104CEE8EC9382829D4AB665 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startSpeedMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSpeedMultiplier_m22326AF745786C1748F6B165361CCC26917F214A (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeedMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeedMultiplier_Injected_m51E3D91BEFC4628CBF55A5B4CF97C1A2B7D0F1E9 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, float ___value1, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeedMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeedMultiplier_m14E157EFF4BD78D8FDA701BE2BD0B398EF6F2453 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startSizeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSizeMultiplier_Injected_mB3E13AEB7F30982961453FD2BD8FE1503202F41D (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startSizeMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSizeMultiplier_m8E241099DB1E4ECE4827E9507415C80012AEA312 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSizeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSizeMultiplier_Injected_m08751D61274A36C843B4EE5D4453A18CEB7D1B9F (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, float ___value1, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSizeMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSizeMultiplier_m6375840B2CADFF82321D7B52103FADC5AD144B8C (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MinMaxCurve::.ctor(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MinMaxCurve__ctor_mE5FDFD4ADB7EA897D19133CF82DC290577B4DD29 (MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 * __this, float ___constant0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/Particle::set_remainingLifetime(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_remainingLifetime_mD6ABB0C19127BD86DE3723B443331E5968EE0E87 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, float ___value0, const RuntimeMethod* method); // System.Void UnityEngine.Vector3::.ctor(System.Single,System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Vector3__ctor_m08F61F548AA5836D8789843ACB4A81E4963D2EE1 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * __this, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::op_Multiply(UnityEngine.Vector3,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___a0, float ___d1, const RuntimeMethod* method); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::get_velocity() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ParticleCollisionEvent_get_velocity_m60BCDF44F8F345C3534705CBA2BD5E69346021A3 (ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * __this, const RuntimeMethod* method) { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 V_0; memset((&V_0), 0, sizeof(V_0)); { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = __this->get_m_Velocity_2(); V_0 = L_0; goto IL_000a; } IL_000a: { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_1 = V_0; return L_1; } } IL2CPP_EXTERN_C Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ParticleCollisionEvent_get_velocity_m60BCDF44F8F345C3534705CBA2BD5E69346021A3_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * _thisAdjusted = reinterpret_cast<ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 *>(__this + _offset); return ParticleCollisionEvent_get_velocity_m60BCDF44F8F345C3534705CBA2BD5E69346021A3(_thisAdjusted, method); } // UnityEngine.Component UnityEngine.ParticleCollisionEvent::get_colliderComponent() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * ParticleCollisionEvent_get_colliderComponent_mE4A94CAC6A2875588395DCB76FB7978A72796B82 (ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * __this, const RuntimeMethod* method) { Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * V_0 = NULL; { int32_t L_0 = __this->get_m_ColliderInstanceID_3(); Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * L_1 = ParticleCollisionEvent_InstanceIDToColliderComponent_m910880B728D5E4C69F257379ADA56A59E29B4F40(L_0, /*hidden argument*/NULL); V_0 = L_1; goto IL_000f; } IL_000f: { Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * L_2 = V_0; return L_2; } } IL2CPP_EXTERN_C Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * ParticleCollisionEvent_get_colliderComponent_mE4A94CAC6A2875588395DCB76FB7978A72796B82_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * _thisAdjusted = reinterpret_cast<ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 *>(__this + _offset); return ParticleCollisionEvent_get_colliderComponent_mE4A94CAC6A2875588395DCB76FB7978A72796B82(_thisAdjusted, method); } // UnityEngine.Component UnityEngine.ParticleCollisionEvent::InstanceIDToColliderComponent(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * ParticleCollisionEvent_InstanceIDToColliderComponent_m910880B728D5E4C69F257379ADA56A59E29B4F40 (int32_t ___instanceID0, const RuntimeMethod* method) { typedef Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * (*ParticleCollisionEvent_InstanceIDToColliderComponent_m910880B728D5E4C69F257379ADA56A59E29B4F40_ftn) (int32_t); static ParticleCollisionEvent_InstanceIDToColliderComponent_m910880B728D5E4C69F257379ADA56A59E29B4F40_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ParticleCollisionEvent_InstanceIDToColliderComponent_m910880B728D5E4C69F257379ADA56A59E29B4F40_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleCollisionEvent::InstanceIDToColliderComponent(System.Int32)"); Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * retVal = _il2cpp_icall_func(___instanceID0); return retVal; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 UnityEngine.ParticlePhysicsExtensions::GetCollisionEvents(UnityEngine.ParticleSystem,UnityEngine.GameObject,System.Collections.Generic.List`1<UnityEngine.ParticleCollisionEvent>) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t ParticlePhysicsExtensions_GetCollisionEvents_m11DDE18328B0E4B9766D1581DFCB0E67BCFD097C (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___ps0, GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * ___go1, List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * ___collisionEvents2, const RuntimeMethod* method) { int32_t V_0 = 0; { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_0 = ___ps0; GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * L_1 = ___go1; List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * L_2 = ___collisionEvents2; int32_t L_3 = ParticleSystemExtensionsImpl_GetCollisionEvents_mADDEE9247E3C74C2227B14242968B2531AFCF0DE(L_0, L_1, L_2, /*hidden argument*/NULL); V_0 = L_3; goto IL_000c; } IL_000c: { int32_t L_4 = V_0; return L_4; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.ParticleSystem::Emit(UnityEngine.Vector3,UnityEngine.Vector3,System.Single,System.Single,UnityEngine.Color32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Emit_m8C3FCE4F94165CDF0B86326DDB5DB886C1D7B0CF (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___position0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___velocity1, float ___size2, float ___lifetime3, Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 ___color4, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ParticleSystem_Emit_m8C3FCE4F94165CDF0B86326DDB5DB886C1D7B0CF_MetadataUsageId); s_Il2CppMethodInitialized = true; } Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E V_0; memset((&V_0), 0, sizeof(V_0)); { il2cpp_codegen_initobj((&V_0), sizeof(Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E )); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = ___position0; Particle_set_position_m3E99F891841E8B03490433FAFF5B601A6D12BDEF((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), L_0, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_1 = ___velocity1; Particle_set_velocity_mD0476C793611AD570296960FB0CB8FECD387E99C((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), L_1, /*hidden argument*/NULL); float L_2 = ___lifetime3; Particle_set_lifetime_m0DB60575386F2D365BCCCAB07538FC2BFF81EC17((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), L_2, /*hidden argument*/NULL); float L_3 = ___lifetime3; Particle_set_startLifetime_mEEB2B63599B1E4D1B8B2CEE25F13A50F1BCE7BBE((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), L_3, /*hidden argument*/NULL); float L_4 = ___size2; Particle_set_startSize_m45B6CD1480219E30A96317D654B9439C8DB2DF87((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), L_4, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_5 = Vector3_get_zero_m3CDDCAE94581DF3BB16C4B40A100E28E9C6649C2(/*hidden argument*/NULL); Particle_set_rotation3D_m46DB39BFDEEF27C6119F5EEE2C0B1CA9093FC834((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), L_5, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_6 = Vector3_get_zero_m3CDDCAE94581DF3BB16C4B40A100E28E9C6649C2(/*hidden argument*/NULL); Particle_set_angularVelocity3D_m0F282D7EE110DF290E04B2B99FEC697ED89BF4EF((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), L_6, /*hidden argument*/NULL); Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 L_7 = ___color4; Particle_set_startColor_m67807C44D14862EBD8C030C1FE094E8438384AA6((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), L_7, /*hidden argument*/NULL); Particle_set_randomSeed_m1311237E65918DDD765FC4D6BAE85047D8B8CBCE((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), 5, /*hidden argument*/NULL); ParticleSystem_EmitOld_Internal_m4313E5BD80E21011786EA12F2D2D9EFE9186320E(__this, (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&V_0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.ParticleSystem::Emit(UnityEngine.ParticleSystem/Particle) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Emit_m26C1CE51747F6F96A02AF1E56DDF3C3539FC926D (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E ___particle0, const RuntimeMethod* method) { { ParticleSystem_EmitOld_Internal_m4313E5BD80E21011786EA12F2D2D9EFE9186320E(__this, (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)(&___particle0), /*hidden argument*/NULL); return; } } // System.Void UnityEngine.ParticleSystem::Play(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Play_mBB238026E6389F44C76498D31038FE7A8C47E3AA (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, bool ___withChildren0, const RuntimeMethod* method) { typedef void (*ParticleSystem_Play_mBB238026E6389F44C76498D31038FE7A8C47E3AA_ftn) (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D *, bool); static ParticleSystem_Play_mBB238026E6389F44C76498D31038FE7A8C47E3AA_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ParticleSystem_Play_mBB238026E6389F44C76498D31038FE7A8C47E3AA_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::Play(System.Boolean)"); _il2cpp_icall_func(__this, ___withChildren0); } // System.Void UnityEngine.ParticleSystem::Play() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Play_m5BC5E6B56FCF639CAD5DF41B51DC05A0B444212F (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, const RuntimeMethod* method) { { ParticleSystem_Play_mBB238026E6389F44C76498D31038FE7A8C47E3AA(__this, (bool)1, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.ParticleSystem::Clear(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Clear_mA140B248D89675286ADAE837E9B82A65F0507164 (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, bool ___withChildren0, const RuntimeMethod* method) { typedef void (*ParticleSystem_Clear_mA140B248D89675286ADAE837E9B82A65F0507164_ftn) (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D *, bool); static ParticleSystem_Clear_mA140B248D89675286ADAE837E9B82A65F0507164_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ParticleSystem_Clear_mA140B248D89675286ADAE837E9B82A65F0507164_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::Clear(System.Boolean)"); _il2cpp_icall_func(__this, ___withChildren0); } // System.Void UnityEngine.ParticleSystem::Clear() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Clear_mE11D3D0E23B1C5AAFF1F432E278ED91F1D929FEE (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, const RuntimeMethod* method) { { ParticleSystem_Clear_mA140B248D89675286ADAE837E9B82A65F0507164(__this, (bool)1, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.ParticleSystem::Emit(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Emit_m4C0873B2917D6C3E000609EA35B3C3F648B0BBC2 (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, int32_t ___count0, const RuntimeMethod* method) { { int32_t L_0 = ___count0; ParticleSystem_Emit_Internal_m1857956B7219B8232C1777E515706F8075C8B925(__this, L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.ParticleSystem::Emit_Internal(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Emit_Internal_m1857956B7219B8232C1777E515706F8075C8B925 (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, int32_t ___count0, const RuntimeMethod* method) { typedef void (*ParticleSystem_Emit_Internal_m1857956B7219B8232C1777E515706F8075C8B925_ftn) (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D *, int32_t); static ParticleSystem_Emit_Internal_m1857956B7219B8232C1777E515706F8075C8B925_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ParticleSystem_Emit_Internal_m1857956B7219B8232C1777E515706F8075C8B925_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::Emit_Internal(System.Int32)"); _il2cpp_icall_func(__this, ___count0); } // System.Void UnityEngine.ParticleSystem::Emit(UnityEngine.ParticleSystem/EmitParams,System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Emit_mC0F1810F887D9EDE111F2307F2280CD0E4BA6AA2 (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, EmitParams_t03557E552852EC6B71876CD05C4098733702A219 ___emitParams0, int32_t ___count1, const RuntimeMethod* method) { { int32_t L_0 = ___count1; ParticleSystem_Emit_Injected_mB34A23399928EDC3111C060A2346A1EF63E1B9CC(__this, (EmitParams_t03557E552852EC6B71876CD05C4098733702A219 *)(&___emitParams0), L_0, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.ParticleSystem::EmitOld_Internal(UnityEngine.ParticleSystem/Particle&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_EmitOld_Internal_m4313E5BD80E21011786EA12F2D2D9EFE9186320E (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * ___particle0, const RuntimeMethod* method) { typedef void (*ParticleSystem_EmitOld_Internal_m4313E5BD80E21011786EA12F2D2D9EFE9186320E_ftn) (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D *, Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *); static ParticleSystem_EmitOld_Internal_m4313E5BD80E21011786EA12F2D2D9EFE9186320E_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ParticleSystem_EmitOld_Internal_m4313E5BD80E21011786EA12F2D2D9EFE9186320E_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::EmitOld_Internal(UnityEngine.ParticleSystem/Particle&)"); _il2cpp_icall_func(__this, ___particle0); } // UnityEngine.ParticleSystem/MainModule UnityEngine.ParticleSystem::get_main() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 ParticleSystem_get_main_m360B0AA57C71DE0358B6B07133C68B5FD88C742F (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, const RuntimeMethod* method) { MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 V_0; memset((&V_0), 0, sizeof(V_0)); { MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 L_0; memset((&L_0), 0, sizeof(L_0)); MainModule__ctor_m10DC65291ACEC243EC5302404E059717B552BA7A((&L_0), __this, /*hidden argument*/NULL); V_0 = L_0; goto IL_000a; } IL_000a: { MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 L_1 = V_0; return L_1; } } // UnityEngine.ParticleSystem/EmissionModule UnityEngine.ParticleSystem::get_emission() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 ParticleSystem_get_emission_mA1204EAF07A6C6B3F65B45295797A1FFF64D343C (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, const RuntimeMethod* method) { EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 V_0; memset((&V_0), 0, sizeof(V_0)); { EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 L_0; memset((&L_0), 0, sizeof(L_0)); EmissionModule__ctor_mD6B4029B58ECFECE0567E7FD67962FEF52B15843((&L_0), __this, /*hidden argument*/NULL); V_0 = L_0; goto IL_000a; } IL_000a: { EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 L_1 = V_0; return L_1; } } // System.Void UnityEngine.ParticleSystem::Emit_Injected(UnityEngine.ParticleSystem/EmitParams&,System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Emit_Injected_mB34A23399928EDC3111C060A2346A1EF63E1B9CC (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, EmitParams_t03557E552852EC6B71876CD05C4098733702A219 * ___emitParams0, int32_t ___count1, const RuntimeMethod* method) { typedef void (*ParticleSystem_Emit_Injected_mB34A23399928EDC3111C060A2346A1EF63E1B9CC_ftn) (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D *, EmitParams_t03557E552852EC6B71876CD05C4098733702A219 *, int32_t); static ParticleSystem_Emit_Injected_mB34A23399928EDC3111C060A2346A1EF63E1B9CC_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ParticleSystem_Emit_Injected_mB34A23399928EDC3111C060A2346A1EF63E1B9CC_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::Emit_Injected(UnityEngine.ParticleSystem/EmitParams&,System.Int32)"); _il2cpp_icall_func(__this, ___emitParams0, ___count1); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Conversion methods for marshalling of: UnityEngine.ParticleSystem/EmissionModule IL2CPP_EXTERN_C void EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshal_pinvoke(const EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1& unmarshaled, EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_pinvoke& marshaled) { Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'EmissionModule': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL); } IL2CPP_EXTERN_C void EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshal_pinvoke_back(const EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_pinvoke& marshaled, EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1& unmarshaled) { Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'EmissionModule': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL); } // Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/EmissionModule IL2CPP_EXTERN_C void EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshal_pinvoke_cleanup(EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.ParticleSystem/EmissionModule IL2CPP_EXTERN_C void EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshal_com(const EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1& unmarshaled, EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_com& marshaled) { Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'EmissionModule': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL); } IL2CPP_EXTERN_C void EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshal_com_back(const EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_com& marshaled, EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1& unmarshaled) { Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'EmissionModule': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL); } // Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/EmissionModule IL2CPP_EXTERN_C void EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshal_com_cleanup(EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_com& marshaled) { } // System.Void UnityEngine.ParticleSystem/EmissionModule::.ctor(UnityEngine.ParticleSystem) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EmissionModule__ctor_mD6B4029B58ECFECE0567E7FD67962FEF52B15843 (EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * __this, ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___particleSystem0, const RuntimeMethod* method) { { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_0 = ___particleSystem0; __this->set_m_ParticleSystem_0(L_0); return; } } IL2CPP_EXTERN_C void EmissionModule__ctor_mD6B4029B58ECFECE0567E7FD67962FEF52B15843_AdjustorThunk (RuntimeObject * __this, ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___particleSystem0, const RuntimeMethod* method) { int32_t _offset = 1; EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * _thisAdjusted = reinterpret_cast<EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 *>(__this + _offset); EmissionModule__ctor_mD6B4029B58ECFECE0567E7FD67962FEF52B15843(_thisAdjusted, ___particleSystem0, method); } // System.Void UnityEngine.ParticleSystem/EmissionModule::set_enabled(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EmissionModule_set_enabled_m3896B441BDE0F0752A6D113012B20D5D31B16D36 (EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * __this, bool ___value0, const RuntimeMethod* method) { { bool L_0 = ___value0; EmissionModule_set_enabled_Injected_m80C70B60E49D3ADE643B12579CE8CD119BD7D5F4((EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 *)__this, L_0, /*hidden argument*/NULL); return; } } IL2CPP_EXTERN_C void EmissionModule_set_enabled_m3896B441BDE0F0752A6D113012B20D5D31B16D36_AdjustorThunk (RuntimeObject * __this, bool ___value0, const RuntimeMethod* method) { int32_t _offset = 1; EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * _thisAdjusted = reinterpret_cast<EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 *>(__this + _offset); EmissionModule_set_enabled_m3896B441BDE0F0752A6D113012B20D5D31B16D36(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/EmissionModule::set_enabled_Injected(UnityEngine.ParticleSystem/EmissionModule&,System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EmissionModule_set_enabled_Injected_m80C70B60E49D3ADE643B12579CE8CD119BD7D5F4 (EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * ____unity_self0, bool ___value1, const RuntimeMethod* method) { typedef void (*EmissionModule_set_enabled_Injected_m80C70B60E49D3ADE643B12579CE8CD119BD7D5F4_ftn) (EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 *, bool); static EmissionModule_set_enabled_Injected_m80C70B60E49D3ADE643B12579CE8CD119BD7D5F4_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (EmissionModule_set_enabled_Injected_m80C70B60E49D3ADE643B12579CE8CD119BD7D5F4_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/EmissionModule::set_enabled_Injected(UnityEngine.ParticleSystem/EmissionModule&,System.Boolean)"); _il2cpp_icall_func(____unity_self0, ___value1); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Conversion methods for marshalling of: UnityEngine.ParticleSystem/EmitParams IL2CPP_EXTERN_C void EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshal_pinvoke(const EmitParams_t03557E552852EC6B71876CD05C4098733702A219& unmarshaled, EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshaled_pinvoke& marshaled) { marshaled.___m_Particle_0 = unmarshaled.get_m_Particle_0(); marshaled.___m_PositionSet_1 = static_cast<int32_t>(unmarshaled.get_m_PositionSet_1()); marshaled.___m_VelocitySet_2 = static_cast<int32_t>(unmarshaled.get_m_VelocitySet_2()); marshaled.___m_AxisOfRotationSet_3 = static_cast<int32_t>(unmarshaled.get_m_AxisOfRotationSet_3()); marshaled.___m_RotationSet_4 = static_cast<int32_t>(unmarshaled.get_m_RotationSet_4()); marshaled.___m_AngularVelocitySet_5 = static_cast<int32_t>(unmarshaled.get_m_AngularVelocitySet_5()); marshaled.___m_StartSizeSet_6 = static_cast<int32_t>(unmarshaled.get_m_StartSizeSet_6()); marshaled.___m_StartColorSet_7 = static_cast<int32_t>(unmarshaled.get_m_StartColorSet_7()); marshaled.___m_RandomSeedSet_8 = static_cast<int32_t>(unmarshaled.get_m_RandomSeedSet_8()); marshaled.___m_StartLifetimeSet_9 = static_cast<int32_t>(unmarshaled.get_m_StartLifetimeSet_9()); marshaled.___m_MeshIndexSet_10 = static_cast<int32_t>(unmarshaled.get_m_MeshIndexSet_10()); marshaled.___m_ApplyShapeToPosition_11 = static_cast<int32_t>(unmarshaled.get_m_ApplyShapeToPosition_11()); } IL2CPP_EXTERN_C void EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshal_pinvoke_back(const EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshaled_pinvoke& marshaled, EmitParams_t03557E552852EC6B71876CD05C4098733702A219& unmarshaled) { Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E unmarshaled_m_Particle_temp_0; memset((&unmarshaled_m_Particle_temp_0), 0, sizeof(unmarshaled_m_Particle_temp_0)); unmarshaled_m_Particle_temp_0 = marshaled.___m_Particle_0; unmarshaled.set_m_Particle_0(unmarshaled_m_Particle_temp_0); bool unmarshaled_m_PositionSet_temp_1 = false; unmarshaled_m_PositionSet_temp_1 = static_cast<bool>(marshaled.___m_PositionSet_1); unmarshaled.set_m_PositionSet_1(unmarshaled_m_PositionSet_temp_1); bool unmarshaled_m_VelocitySet_temp_2 = false; unmarshaled_m_VelocitySet_temp_2 = static_cast<bool>(marshaled.___m_VelocitySet_2); unmarshaled.set_m_VelocitySet_2(unmarshaled_m_VelocitySet_temp_2); bool unmarshaled_m_AxisOfRotationSet_temp_3 = false; unmarshaled_m_AxisOfRotationSet_temp_3 = static_cast<bool>(marshaled.___m_AxisOfRotationSet_3); unmarshaled.set_m_AxisOfRotationSet_3(unmarshaled_m_AxisOfRotationSet_temp_3); bool unmarshaled_m_RotationSet_temp_4 = false; unmarshaled_m_RotationSet_temp_4 = static_cast<bool>(marshaled.___m_RotationSet_4); unmarshaled.set_m_RotationSet_4(unmarshaled_m_RotationSet_temp_4); bool unmarshaled_m_AngularVelocitySet_temp_5 = false; unmarshaled_m_AngularVelocitySet_temp_5 = static_cast<bool>(marshaled.___m_AngularVelocitySet_5); unmarshaled.set_m_AngularVelocitySet_5(unmarshaled_m_AngularVelocitySet_temp_5); bool unmarshaled_m_StartSizeSet_temp_6 = false; unmarshaled_m_StartSizeSet_temp_6 = static_cast<bool>(marshaled.___m_StartSizeSet_6); unmarshaled.set_m_StartSizeSet_6(unmarshaled_m_StartSizeSet_temp_6); bool unmarshaled_m_StartColorSet_temp_7 = false; unmarshaled_m_StartColorSet_temp_7 = static_cast<bool>(marshaled.___m_StartColorSet_7); unmarshaled.set_m_StartColorSet_7(unmarshaled_m_StartColorSet_temp_7); bool unmarshaled_m_RandomSeedSet_temp_8 = false; unmarshaled_m_RandomSeedSet_temp_8 = static_cast<bool>(marshaled.___m_RandomSeedSet_8); unmarshaled.set_m_RandomSeedSet_8(unmarshaled_m_RandomSeedSet_temp_8); bool unmarshaled_m_StartLifetimeSet_temp_9 = false; unmarshaled_m_StartLifetimeSet_temp_9 = static_cast<bool>(marshaled.___m_StartLifetimeSet_9); unmarshaled.set_m_StartLifetimeSet_9(unmarshaled_m_StartLifetimeSet_temp_9); bool unmarshaled_m_MeshIndexSet_temp_10 = false; unmarshaled_m_MeshIndexSet_temp_10 = static_cast<bool>(marshaled.___m_MeshIndexSet_10); unmarshaled.set_m_MeshIndexSet_10(unmarshaled_m_MeshIndexSet_temp_10); bool unmarshaled_m_ApplyShapeToPosition_temp_11 = false; unmarshaled_m_ApplyShapeToPosition_temp_11 = static_cast<bool>(marshaled.___m_ApplyShapeToPosition_11); unmarshaled.set_m_ApplyShapeToPosition_11(unmarshaled_m_ApplyShapeToPosition_temp_11); } // Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/EmitParams IL2CPP_EXTERN_C void EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshal_pinvoke_cleanup(EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.ParticleSystem/EmitParams IL2CPP_EXTERN_C void EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshal_com(const EmitParams_t03557E552852EC6B71876CD05C4098733702A219& unmarshaled, EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshaled_com& marshaled) { marshaled.___m_Particle_0 = unmarshaled.get_m_Particle_0(); marshaled.___m_PositionSet_1 = static_cast<int32_t>(unmarshaled.get_m_PositionSet_1()); marshaled.___m_VelocitySet_2 = static_cast<int32_t>(unmarshaled.get_m_VelocitySet_2()); marshaled.___m_AxisOfRotationSet_3 = static_cast<int32_t>(unmarshaled.get_m_AxisOfRotationSet_3()); marshaled.___m_RotationSet_4 = static_cast<int32_t>(unmarshaled.get_m_RotationSet_4()); marshaled.___m_AngularVelocitySet_5 = static_cast<int32_t>(unmarshaled.get_m_AngularVelocitySet_5()); marshaled.___m_StartSizeSet_6 = static_cast<int32_t>(unmarshaled.get_m_StartSizeSet_6()); marshaled.___m_StartColorSet_7 = static_cast<int32_t>(unmarshaled.get_m_StartColorSet_7()); marshaled.___m_RandomSeedSet_8 = static_cast<int32_t>(unmarshaled.get_m_RandomSeedSet_8()); marshaled.___m_StartLifetimeSet_9 = static_cast<int32_t>(unmarshaled.get_m_StartLifetimeSet_9()); marshaled.___m_MeshIndexSet_10 = static_cast<int32_t>(unmarshaled.get_m_MeshIndexSet_10()); marshaled.___m_ApplyShapeToPosition_11 = static_cast<int32_t>(unmarshaled.get_m_ApplyShapeToPosition_11()); } IL2CPP_EXTERN_C void EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshal_com_back(const EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshaled_com& marshaled, EmitParams_t03557E552852EC6B71876CD05C4098733702A219& unmarshaled) { Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E unmarshaled_m_Particle_temp_0; memset((&unmarshaled_m_Particle_temp_0), 0, sizeof(unmarshaled_m_Particle_temp_0)); unmarshaled_m_Particle_temp_0 = marshaled.___m_Particle_0; unmarshaled.set_m_Particle_0(unmarshaled_m_Particle_temp_0); bool unmarshaled_m_PositionSet_temp_1 = false; unmarshaled_m_PositionSet_temp_1 = static_cast<bool>(marshaled.___m_PositionSet_1); unmarshaled.set_m_PositionSet_1(unmarshaled_m_PositionSet_temp_1); bool unmarshaled_m_VelocitySet_temp_2 = false; unmarshaled_m_VelocitySet_temp_2 = static_cast<bool>(marshaled.___m_VelocitySet_2); unmarshaled.set_m_VelocitySet_2(unmarshaled_m_VelocitySet_temp_2); bool unmarshaled_m_AxisOfRotationSet_temp_3 = false; unmarshaled_m_AxisOfRotationSet_temp_3 = static_cast<bool>(marshaled.___m_AxisOfRotationSet_3); unmarshaled.set_m_AxisOfRotationSet_3(unmarshaled_m_AxisOfRotationSet_temp_3); bool unmarshaled_m_RotationSet_temp_4 = false; unmarshaled_m_RotationSet_temp_4 = static_cast<bool>(marshaled.___m_RotationSet_4); unmarshaled.set_m_RotationSet_4(unmarshaled_m_RotationSet_temp_4); bool unmarshaled_m_AngularVelocitySet_temp_5 = false; unmarshaled_m_AngularVelocitySet_temp_5 = static_cast<bool>(marshaled.___m_AngularVelocitySet_5); unmarshaled.set_m_AngularVelocitySet_5(unmarshaled_m_AngularVelocitySet_temp_5); bool unmarshaled_m_StartSizeSet_temp_6 = false; unmarshaled_m_StartSizeSet_temp_6 = static_cast<bool>(marshaled.___m_StartSizeSet_6); unmarshaled.set_m_StartSizeSet_6(unmarshaled_m_StartSizeSet_temp_6); bool unmarshaled_m_StartColorSet_temp_7 = false; unmarshaled_m_StartColorSet_temp_7 = static_cast<bool>(marshaled.___m_StartColorSet_7); unmarshaled.set_m_StartColorSet_7(unmarshaled_m_StartColorSet_temp_7); bool unmarshaled_m_RandomSeedSet_temp_8 = false; unmarshaled_m_RandomSeedSet_temp_8 = static_cast<bool>(marshaled.___m_RandomSeedSet_8); unmarshaled.set_m_RandomSeedSet_8(unmarshaled_m_RandomSeedSet_temp_8); bool unmarshaled_m_StartLifetimeSet_temp_9 = false; unmarshaled_m_StartLifetimeSet_temp_9 = static_cast<bool>(marshaled.___m_StartLifetimeSet_9); unmarshaled.set_m_StartLifetimeSet_9(unmarshaled_m_StartLifetimeSet_temp_9); bool unmarshaled_m_MeshIndexSet_temp_10 = false; unmarshaled_m_MeshIndexSet_temp_10 = static_cast<bool>(marshaled.___m_MeshIndexSet_10); unmarshaled.set_m_MeshIndexSet_10(unmarshaled_m_MeshIndexSet_temp_10); bool unmarshaled_m_ApplyShapeToPosition_temp_11 = false; unmarshaled_m_ApplyShapeToPosition_temp_11 = static_cast<bool>(marshaled.___m_ApplyShapeToPosition_11); unmarshaled.set_m_ApplyShapeToPosition_11(unmarshaled_m_ApplyShapeToPosition_temp_11); } // Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/EmitParams IL2CPP_EXTERN_C void EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshal_com_cleanup(EmitParams_t03557E552852EC6B71876CD05C4098733702A219_marshaled_com& marshaled) { } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Conversion methods for marshalling of: UnityEngine.ParticleSystem/MainModule IL2CPP_EXTERN_C void MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshal_pinvoke(const MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7& unmarshaled, MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_pinvoke& marshaled) { Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'MainModule': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL); } IL2CPP_EXTERN_C void MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshal_pinvoke_back(const MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_pinvoke& marshaled, MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7& unmarshaled) { Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'MainModule': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL); } // Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/MainModule IL2CPP_EXTERN_C void MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshal_pinvoke_cleanup(MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.ParticleSystem/MainModule IL2CPP_EXTERN_C void MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshal_com(const MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7& unmarshaled, MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_com& marshaled) { Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'MainModule': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL); } IL2CPP_EXTERN_C void MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshal_com_back(const MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_com& marshaled, MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7& unmarshaled) { Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'MainModule': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL); } // Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/MainModule IL2CPP_EXTERN_C void MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshal_com_cleanup(MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_com& marshaled) { } // System.Void UnityEngine.ParticleSystem/MainModule::.ctor(UnityEngine.ParticleSystem) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule__ctor_m10DC65291ACEC243EC5302404E059717B552BA7A (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___particleSystem0, const RuntimeMethod* method) { { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_0 = ___particleSystem0; __this->set_m_ParticleSystem_0(L_0); return; } } IL2CPP_EXTERN_C void MainModule__ctor_m10DC65291ACEC243EC5302404E059717B552BA7A_AdjustorThunk (RuntimeObject * __this, ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___particleSystem0, const RuntimeMethod* method) { int32_t _offset = 1; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * _thisAdjusted = reinterpret_cast<MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *>(__this + _offset); MainModule__ctor_m10DC65291ACEC243EC5302404E059717B552BA7A(_thisAdjusted, ___particleSystem0, method); } // System.Single UnityEngine.ParticleSystem/MainModule::get_startLifetimeMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startLifetimeMultiplier_m0D425E7689C0B99C5B9E8F8C4AE205600C1EA529 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method) { { float L_0 = MainModule_get_startLifetimeMultiplier_Injected_m595857A88FC82240A13F2A2B9EC4262CB2360EEC((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)__this, /*hidden argument*/NULL); return L_0; } } IL2CPP_EXTERN_C float MainModule_get_startLifetimeMultiplier_m0D425E7689C0B99C5B9E8F8C4AE205600C1EA529_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * _thisAdjusted = reinterpret_cast<MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *>(__this + _offset); return MainModule_get_startLifetimeMultiplier_m0D425E7689C0B99C5B9E8F8C4AE205600C1EA529(_thisAdjusted, method); } // System.Void UnityEngine.ParticleSystem/MainModule::set_startLifetimeMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startLifetimeMultiplier_mCD094E55BD574ECF3A8F5D616A2287130B6EC67B (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; MainModule_set_startLifetimeMultiplier_Injected_mDB91EC13ABF1C788DA5565D493F0DF896A45B2B4((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)__this, L_0, /*hidden argument*/NULL); return; } } IL2CPP_EXTERN_C void MainModule_set_startLifetimeMultiplier_mCD094E55BD574ECF3A8F5D616A2287130B6EC67B_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { int32_t _offset = 1; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * _thisAdjusted = reinterpret_cast<MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *>(__this + _offset); MainModule_set_startLifetimeMultiplier_mCD094E55BD574ECF3A8F5D616A2287130B6EC67B(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeed(UnityEngine.ParticleSystem/MinMaxCurve) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeed_m32CD8968F2B5572112DE22CC7B6E2B502222B4AE (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 ___value0, const RuntimeMethod* method) { { MainModule_set_startSpeed_Injected_m8E60F6BB2068411A562524F8F57FBFB6E3539D77((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)__this, (MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 *)(&___value0), /*hidden argument*/NULL); return; } } IL2CPP_EXTERN_C void MainModule_set_startSpeed_m32CD8968F2B5572112DE22CC7B6E2B502222B4AE_AdjustorThunk (RuntimeObject * __this, MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 ___value0, const RuntimeMethod* method) { int32_t _offset = 1; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * _thisAdjusted = reinterpret_cast<MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *>(__this + _offset); MainModule_set_startSpeed_m32CD8968F2B5572112DE22CC7B6E2B502222B4AE(_thisAdjusted, ___value0, method); } // System.Single UnityEngine.ParticleSystem/MainModule::get_startSpeedMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSpeedMultiplier_m22326AF745786C1748F6B165361CCC26917F214A (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method) { { float L_0 = MainModule_get_startSpeedMultiplier_Injected_mFEF854F99A621D3A4104CEE8EC9382829D4AB665((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)__this, /*hidden argument*/NULL); return L_0; } } IL2CPP_EXTERN_C float MainModule_get_startSpeedMultiplier_m22326AF745786C1748F6B165361CCC26917F214A_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * _thisAdjusted = reinterpret_cast<MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *>(__this + _offset); return MainModule_get_startSpeedMultiplier_m22326AF745786C1748F6B165361CCC26917F214A(_thisAdjusted, method); } // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeedMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeedMultiplier_m14E157EFF4BD78D8FDA701BE2BD0B398EF6F2453 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; MainModule_set_startSpeedMultiplier_Injected_m51E3D91BEFC4628CBF55A5B4CF97C1A2B7D0F1E9((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)__this, L_0, /*hidden argument*/NULL); return; } } IL2CPP_EXTERN_C void MainModule_set_startSpeedMultiplier_m14E157EFF4BD78D8FDA701BE2BD0B398EF6F2453_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { int32_t _offset = 1; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * _thisAdjusted = reinterpret_cast<MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *>(__this + _offset); MainModule_set_startSpeedMultiplier_m14E157EFF4BD78D8FDA701BE2BD0B398EF6F2453(_thisAdjusted, ___value0, method); } // System.Single UnityEngine.ParticleSystem/MainModule::get_startSizeMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSizeMultiplier_m8E241099DB1E4ECE4827E9507415C80012AEA312 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method) { { float L_0 = MainModule_get_startSizeMultiplier_Injected_mB3E13AEB7F30982961453FD2BD8FE1503202F41D((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)__this, /*hidden argument*/NULL); return L_0; } } IL2CPP_EXTERN_C float MainModule_get_startSizeMultiplier_m8E241099DB1E4ECE4827E9507415C80012AEA312_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method) { int32_t _offset = 1; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * _thisAdjusted = reinterpret_cast<MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *>(__this + _offset); return MainModule_get_startSizeMultiplier_m8E241099DB1E4ECE4827E9507415C80012AEA312(_thisAdjusted, method); } // System.Void UnityEngine.ParticleSystem/MainModule::set_startSizeMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSizeMultiplier_m6375840B2CADFF82321D7B52103FADC5AD144B8C (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; MainModule_set_startSizeMultiplier_Injected_m08751D61274A36C843B4EE5D4453A18CEB7D1B9F((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)__this, L_0, /*hidden argument*/NULL); return; } } IL2CPP_EXTERN_C void MainModule_set_startSizeMultiplier_m6375840B2CADFF82321D7B52103FADC5AD144B8C_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { int32_t _offset = 1; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * _thisAdjusted = reinterpret_cast<MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *>(__this + _offset); MainModule_set_startSizeMultiplier_m6375840B2CADFF82321D7B52103FADC5AD144B8C(_thisAdjusted, ___value0, method); } // System.Single UnityEngine.ParticleSystem/MainModule::get_startLifetimeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startLifetimeMultiplier_Injected_m595857A88FC82240A13F2A2B9EC4262CB2360EEC (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, const RuntimeMethod* method) { typedef float (*MainModule_get_startLifetimeMultiplier_Injected_m595857A88FC82240A13F2A2B9EC4262CB2360EEC_ftn) (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *); static MainModule_get_startLifetimeMultiplier_Injected_m595857A88FC82240A13F2A2B9EC4262CB2360EEC_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (MainModule_get_startLifetimeMultiplier_Injected_m595857A88FC82240A13F2A2B9EC4262CB2360EEC_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::get_startLifetimeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&)"); float retVal = _il2cpp_icall_func(____unity_self0); return retVal; } // System.Void UnityEngine.ParticleSystem/MainModule::set_startLifetimeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startLifetimeMultiplier_Injected_mDB91EC13ABF1C788DA5565D493F0DF896A45B2B4 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, float ___value1, const RuntimeMethod* method) { typedef void (*MainModule_set_startLifetimeMultiplier_Injected_mDB91EC13ABF1C788DA5565D493F0DF896A45B2B4_ftn) (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *, float); static MainModule_set_startLifetimeMultiplier_Injected_mDB91EC13ABF1C788DA5565D493F0DF896A45B2B4_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (MainModule_set_startLifetimeMultiplier_Injected_mDB91EC13ABF1C788DA5565D493F0DF896A45B2B4_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::set_startLifetimeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single)"); _il2cpp_icall_func(____unity_self0, ___value1); } // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeed_Injected(UnityEngine.ParticleSystem/MainModule&,UnityEngine.ParticleSystem/MinMaxCurve&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeed_Injected_m8E60F6BB2068411A562524F8F57FBFB6E3539D77 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 * ___value1, const RuntimeMethod* method) { typedef void (*MainModule_set_startSpeed_Injected_m8E60F6BB2068411A562524F8F57FBFB6E3539D77_ftn) (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *, MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 *); static MainModule_set_startSpeed_Injected_m8E60F6BB2068411A562524F8F57FBFB6E3539D77_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (MainModule_set_startSpeed_Injected_m8E60F6BB2068411A562524F8F57FBFB6E3539D77_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::set_startSpeed_Injected(UnityEngine.ParticleSystem/MainModule&,UnityEngine.ParticleSystem/MinMaxCurve&)"); _il2cpp_icall_func(____unity_self0, ___value1); } // System.Single UnityEngine.ParticleSystem/MainModule::get_startSpeedMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSpeedMultiplier_Injected_mFEF854F99A621D3A4104CEE8EC9382829D4AB665 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, const RuntimeMethod* method) { typedef float (*MainModule_get_startSpeedMultiplier_Injected_mFEF854F99A621D3A4104CEE8EC9382829D4AB665_ftn) (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *); static MainModule_get_startSpeedMultiplier_Injected_mFEF854F99A621D3A4104CEE8EC9382829D4AB665_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (MainModule_get_startSpeedMultiplier_Injected_mFEF854F99A621D3A4104CEE8EC9382829D4AB665_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::get_startSpeedMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&)"); float retVal = _il2cpp_icall_func(____unity_self0); return retVal; } // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeedMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeedMultiplier_Injected_m51E3D91BEFC4628CBF55A5B4CF97C1A2B7D0F1E9 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, float ___value1, const RuntimeMethod* method) { typedef void (*MainModule_set_startSpeedMultiplier_Injected_m51E3D91BEFC4628CBF55A5B4CF97C1A2B7D0F1E9_ftn) (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *, float); static MainModule_set_startSpeedMultiplier_Injected_m51E3D91BEFC4628CBF55A5B4CF97C1A2B7D0F1E9_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (MainModule_set_startSpeedMultiplier_Injected_m51E3D91BEFC4628CBF55A5B4CF97C1A2B7D0F1E9_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::set_startSpeedMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single)"); _il2cpp_icall_func(____unity_self0, ___value1); } // System.Single UnityEngine.ParticleSystem/MainModule::get_startSizeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSizeMultiplier_Injected_mB3E13AEB7F30982961453FD2BD8FE1503202F41D (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, const RuntimeMethod* method) { typedef float (*MainModule_get_startSizeMultiplier_Injected_mB3E13AEB7F30982961453FD2BD8FE1503202F41D_ftn) (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *); static MainModule_get_startSizeMultiplier_Injected_mB3E13AEB7F30982961453FD2BD8FE1503202F41D_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (MainModule_get_startSizeMultiplier_Injected_mB3E13AEB7F30982961453FD2BD8FE1503202F41D_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::get_startSizeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&)"); float retVal = _il2cpp_icall_func(____unity_self0); return retVal; } // System.Void UnityEngine.ParticleSystem/MainModule::set_startSizeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSizeMultiplier_Injected_m08751D61274A36C843B4EE5D4453A18CEB7D1B9F (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * ____unity_self0, float ___value1, const RuntimeMethod* method) { typedef void (*MainModule_set_startSizeMultiplier_Injected_m08751D61274A36C843B4EE5D4453A18CEB7D1B9F_ftn) (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *, float); static MainModule_set_startSizeMultiplier_Injected_m08751D61274A36C843B4EE5D4453A18CEB7D1B9F_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (MainModule_set_startSizeMultiplier_Injected_m08751D61274A36C843B4EE5D4453A18CEB7D1B9F_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::set_startSizeMultiplier_Injected(UnityEngine.ParticleSystem/MainModule&,System.Single)"); _il2cpp_icall_func(____unity_self0, ___value1); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.ParticleSystem/MinMaxCurve::.ctor(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MinMaxCurve__ctor_mE5FDFD4ADB7EA897D19133CF82DC290577B4DD29 (MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 * __this, float ___constant0, const RuntimeMethod* method) { { __this->set_m_Mode_0(0); __this->set_m_CurveMultiplier_1((0.0f)); __this->set_m_CurveMin_2((AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C *)NULL); __this->set_m_CurveMax_3((AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C *)NULL); __this->set_m_ConstantMin_4((0.0f)); float L_0 = ___constant0; __this->set_m_ConstantMax_5(L_0); return; } } IL2CPP_EXTERN_C void MinMaxCurve__ctor_mE5FDFD4ADB7EA897D19133CF82DC290577B4DD29_AdjustorThunk (RuntimeObject * __this, float ___constant0, const RuntimeMethod* method) { int32_t _offset = 1; MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 * _thisAdjusted = reinterpret_cast<MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 *>(__this + _offset); MinMaxCurve__ctor_mE5FDFD4ADB7EA897D19133CF82DC290577B4DD29(_thisAdjusted, ___constant0, method); } // UnityEngine.ParticleSystem/MinMaxCurve UnityEngine.ParticleSystem/MinMaxCurve::op_Implicit(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 MinMaxCurve_op_Implicit_m998EE9F8D83B9545F63E2DFA304E99620F0F707F (float ___constant0, const RuntimeMethod* method) { MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 V_0; memset((&V_0), 0, sizeof(V_0)); { float L_0 = ___constant0; MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 L_1; memset((&L_1), 0, sizeof(L_1)); MinMaxCurve__ctor_mE5FDFD4ADB7EA897D19133CF82DC290577B4DD29((&L_1), L_0, /*hidden argument*/NULL); V_0 = L_1; goto IL_000a; } IL_000a: { MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 L_2 = V_0; return L_2; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.ParticleSystem/Particle::set_lifetime(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_lifetime_m0DB60575386F2D365BCCCAB07538FC2BFF81EC17 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; Particle_set_remainingLifetime_mD6ABB0C19127BD86DE3723B443331E5968EE0E87((Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *)__this, L_0, /*hidden argument*/NULL); return; } } IL2CPP_EXTERN_C void Particle_set_lifetime_m0DB60575386F2D365BCCCAB07538FC2BFF81EC17_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_lifetime_m0DB60575386F2D365BCCCAB07538FC2BFF81EC17(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_position(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_position_m3E99F891841E8B03490433FAFF5B601A6D12BDEF (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method) { { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = ___value0; __this->set_m_Position_0(L_0); return; } } IL2CPP_EXTERN_C void Particle_set_position_m3E99F891841E8B03490433FAFF5B601A6D12BDEF_AdjustorThunk (RuntimeObject * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_position_m3E99F891841E8B03490433FAFF5B601A6D12BDEF(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_velocity(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_velocity_mD0476C793611AD570296960FB0CB8FECD387E99C (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method) { { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = ___value0; __this->set_m_Velocity_1(L_0); return; } } IL2CPP_EXTERN_C void Particle_set_velocity_mD0476C793611AD570296960FB0CB8FECD387E99C_AdjustorThunk (RuntimeObject * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_velocity_mD0476C793611AD570296960FB0CB8FECD387E99C(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_remainingLifetime(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_remainingLifetime_mD6ABB0C19127BD86DE3723B443331E5968EE0E87 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; __this->set_m_Lifetime_11(L_0); return; } } IL2CPP_EXTERN_C void Particle_set_remainingLifetime_mD6ABB0C19127BD86DE3723B443331E5968EE0E87_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_remainingLifetime_mD6ABB0C19127BD86DE3723B443331E5968EE0E87(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_startLifetime(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_startLifetime_mEEB2B63599B1E4D1B8B2CEE25F13A50F1BCE7BBE (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; __this->set_m_StartLifetime_12(L_0); return; } } IL2CPP_EXTERN_C void Particle_set_startLifetime_mEEB2B63599B1E4D1B8B2CEE25F13A50F1BCE7BBE_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_startLifetime_mEEB2B63599B1E4D1B8B2CEE25F13A50F1BCE7BBE(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_startColor(UnityEngine.Color32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_startColor_m67807C44D14862EBD8C030C1FE094E8438384AA6 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 ___value0, const RuntimeMethod* method) { { Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 L_0 = ___value0; __this->set_m_StartColor_8(L_0); return; } } IL2CPP_EXTERN_C void Particle_set_startColor_m67807C44D14862EBD8C030C1FE094E8438384AA6_AdjustorThunk (RuntimeObject * __this, Color32_t23ABC4AE0E0BDFD2E22EE1FA0DA3904FFE5F6E23 ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_startColor_m67807C44D14862EBD8C030C1FE094E8438384AA6(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_randomSeed(System.UInt32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_randomSeed_m1311237E65918DDD765FC4D6BAE85047D8B8CBCE (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, uint32_t ___value0, const RuntimeMethod* method) { { uint32_t L_0 = ___value0; __this->set_m_RandomSeed_9(L_0); return; } } IL2CPP_EXTERN_C void Particle_set_randomSeed_m1311237E65918DDD765FC4D6BAE85047D8B8CBCE_AdjustorThunk (RuntimeObject * __this, uint32_t ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_randomSeed_m1311237E65918DDD765FC4D6BAE85047D8B8CBCE(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_startSize(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_startSize_m45B6CD1480219E30A96317D654B9439C8DB2DF87 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, float ___value0, const RuntimeMethod* method) { { float L_0 = ___value0; float L_1 = ___value0; float L_2 = ___value0; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_3; memset((&L_3), 0, sizeof(L_3)); Vector3__ctor_m08F61F548AA5836D8789843ACB4A81E4963D2EE1((&L_3), L_0, L_1, L_2, /*hidden argument*/NULL); __this->set_m_StartSize_7(L_3); return; } } IL2CPP_EXTERN_C void Particle_set_startSize_m45B6CD1480219E30A96317D654B9439C8DB2DF87_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_startSize_m45B6CD1480219E30A96317D654B9439C8DB2DF87(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_rotation3D(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_rotation3D_m46DB39BFDEEF27C6119F5EEE2C0B1CA9093FC834 (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Particle_set_rotation3D_m46DB39BFDEEF27C6119F5EEE2C0B1CA9093FC834_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = ___value0; IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_1 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_0, (0.0174532924f), /*hidden argument*/NULL); __this->set_m_Rotation_5(L_1); uint32_t L_2 = __this->get_m_Flags_16(); __this->set_m_Flags_16(((int32_t)((int32_t)L_2|(int32_t)2))); return; } } IL2CPP_EXTERN_C void Particle_set_rotation3D_m46DB39BFDEEF27C6119F5EEE2C0B1CA9093FC834_AdjustorThunk (RuntimeObject * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_rotation3D_m46DB39BFDEEF27C6119F5EEE2C0B1CA9093FC834(_thisAdjusted, ___value0, method); } // System.Void UnityEngine.ParticleSystem/Particle::set_angularVelocity3D(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Particle_set_angularVelocity3D_m0F282D7EE110DF290E04B2B99FEC697ED89BF4EF (Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Particle_set_angularVelocity3D_m0F282D7EE110DF290E04B2B99FEC697ED89BF4EF_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = ___value0; IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_1 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_0, (0.0174532924f), /*hidden argument*/NULL); __this->set_m_AngularVelocity_6(L_1); uint32_t L_2 = __this->get_m_Flags_16(); __this->set_m_Flags_16(((int32_t)((int32_t)L_2|(int32_t)2))); return; } } IL2CPP_EXTERN_C void Particle_set_angularVelocity3D_m0F282D7EE110DF290E04B2B99FEC697ED89BF4EF_AdjustorThunk (RuntimeObject * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method) { int32_t _offset = 1; Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E * _thisAdjusted = reinterpret_cast<Particle_t64AF74F5D9C7EE7018AD98F29E4FF653558A581E *>(__this + _offset); Particle_set_angularVelocity3D_m0F282D7EE110DF290E04B2B99FEC697ED89BF4EF(_thisAdjusted, ___value0, method); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 UnityEngine.ParticleSystemExtensionsImpl::GetCollisionEvents(UnityEngine.ParticleSystem,UnityEngine.GameObject,System.Collections.Generic.List`1<UnityEngine.ParticleCollisionEvent>) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t ParticleSystemExtensionsImpl_GetCollisionEvents_mADDEE9247E3C74C2227B14242968B2531AFCF0DE (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___ps0, GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * ___go1, List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * ___collisionEvents2, const RuntimeMethod* method) { typedef int32_t (*ParticleSystemExtensionsImpl_GetCollisionEvents_mADDEE9247E3C74C2227B14242968B2531AFCF0DE_ftn) (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D *, GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F *, List_1_t2762C811E470D336E31761384C6E5382164DA4C7 *); static ParticleSystemExtensionsImpl_GetCollisionEvents_mADDEE9247E3C74C2227B14242968B2531AFCF0DE_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ParticleSystemExtensionsImpl_GetCollisionEvents_mADDEE9247E3C74C2227B14242968B2531AFCF0DE_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystemExtensionsImpl::GetCollisionEvents(UnityEngine.ParticleSystem,UnityEngine.GameObject,System.Collections.Generic.List`1<UnityEngine.ParticleCollisionEvent>)"); int32_t retVal = _il2cpp_icall_func(___ps0, ___go1, ___collisionEvents2); return retVal; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 UnityEngine.ParticleSystemRenderer::GetMeshes(UnityEngine.Mesh[]) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t ParticleSystemRenderer_GetMeshes_m4DE519F198B6A36169F307F1FA5D76FA28316AD2 (ParticleSystemRenderer_t86E4ED2C0ADF5D2E7FA3D636B6B070600D05C459 * __this, MeshU5BU5D_tDD9C723AA6F0225B35A93D871CDC2CEFF7F8CB89* ___meshes0, const RuntimeMethod* method) { typedef int32_t (*ParticleSystemRenderer_GetMeshes_m4DE519F198B6A36169F307F1FA5D76FA28316AD2_ftn) (ParticleSystemRenderer_t86E4ED2C0ADF5D2E7FA3D636B6B070600D05C459 *, MeshU5BU5D_tDD9C723AA6F0225B35A93D871CDC2CEFF7F8CB89*); static ParticleSystemRenderer_GetMeshes_m4DE519F198B6A36169F307F1FA5D76FA28316AD2_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (ParticleSystemRenderer_GetMeshes_m4DE519F198B6A36169F307F1FA5D76FA28316AD2_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystemRenderer::GetMeshes(UnityEngine.Mesh[])"); int32_t retVal = _il2cpp_icall_func(__this, ___meshes0); return retVal; } #ifdef __clang__ #pragma clang diagnostic pop #endif
58.277637
426
0.865847
[ "mesh", "object" ]
392ecff956e830e01596de94877c90cb96c37597
893
cpp
C++
code/arkin-apx/strip_cover/strip_cover.cpp
d-krupke/turncost
2bbe1f1b31eddca5c6e686988e715be7d76c37a3
[ "MIT" ]
null
null
null
code/arkin-apx/strip_cover/strip_cover.cpp
d-krupke/turncost
2bbe1f1b31eddca5c6e686988e715be7d76c37a3
[ "MIT" ]
null
null
null
code/arkin-apx/strip_cover/strip_cover.cpp
d-krupke/turncost
2bbe1f1b31eddca5c6e686988e715be7d76c37a3
[ "MIT" ]
null
null
null
// // Created by Dominik Krupke, http://krupke.cc on 10/9/17. // #include "strip_cover.h" namespace turncostcover { namespace arkinapx { std::vector<Strip> ComputeStripCover(const GridGraph &graph) { StripExtractor stripExtractor{}; auto strips = stripExtractor.ExtractStrips(graph); using AuxGraph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>; AuxGraph vcGraph{strips.size()}; for (unsigned i = 0; i < strips.size(); ++i) { for (unsigned j = i + 1; j < strips.size(); ++j) { if (strips.at(i).DoIntersect(strips.at(j))) { boost::add_edge(i, j, vcGraph); } } } assert(boost::num_edges(vcGraph) == graph.GetNumVertices()); auto vc_indices = bipartvc::get_minimal_vertex_cover(vcGraph); std::vector<Strip> strip_cover; for (auto i: vc_indices) { strip_cover.push_back(strips.at(i)); } return strip_cover; } } }
26.264706
87
0.674132
[ "vector" ]
3931bb7f91972e29b64ea27a5fb66e5786867dd2
4,572
cc
C++
MetroSVG/Internal/StyleSheet.cc
isabella232/metrosvg
2297bc32bd5b611cd4355deb2cba9dba6337e3e6
[ "Apache-2.0" ]
15
2016-01-29T06:10:46.000Z
2021-10-12T03:15:42.000Z
MetroSVG/Internal/StyleSheet.cc
isabella232/metrosvg
2297bc32bd5b611cd4355deb2cba9dba6337e3e6
[ "Apache-2.0" ]
1
2021-07-12T12:51:44.000Z
2021-07-12T12:51:44.000Z
MetroSVG/Internal/StyleSheet.cc
isabella232/metrosvg
2297bc32bd5b611cd4355deb2cba9dba6337e3e6
[ "Apache-2.0" ]
9
2016-01-25T04:22:55.000Z
2021-07-12T12:51:24.000Z
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MetroSVG/Internal/StyleSheet.h" #include "MetroSVG/Internal/StringPiece.h" #include "MetroSVG/Internal/StyleIterator.h" MSCStyleSheet *MSCStyleSheetCreateWithData(const char *data, size_t data_length) { return metrosvg::internal::ParseStyleSheetData(data, data_length); } void MSCStyleSheetDelete(MSCStyleSheet *style_sheet) { delete style_sheet; } namespace metrosvg { namespace internal { // ParserState is state for parsing CSS. // At OUTSIDE_CONTENTS, before reading selector name and after reading "}". // At BEFORE_VALUE, after reading selector name and before reading "{". // At FINDING_VALUE, reading values between "{" and "}". enum ParserState { OUTSIDE_CONTENTS, BEFORE_VALUE, FINDING_VALUE, }; MSCStyleSheet *ParseStyleSheetData(const char *data, size_t data_length) { ParserState state = OUTSIDE_CONTENTS; std::string selector_name; std::string selector_value; std::vector<std::pair<std::string, std::string>> selector_data; std::unordered_set<std::string> supported_styles; supported_styles.insert("fill"); supported_styles.insert("stop-color"); supported_styles.insert("stroke"); supported_styles.insert("stroke-width"); std::unique_ptr<MSCStyleSheet> style_sheet(new MSCStyleSheet); for (size_t i = 0; i < data_length; i++) { switch (state) { case OUTSIDE_CONTENTS: switch (data[i]) { case '.': while (('a' <= data[i + 1] && data[i + 1] <= 'z') || ('A' <= data[i + 1] && data[i + 1] <= 'Z') || ('0' <= data[i + 1] && data[i + 1] <= '9') || data[i + 1] == '-' || data[i + 1] == '_') { selector_name += data[(i++) + 1]; } state = BEFORE_VALUE; break; case '\n': case '\t': case ' ': break; default: return NULL; } break; case BEFORE_VALUE: switch (data[i]) { case '{': state = FINDING_VALUE; break; case ' ': break; default: return NULL; } break; case FINDING_VALUE: switch (data[i]) { case '}': { StringPiece sp = StringPiece(selector_value); StyleIterator style_iter(&sp, supported_styles); while (style_iter.Next()) { const std::string style_property = style_iter.property().as_std_string(); const std::string style_value = style_iter.value().as_std_string(); selector_data.push_back(std::pair<std::string, std::string>(style_property, style_value)); } style_sheet->entry.insert(std::make_pair(selector_name, selector_data)); selector_data.clear(); selector_name = ""; selector_value = ""; state = OUTSIDE_CONTENTS; break; } case ' ': case '\n': break; default: selector_value += data[i]; break; } break; } } return style_sheet.release(); } void MSCStyleSheetMerge(const MSCStyleSheet &source, MSCStyleSheet *dest) { if (dest == NULL) { return; } for (auto source_item : source.entry) { auto dest_item = dest->entry.find(source_item.first); if (dest_item == dest->entry.end()) { dest->entry.insert(source_item); } else { dest_item->second.insert(dest_item->second.end(), source_item.second.begin(), source_item.second.end()); } } } } // namespace internal } // namespace metrosvg
31.972028
75
0.558618
[ "vector" ]
393621e63c0c5daf0e20ad9463d29b0c3cfba53e
9,340
cpp
C++
src/nv38box/nv/nv_manip.cpp
darwin/inferno
e87017763abae0cfe09d47987f5f6ac37c4f073d
[ "Zlib" ]
2
2016-05-09T11:57:28.000Z
2021-07-28T16:46:08.000Z
src/nv38box/nv/nv_manip.cpp
darwin/inferno
e87017763abae0cfe09d47987f5f6ac37c4f073d
[ "Zlib" ]
null
null
null
src/nv38box/nv/nv_manip.cpp
darwin/inferno
e87017763abae0cfe09d47987f5f6ac37c4f073d
[ "Zlib" ]
null
null
null
#ifndef _nv_manip_h_ #include "nv_manip.h" #endif // _nv_manip_h_ nv_manip::nv_manip() : _mode(_NIL), _behavior(CAMERA|PAN|TRANSLATE|ROTATE), _track_quat(quat_id), _curquat(quat_id), _mouse_start(vec2_null), _eye_pos(vec3_null), _focus_pos(vec3_null), _eye_y(vec3_z), // _eye_y(vec3_y), // hack by woid _m(mat4_id), _p(mat4_id), _camera(mat4_id), _near_z(nv_zero), _far_z(nv_zero), _fov(80.0), _screen_ratio(nv_one) { } void nv_manip::reset() { _track_quat = quat_id; _curquat = quat_id; _mode = _NIL; _m = mat4_id; _mouse_start = vec2_null; _focus_pos = vec3_null; } void nv_manip::set_manip_behavior(long flag) { _behavior = flag; } long nv_manip::get_manip_behavior() const { return _behavior; } long nv_manip::get_manip_mode() const { return _mode; } void nv_manip::mouse_down(const vec2 & pt, int state, nv_manip_mode mode) { _m_old = _m; _mouse_start.x = pt.x; _mouse_start.y = pt.y; _track_quat = _curquat; _prev_eye_pos = _eye_pos; _prev_focus_pos = _focus_pos; _mode = mode; } void nv_manip::mouse_down(const vec2 & pt, int state) { if (state & LMOUSE_DN) { _m_old = _m; _mouse_start.x = pt.x; _mouse_start.y = pt.y; _track_quat = _curquat; _prev_eye_pos = _eye_pos; _prev_focus_pos = _focus_pos; if ( state & CTRL_DN) _mode = _DOLLY; else if ( state & SHIFT_DN) _mode = _PAN; else _mode = _TUMBLE; } } void nv_manip::mouse_up(const vec2 & pt, int state) { _m_old = _m; _mouse_start.x = pt.x; _mouse_start.y = pt.y; _track_quat = _curquat; if (state & LMOUSE_UP) { _mode = _NIL; } } void nv_manip::mouse_move(const vec2 & pt, int state, const nv_scalar & z_scale) { vec3 tmp; quat tmpquat; mat4 inv_m; vec3 offset; switch(_mode) { case _TUMBLE: { vec2 pt1( ( nv_two * _mouse_start.x - _screen_width) / _screen_width, ( _screen_height - nv_two * _mouse_start.y ) / _screen_height); vec2 pt2( ( nv_two * pt.x - _screen_width) / _screen_width, ( _screen_height - nv_two * pt.y ) / _screen_height); if (_behavior & CAMERA_THIRD_PERSON) { pt2.x -= pt1.x; pt2.y -= pt1.y; pt1.x = pt1.y = 0; } trackball( tmpquat, pt1, pt2, nv_scalar(0.8)); if (_behavior & ROTATE) { quat cam_rot, inv_cam_rot; _camera.get_rot(cam_rot); conj(inv_cam_rot, cam_rot); if (_behavior & CAMERA_THIRD_PERSON) { conj(tmpquat); _curquat = _track_quat * inv_cam_rot * tmpquat * cam_rot; } else if (_behavior & CAMERA) // Setting the camera in first person is equivalent to having _camera equal to _m in the third person camera formula _curquat = tmpquat * _track_quat; else if (_behavior & OBJECT) // In object mode _curquat is the inverse of _curquat in camera mode _curquat = inv_cam_rot * tmpquat * cam_rot * _track_quat; if (_behavior & (CAMERA | CAMERA_THIRD_PERSON)) { mat3 M; sub(tmp,_prev_eye_pos,_focus_pos); quat_2_mat(M, _curquat ); nv_scalar mag = nv_norm(tmp); _eye_y = vec3(M.a10, M.a11, M.a12); vec3 z(M.a20, M.a21, M.a22); scale(z,mag); add(_eye_pos,z,_focus_pos); look_at( _m, _eye_pos, _focus_pos, _eye_y); } else if (_behavior & OBJECT) { _m.set_rot( _curquat ); } } break; } case _DOLLY: { nv_scalar z_delta = z_scale * ((pt.y - _mouse_start.y) / _screen_height * (_far_z - _near_z)); if (_behavior & TRANSLATE) { if (_behavior & (CAMERA | CAMERA_THIRD_PERSON)) { vec3 z; vec3 norm_z; sub(z,_prev_eye_pos,_prev_focus_pos); norm_z = z; normalize(norm_z); vec3 z_offset(norm_z); scale(z_offset, z_delta); add(_eye_pos, _prev_eye_pos, z_offset); if (!(_behavior & DONT_TRANSLATE_FOCUS)) add(_focus_pos, _prev_focus_pos, z_offset); look_at( _m, _eye_pos, _focus_pos, _eye_y); if (_behavior & DONT_TRANSLATE_FOCUS) _m.get_rot(_curquat); } else if (_behavior & OBJECT) { vec3 obj_pos = vec3(_m_old.x, _m_old.y, _m_old.z ); vec3 eye_obj_pos; mat4 invcam; invert(invcam, _camera); mult_pos(eye_obj_pos, _camera, obj_pos); eye_obj_pos.z += z_delta * nv_zero_5; mult_pos(obj_pos, invcam, eye_obj_pos); _m.x = obj_pos.x; _m.y = obj_pos.y; _m.z = obj_pos.z; } } break; } case _PAN: { if (_behavior & PAN) { vec2 pt_delta; if (_behavior & PAN_RELATIVE) { vec2 pt1( ( nv_two * _mouse_start.x - _screen_width) / _screen_width, ( _screen_height - nv_two * _mouse_start.y ) / _screen_height); vec2 pt2( ( nv_two * pt.x - _screen_width) / _screen_width, ( _screen_height - nv_two * pt.y ) / _screen_height); // pt_delta = pt2 - pt1; pt_delta = (pt2 - pt1) * vec2(5,5); // woid's hack } else { pt_delta.x = pt.x * nv_two / _screen_width - nv_one; pt_delta.y = (_screen_height - pt.y ) * nv_two / _screen_height - nv_one; } if (_behavior & (CAMERA | CAMERA_THIRD_PERSON)) { if (_behavior & CAMERA_THIRD_PERSON) { pt_delta.x = - pt_delta.x; pt_delta.y = - pt_delta.y; invert(inv_m, _camera); } else invert(inv_m, _m); nv_scalar fov2 = (nv_scalar)-tan(nv_zero_5 * nv_to_rad * _fov ) * _m_old.z; vec3 in( (nv_scalar)(pt_delta.x * fov2 * _screen_ratio), (nv_scalar)(pt_delta.y * fov2), (nv_scalar)(_behavior & PAN_RELATIVE ? 0 : _m_old.z) ); mult_dir(offset, inv_m, in); if (!(_behavior & PAN_RELATIVE)) { add(offset, offset, _prev_eye_pos); scale(offset,-nv_one); } add(_eye_pos, _prev_eye_pos, offset); add(_focus_pos, _prev_focus_pos, offset); look_at( _m, _eye_pos, _focus_pos, _eye_y); } else if (_behavior & OBJECT) { vec3 obj_pos = vec3(_m_old.x, _m_old.y, _m_old.z ); vec3 eye_obj_pos; mult_pos(eye_obj_pos, _camera, obj_pos); nv_scalar fov2 = (nv_scalar)(-tan(nv_zero_5 * nv_to_rad * _fov ) * eye_obj_pos.z); vec3 shift( (nv_scalar)(pt_delta.x * fov2 * _screen_ratio), (nv_scalar)(pt_delta.y * fov2), (nv_scalar)(_behavior & PAN_RELATIVE ? 0 : obj_pos.z) ); invert(inv_m,_camera); mult_dir(offset, inv_m, shift); if (_behavior & PAN_RELATIVE) { _m.x = _m_old.x + offset.x; _m.y = _m_old.y + offset.y; _m.z = _m_old.z + offset.z; } else { _m.x = offset.x; _m.y = offset.y; _m.z = offset.z; } } } break; } default: break; } } void nv_manip::set_clip_planes(const nv_scalar & near_z, const nv_scalar & far_z ) { _near_z = near_z; _far_z = far_z; } void nv_manip::set_fov(const nv_scalar & fov) { _fov = fov; } void nv_manip::set_screen_size(const unsigned int & width, const unsigned int & height ) { _screen_width = width; _screen_height = height; _screen_ratio = (double)width/(double)height; } void nv_manip::set_eye_pos(const vec3 & eye_pos) { _eye_pos = eye_pos; if (_behavior & (CAMERA | CAMERA_THIRD_PERSON) ) { look_at( _m, _eye_pos, _focus_pos, vec3_z); // look_at( _m, _eye_pos, _focus_pos, vec3_y); // hack by woid _track_quat = quat_id; _m.get_rot(_curquat); normalize(_curquat); } } const vec3 & nv_manip::get_eye_pos() const { return _eye_pos; } const vec3 & nv_manip::get_focus_pos() const { return _focus_pos; } void nv_manip::set_camera(const mat4 & camera) { _camera = camera; } const mat4 & nv_manip::get_camera() const { return _camera; } void nv_manip::set_focus_pos(const vec3 & focus_pos) { _focus_pos = focus_pos; if (_behavior & (CAMERA | CAMERA_THIRD_PERSON) ) { look_at( _m, _eye_pos, _focus_pos, vec3_z); // look_at( _m, _eye_pos, _focus_pos, vec3_y); // hach by woid _m.get_rot(_curquat); normalize(_curquat); } _track_quat = quat_id; } const mat4 & nv_manip::get_mat() const { return _m; } void nv_manip::set_mat(const mat4 & m) { _m = m; _m.get_rot(_curquat); } unsigned int nv_manip::get_screen_width() { return _screen_width; } unsigned int nv_manip::get_screen_height() { return _screen_height; } nv_scalar nv_manip::get_fov() { return _fov; } nv_scalar nv_manip::get_near_z() { return _near_z; } nv_scalar nv_manip::get_far_z() { return _far_z; } double nv_manip::get_screen_ratio() { return _screen_ratio; }
23.826531
122
0.575268
[ "object" ]
393de34dcd88cfdd5e032d465a2333a6dbdc5f12
18,503
cpp
C++
Server-Client/GameClientState.cpp
matzar/SFML-Networking
2623ae7c38ada2dfcbbdf725345222e58a86336b
[ "MIT" ]
null
null
null
Server-Client/GameClientState.cpp
matzar/SFML-Networking
2623ae7c38ada2dfcbbdf725345222e58a86336b
[ "MIT" ]
null
null
null
Server-Client/GameClientState.cpp
matzar/SFML-Networking
2623ae7c38ada2dfcbbdf725345222e58a86336b
[ "MIT" ]
null
null
null
#include "GameClientState.h" #include <sstream> GameClientState::GameClientState(sf::RenderWindow* hwnd, Input* in) { window = hwnd; input = in; lerp_mode = true; debug_mode = false; text.setFont(font); text.setCharacterSize(32); text.setPosition(10, 0); text.setString(""); // player player.setSize(sf::Vector2f(32, 32)); player.setTexture(&player_texture); sf::Vector2f initial_player_position(5.0f, 5.0f); player.setPosition(initial_player_position); // enemy enemy.setSize(sf::Vector2f(32, 32)); enemy.setTexture(&enemy_texture); enemy.setPosition(800, 500); //window->setMouseCursorVisible(false); } GameClientState::~GameClientState() {} void GameClientState::render() { beginDraw(); //level.render(window); window->draw(player); window->draw(enemy); window->draw(text); endDraw(); } void GameClientState::beginDraw() { window->clear(sf::Color(0, 0, 0)); } void GameClientState::endDraw() { window->display(); } void GameClientState::handleInput() { //The class that provides access to the keyboard state is sf::Keyboard.It only contains one function, isKeyPressed, which checks the current state of a key(pressed or released).It is a static function, so you don't need to instanciate sf::Keyboard to use it. //This function directly reads the keyboard state, ignoring the focus state of your window.This means that isKeyPressed may return true even if your window is inactive. // toggle debug mode to display socket messages if (input->isKeyDown(sf::Keyboard::D)) { input->setKeyUp(sf::Keyboard::D); debug_mode = !debug_mode; } } void GameClientState::displayText() { // the string buffer to convert numbers to a string std::ostringstream ss; // Put the text to display into the string buffer ss << "ESTABLISHED CONNECTION: " << established_connection << "\n" << "SERVER TIME: " << server_time << " CLIENT TIME: " << start_timing_latency << " OFFSET: " << offset << "MS" << " LAG: " << lag << "MS" << "\n" << "START TIMING LATENCY: " << start_timing_latency << " END TIMING LATENCY: " << end_timing_latency << " LATENCY: " << latency << "MS" << "\n" << "IP: " << Network::ip_address.getLocalAddress() << " PORT: " << Network::socket.getLocalPort() << " CLOCK: " << getCurrentTime(clock, offset); // display text text.setString(ss.str()); } // keep track of player's local positions for linear and quadratic prediction void GameClientState::keepTrackOfPlayerLocalPositions() { Message player_local_message; player_local_message.player_position.x = player.getPosition().x; player_local_message.player_position.y = player.getPosition().y; player_local_message.time = getCurrentTime(clock, offset); player_linear_prediction.keepTrackOfLinearLocalPositoins(player_local_message); player_quadratic_prediction.keepTrackOfQuadraticLocalPositoins(player_local_message); } // keep track of enemy's local positions for linear and quadratic prediction void GameClientState::keepTrackOfEnemyLocalPositions() { Message enemy_local_message; enemy_local_message.enemy_position.x = enemy.getPosition().x; enemy_local_message.enemy_position.y = enemy.getPosition().y; enemy_local_message.time = getCurrentTime(clock, offset); enemy_linear_prediction.keepTrackOfLinearLocalPositoins(enemy_local_message); enemy_quadratic_prediction.keepTrackOfQuadraticLocalPositoins(enemy_local_message); } void GameClientState::playerLinearPrediction() { // PLAYER LINEAR PREDICTION // start player's linear prediction only if the queue of local and network positions is full and the linear mode is on if (linear_prediction && player_linear_prediction.network_message_history.size() == player_linear_prediction.linear_message_number && player_linear_prediction.local_message_history.size() == player_linear_prediction.linear_message_number) { sf::Vector2f msg0_local_position(player_linear_prediction.local_message_history.front().player_position.x, player_linear_prediction.local_message_history.front().player_position.y); sf::Vector2f msg1_local_position(player_linear_prediction.local_message_history.back().player_position.x, player_linear_prediction.local_message_history.back().player_position.y); sf::Vector2f msg0_network_position(player_linear_prediction.network_message_history.front().player_position.x, player_linear_prediction.network_message_history.front().player_position.y); sf::Vector2f msg1_network_position(player_linear_prediction.network_message_history.back().player_position.x, player_linear_prediction.network_message_history.back().player_position.y); float msg0_time = player_linear_prediction.network_message_history.front().time; float msg1_time = player_linear_prediction.network_message_history.back().time; sf::Vector2f player_lerp_position = player_linear_prediction.linearInterpolation( player, // PLAYER msg0_local_position, msg1_local_position, msg0_network_position, msg1_network_position, msg0_time, msg1_time, getCurrentTime(clock, offset), lerp_mode); if (lerp_mode) { // add lerped to the history of the local posistions Message player_lerp_position_msg; player_lerp_position_msg.player_position.x = player_lerp_position.x; player_lerp_position_msg.player_position.y = player_lerp_position.y; player_lerp_position_msg.time = getCurrentTime(clock, offset); player_linear_prediction.keepTrackOfLinearLocalPositoins(player_lerp_position_msg); } } } void GameClientState::enemyLinearPrediciton() { // ENEMY LINEAR PREDICTION // start enemny's linear prediction only if the queue of local and network positions is full and the linear mode is on if (linear_prediction && enemy_linear_prediction.network_message_history.size() == enemy_linear_prediction.linear_message_number && enemy_linear_prediction.local_message_history.size() == enemy_linear_prediction.linear_message_number) { sf::Vector2f msg0_local_position(enemy_linear_prediction.local_message_history.front().enemy_position.x, enemy_linear_prediction.local_message_history.front().enemy_position.y); sf::Vector2f msg1_local_position(enemy_linear_prediction.local_message_history.back().enemy_position.x, enemy_linear_prediction.local_message_history.back().enemy_position.y); sf::Vector2f msg0_network_position(enemy_linear_prediction.network_message_history.front().enemy_position.x, enemy_linear_prediction.network_message_history.front().enemy_position.y); sf::Vector2f msg1_network_position(enemy_linear_prediction.network_message_history.back().enemy_position.x, enemy_linear_prediction.network_message_history.back().enemy_position.y); float msg0_time = enemy_linear_prediction.network_message_history.front().time; float msg1_time = enemy_linear_prediction.network_message_history.back().time; sf::Vector2f enemy_lerp_position = enemy_linear_prediction.linearInterpolation( enemy, // ENEMY msg0_local_position, msg1_local_position, msg0_network_position, msg1_network_position, msg0_time, msg1_time, getCurrentTime(clock, offset), lerp_mode); if (lerp_mode) { // add lerped to the history of the local posistions Message enemy_lerp_position_msg; enemy_lerp_position_msg.enemy_position.x = enemy_lerp_position.x; enemy_lerp_position_msg.enemy_position.y = enemy_lerp_position.y; enemy_lerp_position_msg.time = getCurrentTime(clock, offset); enemy_linear_prediction.keepTrackOfLinearLocalPositoins(enemy_lerp_position_msg); } } } void GameClientState::playerQuadraticPrediction() { // PLAYER QUADRATIC PREDICTION // start the quadratic prediction only if the queue of local and network positions is full and the quadratic mode is on if (quadratic_prediction && player_quadratic_prediction.network_message_history.size() == player_quadratic_prediction.quadratic_message_number && player_quadratic_prediction.local_message_history.size() == player_quadratic_prediction.quadratic_message_number) { // HISTORY OF LOCAL POSITIONS sf::Vector2f msg0_local_position(player_quadratic_prediction.local_message_history.at(0).player_position.x, player_quadratic_prediction.local_message_history.at(0).player_position.y); sf::Vector2f msg1_local_position(player_quadratic_prediction.local_message_history.at(1).player_position.x, player_quadratic_prediction.local_message_history.at(1).player_position.y); sf::Vector2f msg2_local_position(player_quadratic_prediction.local_message_history.at(2).player_position.x, player_quadratic_prediction.local_message_history.at(2).player_position.y); // HISTORY OF NETWORK POSITIONS sf::Vector2f msg0_network_position(player_quadratic_prediction.network_message_history.at(0).player_position.x, player_quadratic_prediction.network_message_history.at(0).player_position.y); sf::Vector2f msg1_network_position(player_quadratic_prediction.network_message_history.at(1).player_position.x, player_quadratic_prediction.network_message_history.at(1).player_position.y); sf::Vector2f msg2_network_position(player_quadratic_prediction.network_message_history.at(2).player_position.x, player_quadratic_prediction.network_message_history.at(2).player_position.y); // HISTORY OF TIME STAMPS float msg0_time = player_quadratic_prediction.local_message_history.at(0).time; float msg1_time = player_quadratic_prediction.local_message_history.at(1).time; float msg2_time = player_quadratic_prediction.local_message_history.at(2).time; sf::Vector2f player_lerp_position = player_quadratic_prediction.quadraticInterpolation( player, // PLAYER msg0_local_position, msg1_local_position, msg2_local_position, msg0_network_position, msg1_network_position, msg2_network_position, msg0_time, msg1_time, msg2_time, getCurrentTime(clock, offset), lerp_mode); if (lerp_mode) { // add lerped to the history of the local posistions Message player_lerp_position_msg; player_lerp_position_msg.player_position.x = player_lerp_position.x; player_lerp_position_msg.player_position.y = player_lerp_position.y; player_lerp_position_msg.time = getCurrentTime(clock, offset); player_linear_prediction.keepTrackOfLinearLocalPositoins(player_lerp_position_msg); } } } void GameClientState::enemyQuadraticPrediction() { // ENEMY QUADRATIC PREDICTION // start the quadratic prediction only if the queue of local and network positions is full and the quadratic mode is on if (quadratic_prediction && enemy_quadratic_prediction.network_message_history.size() == enemy_quadratic_prediction.quadratic_message_number && enemy_quadratic_prediction.local_message_history.size() == enemy_quadratic_prediction.quadratic_message_number) { // HISTORY OF LOCAL POSITIONS sf::Vector2f msg0_local_position(enemy_quadratic_prediction.local_message_history.at(0).enemy_position.x, enemy_quadratic_prediction.local_message_history.at(0).enemy_position.y); sf::Vector2f msg1_local_position(enemy_quadratic_prediction.local_message_history.at(1).enemy_position.x, enemy_quadratic_prediction.local_message_history.at(1).enemy_position.y); sf::Vector2f msg2_local_position(enemy_quadratic_prediction.local_message_history.at(2).enemy_position.x, enemy_quadratic_prediction.local_message_history.at(2).enemy_position.y); // HISTORY OF NETWORK POSITIONS sf::Vector2f msg0_network_position(enemy_quadratic_prediction.network_message_history.at(0).enemy_position.x, enemy_quadratic_prediction.network_message_history.at(0).enemy_position.y); sf::Vector2f msg1_network_position(enemy_quadratic_prediction.network_message_history.at(1).enemy_position.x, enemy_quadratic_prediction.network_message_history.at(1).enemy_position.y); sf::Vector2f msg2_network_position(enemy_quadratic_prediction.network_message_history.at(2).enemy_position.x, enemy_quadratic_prediction.network_message_history.at(2).enemy_position.y); // HISTORY OF TIME STAMPS float msg0_time = enemy_quadratic_prediction.local_message_history.at(0).time; float msg1_time = enemy_quadratic_prediction.local_message_history.at(1).time; float msg2_time = enemy_quadratic_prediction.local_message_history.at(2).time; sf::Vector2f enemy_lerp_position = enemy_quadratic_prediction.quadraticInterpolation( enemy, // ENEMY msg0_local_position, msg1_local_position, msg2_local_position, msg0_network_position, msg1_network_position, msg2_network_position, msg0_time, msg1_time, msg2_time, getCurrentTime(clock, offset), lerp_mode); if (lerp_mode) { // add lerped to the history of the local posistions Message enemy_lerp_position_msg; enemy_lerp_position_msg.enemy_position.x = enemy_lerp_position.x; enemy_lerp_position_msg.enemy_position.y = enemy_lerp_position.y; enemy_lerp_position_msg.time = getCurrentTime(clock, offset); enemy_linear_prediction.keepTrackOfLinearLocalPositoins(enemy_lerp_position_msg); } } } // CLIENT // // Send a message to the server... void GameClientState::sayHelloToServer(const bool& debug_mode) { ///////////////////////////////////////////////////////////////////////////////////// // RECEIVE (what server receives) - MUST MATCH packet_receive in the NetworkServer // ///////////////////////////////////////////////////////////////////////////////////// // Group the variables to send into a packet sf::Packet send_packet; // Message to send bool hello = true; send_packet << hello; // Send it over the network switch (socket.send(send_packet, Network::ip_address, Network::port)) { case sf::Socket::Partial: /* https://www.sfml-dev.org/tutorials/2.4/network-socket.php if only a part of the data was sent in the call, the return status will be sf::Socket::Partial to indicate a partial send. If sf::Socket::Partial is returned, you must make sure to handle the partial send properly or else data corruption will occur. When sending raw data, you must reattempt sending the raw data at the byte offset where the previous send call stopped. */ while (socket.send(send_packet, Network::ip_address, Network::port) != sf::Socket::Done) {} break; case sf::Socket::Done: // send a packet. // stop timing latency //GameClientState::ip_address = Network::ip_address; //GameClientState::port = Network::port; if (debug_mode) std::cout << "\nCLIENT: Sent one!\n"; break; case sf::Socket::NotReady: // No more data to receive (yet). // allow for timing latency when the client is establishing the connection //clocks_synced = false; if (debug_mode) std::cout << "\nCLIENT: Can't send now\n"; //if (debug_mode) return; case sf::Socket::Disconnected: if (debug_mode) std::cout << "CLIENT: Disconnected\n"; return; case sf::Socket::Error: // Something went wrong. if (debug_mode) std::cout << "\nCLIENT: receive didn't return Done\n"; return; default: // Something went wrong. if (debug_mode) std::cout << "\nCLIENT: send didn't return Done\n"; return; } /// Extract the variables contained in the packet //if (packet_to_send >> hello) //{ // send_packet = false; // // Data extracted successfully... //} } // CLIENT // // ...wait for the answer void GameClientState::syncClockWithServer(const bool& debug_mode) { // CHECK FOR INCOMING PACKETS while (true) { // Try to receive the packet from the other end /////////////////////////////////////////////////////////////////////////////// // SEND (What server is sending) MUST MATCH packet_send in the NetworkServer // /////////////////////////////////////////////////////////////////////////////// sf::Packet packet_receive; switch (socket.receive(packet_receive, Network::ip_address, Network::port)) { case sf::Socket::Partial: // clear the packet if only part of the data was received packet_receive.clear(); break; case sf::Socket::Done: // Received a packet. if (debug_mode) std::cout << "\nCLIENT: Got one!\n"; break; case sf::Socket::NotReady: // No more data to receive (yet). if (debug_mode) std::cout << "\nCLIENT: No more data to receive now\n"; return; case sf::Socket::Disconnected: if (debug_mode) std::cout << "CLIENT: Disconnected\n"; return; case sf::Socket::Error: // Something went wrong. if (debug_mode) std::cout << "\nCLIENT: receive didn't return Done\n"; return; default: // Something went wrong. if (debug_mode) std::cout << "\nCLIENT: receive didn't return Done\n"; return; } // Extract the variables contained in the packet // Packets must match to what the server is sending (e.g.: server is sending string, client must expect string) if (packet_receive >> server_time >> established_connection) { // Data extracted successfully... // Deal with the messages from the packet // end timing latency end_timing_latency = clock.getElapsedTime().asMilliseconds(); std::cout << "end_timing_latency: " << end_timing_latency << "\n"; latency = (end_timing_latency - start_timing_latency); std::cout << "latency: " << latency << "\n"; // calculate server time sf::Int32 client_time = clock.getElapsedTime().asMilliseconds(); std::cout << "client_time: " << client_time << "\n"; // server_time from the message offset = ((server_time + (0.5 * latency)) - client_time); std::cout << "offset: " << offset << "\n"; std::cout << "clocks synced" << "\n"; clocks_synced = true; return; } } } // CLIENT // void GameClientState::syncClocks(const bool& debug_mode) { // send message to the server... if (!clocks_synced) { // start timing latency start_timing_latency = clock.getElapsedTime().asMilliseconds(); std::cout << "start_timing_latency: " << start_timing_latency << "\n"; sayHelloToServer(debug_mode); // ...wait for the answer syncClockWithServer(debug_mode); } } void GameClientState::update() { // the client wants to receive the message as soon as it gets to it // so we don't need to keep track of the frames // display text displayText(); // SYNC THE CLIENT'S CLOCK WITH THE SERVER'S CLOCK - DO IT ONLY ONCE!!! syncClocks(debug_mode); // keep track of player's local positions for linear and quadratic prediction keepTrackOfPlayerLocalPositions(); // keep track of enemy's local positions for linear and quadratic prediction keepTrackOfEnemyLocalPositions(); // checkForIncomingPackets(debug_mode); playerLinearPrediction(); enemyLinearPrediciton(); playerQuadraticPrediction(); enemyQuadraticPrediction(); }
39.201271
259
0.757661
[ "render" ]
39436de2c8c4c5eb5b0dc6ab10897da5e4e02ee0
465
cpp
C++
object.cpp
Adnan-Ali-Ahmad/RK4-R3BP-SE
b76c0e3711cc0efa1ef1a2972c0ce939391afa8f
[ "Unlicense" ]
null
null
null
object.cpp
Adnan-Ali-Ahmad/RK4-R3BP-SE
b76c0e3711cc0efa1ef1a2972c0ce939391afa8f
[ "Unlicense" ]
null
null
null
object.cpp
Adnan-Ali-Ahmad/RK4-R3BP-SE
b76c0e3711cc0efa1ef1a2972c0ce939391afa8f
[ "Unlicense" ]
null
null
null
#include <object.h> object::object(double m,double R,double T,double density,double a,double e,double i,double w,double Om,double M) { this->m = m; this->R = R; this->T = T; this->x = x; this->y = y; this->z = z; this->vx = vx; this->vy = vy; this->vz = vz; this->a = a; this->e = e; this->i = i; this->w = w; this->Om = Om; this->M = M; this->density = density; } object::~object() { //dtor }
16.607143
112
0.505376
[ "object" ]
394390e527a6d2ea14a6ba18aaab6a1b4350e6dc
3,093
cpp
C++
Source/Ilum/Renderer/RenderPass/PreProcess/KullaConty.cpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
11
2022-01-09T05:32:56.000Z
2022-03-28T06:35:16.000Z
Source/Ilum/Renderer/RenderPass/PreProcess/KullaConty.cpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
null
null
null
Source/Ilum/Renderer/RenderPass/PreProcess/KullaConty.cpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
1
2021-11-20T15:39:03.000Z
2021-11-20T15:39:03.000Z
#include "KullaConty.hpp" #include "Renderer/RenderGraph/RenderGraph.hpp" #include "Renderer/Renderer.hpp" #include "Graphics/Vulkan/VK_Debugger.h" #include "ImGui/ImGuiContext.hpp" #include <imgui.h> namespace Ilum::pass { void KullaContyEnergy::setupPipeline(PipelineState &state) { state.shader.load(std::string(PROJECT_SOURCE_DIR) + "Source/Shaders/PreProcess/KullaContyEnergy.hlsl", VK_SHADER_STAGE_COMPUTE_BIT, Shader::Type::HLSL); state.declareAttachment("EmuLut", VK_FORMAT_R16_SFLOAT, 1024, 1024); state.addOutputAttachment("EmuLut", AttachmentState::Clear_Color); state.descriptor_bindings.bind(0, 0, "EmuLut", VK_DESCRIPTOR_TYPE_STORAGE_IMAGE); } void KullaContyEnergy::resolveResources(ResolveState &resolve) { } void KullaContyEnergy::render(RenderPassState &state) { if (!m_finish) { auto &cmd_buffer = state.command_buffer; vkCmdBindPipeline(cmd_buffer, state.pass.bind_point, state.pass.pipeline); for (auto &descriptor_set : state.pass.descriptor_sets) { vkCmdBindDescriptorSets(cmd_buffer, state.pass.bind_point, state.pass.pipeline_layout, descriptor_set.index(), 1, &descriptor_set.getDescriptorSet(), 0, nullptr); } vkCmdDispatch(cmd_buffer, 1024 / 32, 1024 / 32, 1); m_finish = true; } } void KullaContyEnergy::onImGui() { const auto &EmuLut = Renderer::instance()->getRenderGraph()->getAttachment("EmuLut"); ImGui::Text("Kulla Conty Energy Emu Precompute Result: "); ImGui::Image(ImGuiContext::textureID(EmuLut.getView(), Renderer::instance()->getSampler(Renderer::SamplerType::Trilinear_Clamp)), ImVec2(100, 100)); } void KullaContyAverage::setupPipeline(PipelineState &state) { state.shader.load(std::string(PROJECT_SOURCE_DIR) + "Source/Shaders/PreProcess/KullaContyEnergyAverage.hlsl", VK_SHADER_STAGE_COMPUTE_BIT, Shader::Type::HLSL); state.descriptor_bindings.bind(0, 0, "EmuLut", ImageViewType::Native, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE); state.declareAttachment("EavgLut", VK_FORMAT_R16_SFLOAT, 1024, 1024); state.addOutputAttachment("EavgLut", AttachmentState::Clear_Color); state.descriptor_bindings.bind(0, 1, "EavgLut", VK_DESCRIPTOR_TYPE_STORAGE_IMAGE); } void KullaContyAverage::resolveResources(ResolveState &resolve) { } void KullaContyAverage::render(RenderPassState &state) { if (!m_finish) { auto &cmd_buffer = state.command_buffer; vkCmdBindPipeline(cmd_buffer, state.pass.bind_point, state.pass.pipeline); for (auto &descriptor_set : state.pass.descriptor_sets) { vkCmdBindDescriptorSets(cmd_buffer, state.pass.bind_point, state.pass.pipeline_layout, descriptor_set.index(), 1, &descriptor_set.getDescriptorSet(), 0, nullptr); } vkCmdDispatch(cmd_buffer, 1024 / 32, 1, 1); m_finish = true; } } void KullaContyAverage::onImGui() { const auto &EavgLut = Renderer::instance()->getRenderGraph()->getAttachment("EavgLut"); ImGui::Text("Kulla Conty Energy Average Eavg Precompute Result: "); ImGui::Image(ImGuiContext::textureID(EavgLut.getView(), Renderer::instance()->getSampler(Renderer::SamplerType::Trilinear_Clamp)), ImVec2(100, 100)); } } // namespace Ilum::pass
32.557895
165
0.770773
[ "render" ]
394dcbe6663803255550f16658b11df7df62adc7
19,203
cpp
C++
src/modules/localization/src/segmentation/point_cloud_segmenter.cpp
joeyzhu00/FusionAD
7c912e399b9fcfa657d623f74be64921fc1a11ac
[ "MIT" ]
33
2018-06-03T19:45:42.000Z
2022-02-17T09:18:11.000Z
src/modules/localization/src/segmentation/point_cloud_segmenter.cpp
joeyzhu00/FusionAD
7c912e399b9fcfa657d623f74be64921fc1a11ac
[ "MIT" ]
167
2018-05-17T03:48:11.000Z
2019-04-30T21:57:01.000Z
src/modules/localization/src/segmentation/point_cloud_segmenter.cpp
joeyzhu00/FusionAD
7c912e399b9fcfa657d623f74be64921fc1a11ac
[ "MIT" ]
26
2018-07-04T04:32:54.000Z
2022-02-22T10:10:49.000Z
/*************************************************************************************** Author: Mitchell Sayer Program Name: point_cloud_segmenter.cc Brief: Date: MAR 1 2018 ***************************************************************************************/ #include "localization/segmentation/point_cloud_segmenter.h" #include "localization/segmentation/nanoflann.h" //************************************************************************************************ #define PI 3.14155926 bool CompareZ(Vec3 const& a, Vec3 const& b) { return a.z < b.z; } bool CompareX(Vec3 const& a, Vec3 const& b) { return a.x < b.x; } bool CompareTheta(Vec3 const& a, Vec3 const& b) { return a.theta < b.theta; } // Allows Vec3 to be printed directly to std::cout or std::cerr std::ostream& operator<<(std::ostream& os, const Vec3& vec) { return os << vec.x << ";" << vec.y << ";" << vec.z << ": " << vec.label; } /* Main implementation of GPF - Split data into n_segs along the x-axis (dir of travel) - Get initial seeds and use them to create first plane estimation - Repeat for n_iters using the estimated gnd points from each iter to calculate the new estimated */ void PointCloudSegmenter::GroundPlaneFitting(std::vector<Vec3>& cloud) { double segment_size = (2.0 * max_x) / n_segs; std::vector<Vec3> cloud_segs[n_segs]; std::vector<Vec3>::iterator it; int i = 0, cur_seg = 0; //Sort points in current segment by x value for segmentation int group; for (it = cloud.begin(); it != cloud.end(); it++, i++) { group = int((it->x + max_x) / segment_size); if (group < n_segs) { cloud_segs[group].push_back(*it); } else { cloud_segs[n_segs-1].push_back(*it); } } std::vector<Vec3> cur_p_gnd; //Pts belonging to ground surface in current segment iteration std::vector<Vec3> cur_p_ngnd; //Pts not belonging to ground surface in current segment iteration //Loop through each segment and apply GPF for (i = 0; i < n_segs; i++) { //Get initial ground points ExtractInitialSeeds(cloud_segs[i], cur_p_gnd, cur_p_ngnd); for(int j = 0; j < n_iter; j++) { Eigen::Vector4d normal = CalculatePlaneNormal(cur_p_gnd); double normal_mag = std::sqrt((normal(0) * normal(0)) + (normal(1) * normal(1)) + (normal(2) * normal(2))); if (!(std::isfinite(normal(0)) && std::isfinite(normal(1)) && std::isfinite(normal(2)) && std::isfinite(normal(3))) || (normal_mag == 0 || normal(3) == 0)) { continue; } std::cout << normal << std::endl; //Clear gnd points in between iterations cur_p_gnd.clear(); cur_p_ngnd.clear(); //Calculate distance from point to orthogonal projection //and compare to th_dist std::vector<Vec3>::iterator seg_it; for (seg_it = cloud_segs[i].begin(); seg_it != cloud_segs[i].end(); seg_it++) { double dist = std::abs((normal(0) * seg_it->x) + (normal(1) * seg_it->y) + (normal(2) * seg_it->z) + normal(3)) / normal_mag; if (dist < th_dist) { cur_p_gnd.push_back(*seg_it); } else { cur_p_ngnd.push_back(*seg_it); } } } for (it = cur_p_gnd.begin(); it != cur_p_gnd.end(); it++) { it->label = -3; } //Add results from current segment to main sets this->p_gnd.insert(p_gnd.end(), cur_p_gnd.begin(), cur_p_gnd.end()); this->p_ngnd.insert(p_ngnd.end(), cur_p_ngnd.begin(), cur_p_ngnd.end()); this->p_all.insert(p_all.end(), cur_p_gnd.begin(), cur_p_gnd.end()); this->p_all.insert(p_all.end(), cur_p_ngnd.begin(), cur_p_ngnd.end()); cur_p_gnd.clear(); cur_p_ngnd.clear(); } } /* Calculate Lowest Point Representative and calculate inital seed points using th_seeds */ void PointCloudSegmenter::ExtractInitialSeeds(std::vector<Vec3>& cloud_seg, std::vector<Vec3>& seeds, std::vector<Vec3>& not_seeds) { if (!cloud_seg.size() < n_lpr) { //Sort points in current segment by height std::sort(cloud_seg.begin(), cloud_seg.end(), CompareZ); Vec3 lpr; //Calc Lowest Point Representative (LPR) std::vector<Vec3>::iterator it; int i = 0; for (it = cloud_seg.begin(); it != cloud_seg.end(); it++, i++) { if (i == n_lpr) break; lpr.x += it->x; lpr.y += it->y; lpr.z += it->z; } lpr.x /= n_lpr; lpr.y /= n_lpr; lpr.z /= n_lpr; //Add point as initial seed if its dist to lpr is < th_seeds for (it = cloud_seg.begin(); it != cloud_seg.end(); it++) { if (it->z < this->th_seeds + lpr.z) { seeds.push_back(*it); } else { not_seeds.push_back(*it); } } } } /* Calculating Estimated Plane Normal: 1. Calculate the centroid of the points 2. Calculate the covariance matrix of the points relative to the centroid 3. Find the main axis (the component of the plane normal which will have the largest absolute value) and do simple linear regression along that axis */ Eigen::Vector4d PointCloudSegmenter::CalculatePlaneNormal(std::vector<Vec3>& cur_p_gnd) { double n = double(cur_p_gnd.size()); if (n < 3) { Eigen::Vector4d output(0,0,0,0); return output; } Vec3 centroid; std::vector<Vec3>::iterator it; for (it = cur_p_gnd.begin(); it != cur_p_gnd.end(); it++) { centroid.x += it->x; centroid.y += it->y; centroid.z += it->z; } centroid.x /= n; centroid.y /= n; centroid.z /= n; //Caclculate 3x3 covariance matrix, excluding symmitries double xx = 0.0, xy = 0.0, xz = 0.0, yy = 0.0, yz = 0.0, zz = 0.0; Vec3 r; for (it = cur_p_gnd.begin(); it != cur_p_gnd.end(); it++) { r.x = it->x - centroid.x; r.y = it->y - centroid.y; r.z = it->z - centroid.z; xx = r.x * r.x; xy = r.x * r.y; xz = r.x * r.z; yy = r.y * r.y; yz = r.y * r.z; zz = r.z * r.z; } xx /= n; xy /= n; xz /= n; yy /= n; yz /= n; zz /= n; double det_x = yy*zz - yz*yz; double det_y = xx*zz - xz*xz; double det_z = xx*yy - xy*xy; double max_det = std::max(det_x, std::max(det_y, det_z)); if (max_det < 0.0) { Eigen::Vector4d output(0.0,0.0,0.0,0.0); return output; } Vec3 axis_dir; if (max_det == det_x) { axis_dir.x = det_x; axis_dir.y = xz*yz - xy*zz; axis_dir.z = xy*yz - xz*yy; } else if (max_det == det_y) { axis_dir.x = xz*yz - xy*zz; axis_dir.y = det_y; axis_dir.z = xy*xz - yz*xx; } else { axis_dir.x = xy*yz - xz*yy; axis_dir.y = xy*xz - yz*xx; axis_dir.z = det_z; } double mag = std::sqrt(axis_dir.x * axis_dir.x + axis_dir.y * axis_dir.y + axis_dir.z * axis_dir.z); axis_dir.x /= mag; axis_dir.y /= mag; axis_dir.z /= mag; double min_thresh = 0.05; if ( std::abs(axis_dir.x) > min_thresh || std::abs(axis_dir.y) > min_thresh) { axis_dir.x = 0; axis_dir.y = 0; axis_dir.z = 1; } double d = -(axis_dir.x * centroid.x + axis_dir.y * centroid.y + axis_dir.z * centroid.z); Eigen::Vector4d output; output << axis_dir.x, axis_dir.y, axis_dir.z, d; return output; } //**************************************************************** SCAN LINE RUN ********************************************************************** /* Main Implementation of Scan Line Run: TODO: Properly identify scan lines, Change label implementation */ std::vector<Vec3> PointCloudSegmenter::ScanLineRun(std::vector<Vec3>& cloud) { int start_s = clock(); //Take start timestamp this->new_label = 0; this->next.push_back(-1); this->tail.push_back(this->new_label); this->rtable.push_back(this->new_label); std::vector<Scanline> scanlines; std::vector<Vec3>::iterator v_it; std::vector<Scanline>::iterator s_it; std::vector<int>::iterator r_it; int i; //Organize points into scanlines Scanline scanline; scanline.points = std::vector<Vec3>(); scanline.s_queue = std::vector<int>(); scanline.e_queue = std::vector<int>(); i = 0; for (v_it = cloud.begin(); v_it != cloud.end(); v_it++, i++) { int scan_index; //if (v_it->theta <= 2 && v_it->theta > -8.333) { scan_index = v_it->scanline; // } else if (v_it->theta <= -8.333 && v_it->theta >= -24.333 ) { // scan_index = 31 + (int)round(abs((v_it->theta + 8.333) / (0.5))); // } if (scan_index >= scanlines.size()) { scanlines.resize(scan_index + 1); scanlines.insert(scanlines.begin() + scan_index, scanline); } scanlines[scan_index].points.push_back(*v_it); } //Index scanlines by theta for (s_it = scanlines.begin(); s_it != scanlines.end(); s_it++) { if (s_it->points.size() == 0) { //(s_it - 1)->points.insert((s_it - 1)->points.end(), s_it->points.begin(), s_it->points.end()); scanlines.erase(s_it); s_it--; } else { std::sort(s_it->points.begin(), s_it->points.end(), CompareTheta); if (s_it->points.size() > 0) { ScanlinePointCloud * tree_point_cloud = new ScanlinePointCloud(s_it->points); ScanlineKDTree * tree = new ScanlineKDTree(3, *tree_point_cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10)); tree->buildIndex(); s_it->tree_point_cloud = tree_point_cloud; s_it->tree = tree; } } } //std::cout << "Num Scanlines: " << scanlines.size() << std::endl; //Assign inital labels Scanline* scan_above = &(scanlines[0]); Scanline* scan_current = nullptr; FindRuns(*scan_above); int start_index; int end_index; for (int i = 0; i < scan_above->s_queue.size(); i++) { start_index = scan_above->s_queue[i]; end_index = scan_above->e_queue[i]; SetRunLabel(*scan_above, start_index, end_index, this->new_label); this->new_label += 1; this->next.push_back(-1); this->tail.push_back(this->new_label); this->rtable.push_back(this->new_label); } //Find runs for all subsequent scanlines and propogate labels //std::vector<Scanline>::reverse_iterator rs_it; for (int i = 1; i < scanlines.size(); i++) { scan_current = &(scanlines[i]); FindRuns(*scan_current); UpdateLabels(*scan_current, *scan_above); scan_above = scan_current; } //Take end timestamp int stop_s = clock(); //std::cout << "SLR runtime: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000 << " ms" << std::endl; //Extract and return clusters return ExtractClusters(scanlines); } /* Find Runs: Find runs and add start and end indices to s_queue and e_queue respectively Take into account: ground points, edge cases TODO: Redo logic and make prettier */ void PointCloudSegmenter::FindRuns(Scanline& cur_scanline) { int i = 0; std::vector<Vec3>::iterator it; bool start_run = true; if (cur_scanline.points[0].label == -3 || cur_scanline.points.back().label == -3) { start_run = false; } while (cur_scanline.points[i].label == -3) { i++; } if (i < cur_scanline.points.size() ) { cur_scanline.s_queue.push_back(i); if (i == cur_scanline.points.size() - 1) { cur_scanline.e_queue.push_back(i); return; } ++i; } else { return; } for (; i < cur_scanline.points.size(); i++) { Vec3* cur_p = &cur_scanline.points[i]; Vec3* prev_p = &cur_scanline.points[i-1]; if (cur_p->label != -3) { if (prev_p->label == -3) { //Start new run if immediately after gnd pt if (i == cur_scanline.points.size() - 1) { if (start_run && (cur_scanline.points[i]).distance(cur_scanline.points[0]) < this->th_run) { cur_scanline.s_queue[0] = i; } else { cur_scanline.s_queue.push_back(i); cur_scanline.e_queue.push_back(i); } } else { cur_scanline.s_queue.push_back(i); } } else { //check distance to prev point if ( (cur_scanline.points[i]).distance(cur_scanline.points[i-1]) > this->th_run ) { cur_scanline.e_queue.push_back(i - 1); if (i == cur_scanline.points.size() - 1) { if (start_run && (cur_scanline.points[i]).distance(cur_scanline.points[0]) < this->th_run) { cur_scanline.s_queue[0] = i; } else { cur_scanline.s_queue.push_back(i); cur_scanline.e_queue.push_back(i); } } else { cur_scanline.s_queue.push_back(i); } } else { if (i == cur_scanline.points.size() - 1) { if (start_run && (cur_scanline.points[i]).distance(cur_scanline.points[0]) < this->th_run) { cur_scanline.s_queue[0] = cur_scanline.s_queue.back(); cur_scanline.s_queue.erase(cur_scanline.s_queue.end() - 1); } else { cur_scanline.e_queue.push_back(i); } } } } } else { //Current point is ground & previous point is not //then end that run if (prev_p->label != -3) { cur_scanline.e_queue.push_back(i-1); } } } } /* Update Labels: 1.Loop through all runs 2.For each point in each run, find its nearest neigbor in the above scanline 3.If there are neigbors within th->merge: Pick the min label of the label candidates and merge all labels to that one Else: Set all labels in run to newlabel and increment newlabel */ void PointCloudSegmenter::UpdateLabels(Scanline &scan_current, Scanline &scan_above) { std::vector<int> labels_to_merge; std::vector<int>::iterator i_it; int start_index; int end_index; if (scan_current.s_queue.size() != scan_current.e_queue.size()) { std::cout << "Start & End: " << scan_current.s_queue.size() << " " << scan_current.e_queue.size() << std::endl; return; } for (int i = 0; i < scan_current.s_queue.size(); i++) { start_index = scan_current.s_queue[i]; end_index = scan_current.e_queue[i]; if (start_index > end_index) { for (int k = start_index; k < scan_current.points.size(); k++) { if (scan_current.points[k].label != -3) { int nearest_label = FindNearestNeighbor(scan_current, scan_above, k); if (nearest_label != -1 && std::find(labels_to_merge.begin(), labels_to_merge.end(), nearest_label) == labels_to_merge.end()) { labels_to_merge.push_back( nearest_label ); } } } for (int k = 0; k <= end_index; k++) { if (scan_current.points[k].label != -3) { int nearest_label = FindNearestNeighbor(scan_current, scan_above, k); if (nearest_label != -1 && std::find(labels_to_merge.begin(), labels_to_merge.end(), nearest_label) == labels_to_merge.end()) { labels_to_merge.push_back( nearest_label ); } } } } else { for (int k = start_index; k <= end_index; k++) { if (scan_current.points[k].label != -3) { int nearest_label = FindNearestNeighbor(scan_current, scan_above, k); if (nearest_label != -1 && std::find(labels_to_merge.begin(), labels_to_merge.end(), nearest_label) == labels_to_merge.end()) { labels_to_merge.push_back( nearest_label ); } } } } if (labels_to_merge.size() == 0) { SetRunLabel(scan_current, start_index, end_index, this->new_label); this->new_label += 1; this->next.push_back(-1); this->tail.push_back(this->new_label); this->rtable.push_back(this->new_label); } else { int min_label = *std::min_element(labels_to_merge.begin(), labels_to_merge.end());; SetRunLabel(scan_current, start_index, end_index, min_label); MergeLabels(labels_to_merge, min_label); } labels_to_merge.clear(); } } /* Merge all labels in the input array into the established min label */ void PointCloudSegmenter::MergeLabels(std::vector<int>& labels_to_merge, int min_label) { std::vector<int>::iterator it; for (int i = 0; i < labels_to_merge.size(); i++) { ResolveMerge(labels_to_merge[i], min_label); } } /* Handle merge cases of labels Note: if u == v, nothing happens */ void PointCloudSegmenter::ResolveMerge(int x, int y) { int u = this->rtable.at(x); int v = this->rtable.at(y); if (u < v) { MergeOperation(u, v); } else if (u > v) { MergeOperation(v, u); } } /* Merge label v into label u and update next, tail, and rtable accordingly. */ void PointCloudSegmenter::MergeOperation(int u, int v) { int i = v; while (i != -1) { this->rtable[i] = u; i = this->next[i]; } this->next[this->tail[u]] = v; this->tail[u] = this->tail[v]; } /* Update labels of points in a run. TODO: Make array of run labels to coincide with s_queue and e_queue to reduce vector accesses. */ void PointCloudSegmenter::SetRunLabel(Scanline &scan_current, int start_index, int end_index, int set_label) { int k; if (start_index <= end_index) { for (k = start_index; k <= end_index; k++) { scan_current.points[k].label = set_label; } } else { for (k = start_index; k < scan_current.points.size(); k++) { scan_current.points[k].label = set_label; } for (k = 0; k <= end_index; k++) { scan_current.points[k].label = set_label; } } } /* Given a point, find its nearest neigbor in the above scanline and return its label. TODO: Implement smart indexing and kdtree */ int PointCloudSegmenter::FindNearestNeighbor(Scanline& scan_current, Scanline& scan_above, int point_index) { //double conversion_factor = scan_above.points.size() / scan_current.points.size(); //int above_start = floor(start_index * conversion_factor); //int above_end = floor(end_index * conversion_factor); // Determine nearest point to search at Vec3 current = scan_current.points[point_index]; float query[3] = {current.x, current.y, current.z}; // Set up KNN result set size_t result_index; float result_dist_squared; nanoflann::KNNResultSet<float> results(1); results.init(&result_index, &result_dist_squared); // Perform search scan_above.tree->findNeighbors(results, &query[0], nanoflann::SearchParams(10)); if (result_dist_squared < this->th_merge * this->th_merge) { return scan_above.tree_point_cloud->get_label(result_index); } return -1; } //Perform label updating by looking up current labels in rtable //Group points into clusters std::vector<Vec3> PointCloudSegmenter::ExtractClusters( std::vector<Scanline>& scanlines ) { std::vector<Scanline>::iterator s_it; std::vector<Vec3>::iterator v_it; std::vector<Vec3> out_points; int i = 0; for (s_it = scanlines.begin(); s_it != scanlines.end(); s_it++, i++ ) { for (v_it = s_it->points.begin(); v_it != s_it->points.end(); v_it++) { if (v_it->label < this->rtable.size() && v_it->label != -3) { v_it->label = this->rtable[v_it->label]; out_points.push_back(*v_it); } } } return out_points; }
28.704036
151
0.597094
[ "vector" ]
39536c20095f88f290c4099541c4413a8fd77a7f
10,034
cpp
C++
src/lib/data/Image.cpp
kaifeichen/MARVEL
87d6aa0bb126f739450529069cb5cdf42c66c3fd
[ "Unlicense" ]
5
2018-01-23T21:55:08.000Z
2021-02-07T00:56:40.000Z
src/lib/data/Image.cpp
kaifeichen/MARVEL
87d6aa0bb126f739450529069cb5cdf42c66c3fd
[ "Unlicense" ]
null
null
null
src/lib/data/Image.cpp
kaifeichen/MARVEL
87d6aa0bb126f739450529069cb5cdf42c66c3fd
[ "Unlicense" ]
2
2018-03-26T09:03:21.000Z
2021-02-07T00:56:58.000Z
#include "lib/data/Image.h" Image::Image(int id, int roomId, const cv::Mat &image, const cv::Mat &depth, const Transform &pose, const CameraModel &camera) : _id(id), _roomId(roomId), _image(image), _depth(depth), _pose(pose), _camera(camera) {} int Image::getId() const { return _id; } int Image::getRoomId() const { return _roomId; } const cv::Mat &Image::getImage() const { return _image; } const cv::Mat &Image::getDepth() const { return _depth; } const Transform &Image::getPose() const { return _pose; } const CameraModel &Image::getCameraModel() const { return _camera; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr Image::getCloud(int decimation) const { // generate a new pcl point cloud and return auto cloud = cloudFromDepthRGB(_image, _depth, _camera, decimation, 0, 0); std::vector<int> indices; pcl::removeNaNFromPointCloud(*cloud, *cloud, indices); return cloud; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr Image::cloudFromDepthRGB(const cv::Mat &imageRgb, const cv::Mat &imageDepthIn, const CameraModel &model, int decimation, float maxDepth, float minDepth) const { pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud( new pcl::PointCloud<pcl::PointXYZRGB>); if (decimation == 0) { decimation = 1; } if (decimation < 0) { if (imageRgb.rows % decimation != 0 || imageRgb.cols % decimation != 0) { int oldDecimation = decimation; while (decimation <= -1) { if (imageRgb.rows % decimation == 0 && imageRgb.cols % decimation == 0) { break; } ++decimation; } if (imageRgb.rows % oldDecimation != 0 || imageRgb.cols % oldDecimation != 0) { std::cerr << "Decimation " << oldDecimation << " is not valid for current image size (rgb=" << imageRgb.cols << " x " << imageRgb.rows << ". Highest compatible decimation used=" << decimation; } } } else { if (imageDepthIn.rows % decimation != 0 || imageDepthIn.cols % decimation != 0) { int oldDecimation = decimation; while (decimation >= 1) { if (imageDepthIn.rows % decimation == 0 && imageDepthIn.cols % decimation == 0) { break; } --decimation; } if (imageDepthIn.rows % oldDecimation != 0 || imageDepthIn.cols % oldDecimation != 0) { std::cerr << "Decimation " << oldDecimation << " is not valid for current image size (rgb=" << imageRgb.cols << " x " << imageRgb.rows << ". Highest compatible decimation used=" << decimation; } } } cv::Mat imageDepth = imageDepthIn; bool mono; if (imageRgb.channels() == 3) // BGR { mono = false; } else if (imageRgb.channels() == 1) // Mono { mono = true; } else { return cloud; } // cloud.header = cameraInfo.header; cloud->height = imageDepth.rows / decimation; cloud->width = imageDepth.cols / decimation; cloud->is_dense = false; cloud->resize(cloud->height * cloud->width); float rgbToDepthFactorX = static_cast<float>(imageRgb.cols) / static_cast<float>(imageDepth.cols); float rgbToDepthFactorY = static_cast<float>(imageRgb.rows) / static_cast<float>(imageDepth.rows); float depthFx = model.fx() / rgbToDepthFactorX; float depthFy = model.fy() / rgbToDepthFactorY; float depthCx = model.cx() / rgbToDepthFactorX; float depthCy = model.cy() / rgbToDepthFactorY; int oi = 0; for (int h = 0; h < imageDepth.rows && h / decimation < (int)cloud->height; h += decimation) { for (int w = 0; w < imageDepth.cols && w / decimation < (int)cloud->width; w += decimation) { pcl::PointXYZRGB &pt = cloud->at((h / decimation) * cloud->width + (w / decimation)); int x = static_cast<int>(w * rgbToDepthFactorX); int y = static_cast<int>(h * rgbToDepthFactorY); assert(x >= 0 && x < imageRgb.cols && y >= 0 && y < imageRgb.rows); if (!mono) { const unsigned char *bgr = imageRgb.ptr<unsigned char>(y, x); pt.b = bgr[0]; pt.g = bgr[1]; pt.r = bgr[2]; } else { unsigned char v = imageRgb.at<unsigned char>(y, x); pt.b = v; pt.g = v; pt.r = v; } pcl::PointXYZ ptXYZ = projectDepthTo3D(imageDepth, w, h, depthCx, depthCy, depthFx, depthFy, false, 0.02f); if (pcl::isFinite(ptXYZ) && ptXYZ.z >= minDepth && (maxDepth <= 0.0f || ptXYZ.z <= maxDepth)) { pt.x = ptXYZ.x; pt.y = ptXYZ.y; pt.z = ptXYZ.z; ++oi; } else { pt.x = pt.y = pt.z = std::numeric_limits<float>::quiet_NaN(); } } } if (oi == 0) { std::cerr << "Cloud with only NaN values created!\n"; } return cloud; } float Image::getDepth(const cv::Mat &depthImage, float x, float y, bool smoothing, float maxZError, bool estWithNeighborsIfNull) const { assert(!depthImage.empty()); assert(depthImage.type() == CV_16UC1 || depthImage.type() == CV_32FC1); int u = static_cast<int>(x + 0.5f); int v = static_cast<int>(y + 0.5f); if (u == depthImage.cols && x < static_cast<float>(depthImage.cols)) { u = depthImage.cols - 1; } if (v == depthImage.rows && y < static_cast<float>(depthImage.rows)) { v = depthImage.rows - 1; } if (!(u >= 0 && u < depthImage.cols && v >= 0 && v < depthImage.rows)) { fprintf(stderr, "!(x >=0 && x<depthImage.cols && y >=0 && " "y<depthImage.rows) cond failed! returning bad point. " "(x=%f (u=%d), y=%f (v=%d), cols=%d, rows=%d)", x, u, y, v, depthImage.cols, depthImage.rows); return 0; } bool isInMM = depthImage.type() == CV_16UC1; // is in mm? // Inspired from RGBDFrame::getGaussianMixtureDistribution() method from // https://github.com/ccny-ros-pkg/rgbdtools/blob/master/src/rgbd_frame.cpp // Window weights: // | 1 | 2 | 1 | // | 2 | 4 | 2 | // | 1 | 2 | 1 | int u_start = std::max(u - 1, 0); int v_start = std::max(v - 1, 0); int u_end = std::min(u + 1, depthImage.cols - 1); int v_end = std::min(v + 1, depthImage.rows - 1); float depth = 0.0f; if (isInMM) { if (depthImage.at<unsigned short>(v, u) > 0 && depthImage.at<unsigned short>(v, u) < std::numeric_limits<unsigned short>::max()) { depth = static_cast<float>(depthImage.at<unsigned short>(v, u)) * 0.001f; } } else { depth = depthImage.at<float>(v, u); } if ((depth == 0.0f || !std::isfinite(depth)) && estWithNeighborsIfNull) { // all cells no2 must be under the zError to be accepted float tmp = 0.0f; int count = 0; for (int uu = u_start; uu <= u_end; ++uu) { for (int vv = v_start; vv <= v_end; ++vv) { if ((uu == u && vv != v) || (uu != u && vv == v)) { float d = 0.0f; if (isInMM) { if (depthImage.at<unsigned short>(vv, uu) > 0 && depthImage.at<unsigned short>(vv, uu) < std::numeric_limits<unsigned short>::max()) { d = static_cast<float>(depthImage.at<unsigned short>(vv, uu)) * 0.001f; } } else { d = depthImage.at<float>(vv, uu); } if (d != 0.0f && std::isfinite(d)) { if (tmp == 0.0f) { tmp = d; ++count; } else if (fabs(d - tmp / static_cast<float>(count)) < maxZError) { tmp += d; ++count; } } } } } if (count > 1) { depth = tmp / static_cast<float>(count); } } if (depth != 0.0f && std::isfinite(depth)) { if (smoothing) { float sumWeights = 0.0f; float sumDepths = 0.0f; for (int uu = u_start; uu <= u_end; ++uu) { for (int vv = v_start; vv <= v_end; ++vv) { if (!(uu == u && vv == v)) { float d = 0.0f; if (isInMM) { if (depthImage.at<unsigned short>(vv, uu) > 0 && depthImage.at<unsigned short>(vv, uu) < std::numeric_limits<unsigned short>::max()) { d = static_cast<float>(depthImage.at<unsigned short>(vv, uu)) * 0.001f; } } else { d = depthImage.at<float>(vv, uu); } // ignore if not valid or depth difference is too high if (d != 0.0f && std::isfinite(d) && fabs(d - depth) < maxZError) { if (uu == u || vv == v) { sumWeights += 2.0f; d *= 2.0f; } else { sumWeights += 1.0f; } sumDepths += d; } } } } // set window weight to center point depth *= 4.0f; sumWeights += 4.0f; // mean depth = (depth + sumDepths) / sumWeights; } } else { depth = 0; } return depth; } pcl::PointXYZ Image::projectDepthTo3D(const cv::Mat &depthImage, float x, float y, float cx, float cy, float fx, float fy, bool smoothing, float maxZError) const { pcl::PointXYZ pt; float depth = getDepth(depthImage, x, y, smoothing, maxZError, false); if (depth > 0.0f) { // Use correct principal point from calibration cx = cx > 0.0f ? cx : static_cast<float>(depthImage.cols / 2) - 0.5f; // cameraInfo.K.at(2) cy = cy > 0.0f ? cy : static_cast<float>(depthImage.rows / 2) - 0.5f; // cameraInfo.K.at(5) // Fill in XYZ pt.x = (x - cx) * depth / fx; pt.y = (y - cy) * depth / fy; pt.z = depth; } else { pt.x = pt.y = pt.z = std::numeric_limits<float>::quiet_NaN(); } return pt; }
33.446667
80
0.529201
[ "vector", "model", "transform" ]
3956ceb3a1a58036b444c8bd3772b57f2d809e7a
51,485
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/3ds/ReaderWriter3DS.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/3ds/ReaderWriter3DS.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/3ds/ReaderWriter3DS.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
#include <osg/Notify> #include <osg/Group> #include <osg/Geode> #include <osg/Geometry> #include <osg/Texture2D> #include <osg/Material> #include <osg/TexEnv> #include <osg/ref_ptr> #include <osg/MatrixTransform> #include <osg/BlendFunc> #include <osg/TexEnvCombine> #include <osgDB/Registry> #include <osgDB/FileUtils> #include <osgDB/FileNameUtils> #include <osgDB/ReadFile> #include <osgUtil/TriStripVisitor> //MIKEC debug only for PrintVisitor #include <osg/NodeVisitor> #include "WriterNodeVisitor.h" #include "lib3ds/lib3ds.h" #include <stdlib.h> #include <string.h> #include <set> #include <map> #include <iostream> #include <sstream> #include <assert.h> using namespace std; using namespace osg; /// Implementation borrowed from boost and slightly modified template<class T> class scoped_array // noncopyable { private: T * px; scoped_array(scoped_array const &); scoped_array & operator=(scoped_array const &); typedef scoped_array<T> this_type; void operator==( scoped_array const& ) const; void operator!=( scoped_array const& ) const; public: typedef T element_type; explicit scoped_array( T * p = 0 ) : px( p ) {} ~scoped_array() { delete[] px; } void reset(T * p = 0) { assert( p == 0 || p != px ); // catch self-reset errors this_type(p).swap(*this); } T & operator[](std::ptrdiff_t i) const // never throws { assert( px != 0 ); assert( i >= 0 ); return px[i]; } T * get() const // never throws { return px; } void swap(scoped_array & b) // never throws { T * tmp = b.px; b.px = px; px = tmp; } }; void copyLib3dsMatrixToOsgMatrix(osg::Matrix& osg_matrix, const Lib3dsMatrix lib3ds_matrix) { osg_matrix.set( lib3ds_matrix[0][0],lib3ds_matrix[0][1],lib3ds_matrix[0][2],lib3ds_matrix[0][3], lib3ds_matrix[1][0],lib3ds_matrix[1][1],lib3ds_matrix[1][2],lib3ds_matrix[1][3], lib3ds_matrix[2][0],lib3ds_matrix[2][1],lib3ds_matrix[2][2],lib3ds_matrix[2][3], lib3ds_matrix[3][0],lib3ds_matrix[3][1],lib3ds_matrix[3][2],lib3ds_matrix[3][3]); } osg::Matrix copyLib3dsMatrixToOsgMatrix(const Lib3dsMatrix mat) { osg::Matrix osgMatrix; copyLib3dsMatrixToOsgMatrix(osgMatrix, mat); return osgMatrix; } void copyLib3dsVec3ToOsgVec3(osg::Vec3f osgVec, const float vertices[3]) { return osgVec.set(vertices[0], vertices[1], vertices[2]); } osg::Vec3f copyLib3dsVec3ToOsgVec3(const float vertices[3]) { return osg::Vec3f(vertices[0], vertices[1], vertices[2]); } osg::Quat copyLib3dsQuatToOsgQuat(const float quat[4]) { return osg::Quat(quat[0], quat[1], quat[2], quat[3]); } class PrintVisitor : public NodeVisitor { public: PrintVisitor(std::ostream& out): NodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN), _out(out) { _indent = 0; _step = 4; } inline void moveIn() { _indent += _step; } inline void moveOut() { _indent -= _step; } inline void writeIndent() { for(int i=0;i<_indent;++i) _out << " "; } virtual void apply(Node& node) { moveIn(); writeIndent(); _out << node.className() <<std::endl; traverse(node); moveOut(); } virtual void apply(Geode& node) { apply((Node&)node); } virtual void apply(Billboard& node) { apply((Geode&)node); } virtual void apply(LightSource& node) { apply((Group&)node); } virtual void apply(ClipNode& node) { apply((Group&)node); } virtual void apply(Group& node) { apply((Node&)node); } virtual void apply(Transform& node) { apply((Group&)node); } virtual void apply(Projection& node) { apply((Group&)node); } virtual void apply(Switch& node) { apply((Group&)node); } virtual void apply(LOD& node) { apply((Group&)node); } protected: PrintVisitor& operator = (const PrintVisitor&) { return *this; } std::ostream& _out; int _indent; int _step; }; /// Possible options: /// - noMatrixTransforms: set the plugin to apply matrices into the mesh vertices ("old behaviour") instead of restoring them ("new behaviour"). You may use this option to avoid a few rounding errors. /// - checkForEspilonIdentityMatrices: if noMatrixTransforms is \b not set, then consider "almost identity" matrices to be identity ones (in case of rounding errors). /// - restoreMatrixTransformsNoMeshes: makes an exception to the behaviour when 'noMatrixTransforms' is \b not set for mesh instances. When a mesh instance has a transform on it, the reader creates a MatrixTransform above the Geode. If you don't want the hierarchy to be modified, then you can use this option to merge the transform into vertices. class ReaderWriter3DS : public osgDB::ReaderWriter { public: ReaderWriter3DS(); virtual const char* className() const { return "3DS Auto Studio Reader/Writer"; } virtual ReadResult readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const; virtual ReadResult readNode(std::istream& fin, const Options* options) const; virtual ReadResult doReadNode(std::istream& fin, const Options* options, const std::string & fileNamelib3ds) const; ///< Subfunction of readNode()s functions. virtual WriteResult writeNode(const osg::Node& /*node*/,const std::string& /*fileName*/,const Options* =NULL) const; virtual WriteResult writeNode(const osg::Node& /*node*/,std::ostream& /*fout*/,const Options* =NULL) const; virtual WriteResult doWriteNode(const osg::Node& /*node*/,std::ostream& /*fout*/,const Options*, const std::string & fileNamelib3ds) const; protected: ReadResult constructFrom3dsFile(Lib3dsFile *f,const std::string& filename, const Options* options) const; bool createFileObject(const osg::Node& node, Lib3dsFile * file3ds,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const; /// An OSG state set with the original 3DS material attached (used to get info such as UV scaling & offset) struct StateSetInfo { StateSetInfo(osg::StateSet * stateset=NULL, Lib3dsMaterial * lib3dsmat=NULL) : stateset(stateset), lib3dsmat(lib3dsmat) {} StateSetInfo(const StateSetInfo & v) : stateset(v.stateset), lib3dsmat(v.lib3dsmat) {} StateSetInfo & operator=(const StateSetInfo & v) { stateset=v.stateset; lib3dsmat=v.lib3dsmat; return *this; } osg::StateSet * stateset; Lib3dsMaterial * lib3dsmat; }; class ReaderObject { public: ReaderObject(const osgDB::ReaderWriter::Options* options); typedef std::vector<StateSetInfo> StateSetMap; typedef std::vector<int> FaceList; typedef std::map<std::string,osg::StateSet*> GeoStateMap; osg::Texture2D* createTexture(Lib3dsTextureMap *texture,const char* label,bool& transparancy); StateSetInfo createStateSet(Lib3dsMaterial *materials); osg::Drawable* createDrawable(Lib3dsMesh *meshes,FaceList& faceList, const osg::Matrix * matrix, StateSetInfo & ssi); std::string _directory; bool _useSmoothingGroups; bool _usePerVertexNormals; // MIKEC osg::Node* processMesh(StateSetMap& drawStateMap,osg::Group* parent,Lib3dsMesh* mesh, const osg::Matrix * matrix); osg::Node* processNode(StateSetMap& drawStateMap,Lib3dsFile *f,Lib3dsNode *node); private: const osgDB::ReaderWriter::Options* options; bool noMatrixTransforms; ///< Should the plugin apply matrices into the mesh vertices ("old behaviour"), instead of restoring matrices ("new behaviour")? bool checkForEspilonIdentityMatrices; bool restoreMatrixTransformsNoMeshes; typedef std::map<unsigned int,FaceList> SmoothingFaceMap; void addDrawableFromFace(osg::Geode * geode, FaceList & faceList, Lib3dsMesh * mesh, const osg::Matrix * matrix, StateSetInfo & ssi); typedef std::map<std::string, osg::ref_ptr<osg::Texture2D> > TexturesMap; // Should be an unordered map (faster) TexturesMap texturesMap; }; }; // now register with Registry to instantiate the above // reader/writer. REGISTER_OSGPLUGIN(3ds, ReaderWriter3DS) ReaderWriter3DS::ReaderWriter3DS() { supportsExtension("3ds","3D Studio model format"); //supportsOption("OutputTextureFiles","Write out the texture images to file"); //supportsOption("flipTexture", "flip texture upside-down"); supportsOption("extended3dsFilePaths", "(Write option) Keeps long texture filenames (not 8.3) when exporting 3DS, but can lead to compatibility problems."); supportsOption("noMatrixTransforms", "(Read option) Set the plugin to apply matrices into the mesh vertices (\"old behaviour\") instead of restoring them (\"new behaviour\"). You may use this option to avoid a few rounding errors."); supportsOption("checkForEspilonIdentityMatrices", "(Read option) If not set, then consider \"almost identity\" matrices to be identity ones (in case of rounding errors)."); supportsOption("restoreMatrixTransformsNoMeshes", "(Read option) Makes an exception to the behaviour when 'noMatrixTransforms' is not set for mesh instances. When a mesh instance has a transform on it, the reader creates a MatrixTransform above the Geode. If you don't want the hierarchy to be modified, then you can use this option to merge the transform into vertices."); #if 0 OSG_NOTICE<<"3DS reader sizes:"<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsBool)="<<sizeof(Lib3dsBool)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsByte)="<<sizeof(Lib3dsByte)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsWord)="<<sizeof(Lib3dsWord)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsDword)="<<sizeof(Lib3dsDword)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsIntb)="<<sizeof(Lib3dsIntb)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsIntw)="<<sizeof(Lib3dsIntw)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsIntd)="<<sizeof(Lib3dsIntd)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsFloat)="<<sizeof(Lib3dsFloat)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsDouble)="<<sizeof(Lib3dsDouble)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsVector)="<<sizeof(Lib3dsVector)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsTexel)="<<sizeof(Lib3dsTexel)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsQuat)="<<sizeof(Lib3dsQuat)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsMatrix)="<<sizeof(Lib3dsMatrix)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsRgb)="<<sizeof(Lib3dsRgb)<<std::endl; OSG_NOTICE<<" sizeof(Lib3dsRgba)="<<sizeof(Lib3dsRgba)<<std::endl; #endif } ReaderWriter3DS::ReaderObject::ReaderObject(const osgDB::ReaderWriter::Options* options) : _useSmoothingGroups(true), _usePerVertexNormals(true), options(options), noMatrixTransforms(false), checkForEspilonIdentityMatrices(false), restoreMatrixTransformsNoMeshes(false) { if (options) { std::istringstream iss(options->getOptionString()); std::string opt; while (iss >> opt) { if (opt == "noMatrixTransforms") noMatrixTransforms = true; else if (opt == "checkForEspilonIdentityMatrices") checkForEspilonIdentityMatrices = true; else if (opt == "restoreMatrixTransformsNoMeshes") restoreMatrixTransformsNoMeshes = true; } } } /** These print methods for 3ds hacking */ void pad(int level) { for(int i=0;i<level;i++) std::cout<<" "; } void print(Lib3dsMesh *mesh,int level); void print(Lib3dsUserData *user,int level); void print(Lib3dsMeshInstanceNode *object,int level); void print(Lib3dsNode *node, int level); void print(Lib3dsMatrix matrix,int level) { pad(level); cout << matrix[0][0] <<" "<< matrix[0][1] <<" "<< matrix[0][2] <<" "<< matrix[0][3] << endl; pad(level); cout << matrix[1][0] <<" "<< matrix[1][1] <<" "<< matrix[1][2] <<" "<< matrix[1][3] << endl; pad(level); cout << matrix[2][0] <<" "<< matrix[2][1] <<" "<< matrix[2][2] <<" "<< matrix[2][3] << endl; pad(level); cout << matrix[3][0] <<" "<< matrix[3][1] <<" "<< matrix[3][2] <<" "<< matrix[3][3] << endl; } void print(Lib3dsMesh *mesh,int level) { if (mesh) { pad(level); cout << "mesh name " << mesh->name << endl; print(mesh->matrix,level); } else { pad(level); cout << "no mesh " << endl; } } void print(Lib3dsUserData *user,int level) { if (user) { pad(level); cout << "user data" << endl; //print(user->mesh,level+1); } else { pad(level); cout << "no user data" << endl; } } void print(Lib3dsMeshInstanceNode *object,int level) { if (object) { pad(level); cout << "objectdata instance [" << object->instance_name << "]" << endl; pad(level); cout << "pivot " << object->pivot[0] <<" "<< object->pivot[1] <<" "<< object->pivot[2] << endl; pad(level); cout << "pos " << object->pos[0] <<" "<< object->pos[1] <<" "<< object->pos[2] << endl; pad(level); cout << "scl " << object->scl[0] <<" "<< object->scl[1] <<" "<< object->scl[2] << endl; pad(level); cout << "rot " << object->rot[0] <<" "<< object->rot[1] <<" "<< object->rot[2] <<" "<< object->rot[3] << endl; } else { pad(level); cout << "no object data" << endl; } } void print(Lib3dsNode *node, int level) { pad(level); cout << "node name [" << node->name << "]" << endl; pad(level); cout << "node id " << node->user_id << endl; pad(level); cout << "node parent id " << (node->parent ? static_cast<int>(node->parent->user_id) : -1) << endl; pad(level); cout << "node matrix:" << endl; print(node->matrix,level+1); if (node->type == LIB3DS_NODE_MESH_INSTANCE) { pad(level); cout << "mesh instance data:" << endl; print(reinterpret_cast<Lib3dsMeshInstanceNode *>(node),level+1); } else { pad(level); cout << "node is not a mesh instance (not handled)" << endl; } print(&node->user_ptr,level); for(Lib3dsNode *child=node->childs; child; child=child->next) { print(child,level+1); } } void ReaderWriter3DS::ReaderObject::addDrawableFromFace(osg::Geode * geode, FaceList & faceList, Lib3dsMesh * mesh, const osg::Matrix * matrix, StateSetInfo & ssi) { if (_useSmoothingGroups) { SmoothingFaceMap smoothingFaceMap; for (FaceList::iterator flitr=faceList.begin(); flitr!=faceList.end(); ++flitr) { smoothingFaceMap[mesh->faces[*flitr].smoothing_group].push_back(*flitr); } for(SmoothingFaceMap::iterator sitr=smoothingFaceMap.begin(); sitr!=smoothingFaceMap.end(); ++sitr) { // each smoothing group to have its own geom // to ensure the vertices on adjacent groups // don't get shared. FaceList& smoothFaceMap = sitr->second; osg::ref_ptr<osg::Drawable> drawable = createDrawable(mesh,smoothFaceMap,matrix,ssi); if (drawable.valid()) { if (ssi.stateset) drawable->setStateSet(ssi.stateset); geode->addDrawable(drawable.get()); } } } else // ignore smoothing groups. { osg::ref_ptr<osg::Drawable> drawable = createDrawable(mesh,faceList,matrix,ssi); if (drawable.valid()) { if (ssi.stateset) drawable->setStateSet(ssi.stateset); geode->addDrawable(drawable.get()); } } } // Transforms points by matrix if 'matrix' is not NULL // Creates a Geode and Geometry (as parent,child) and adds the Geode to 'parent' parameter iff 'parent' is non-NULL // Returns ptr to the Geode osg::Node* ReaderWriter3DS::ReaderObject::processMesh(StateSetMap& drawStateMap,osg::Group* parent,Lib3dsMesh* mesh, const osg::Matrix * matrix) { typedef std::vector<FaceList> MaterialFaceMap; MaterialFaceMap materialFaceMap; unsigned int numMaterials = drawStateMap.size(); materialFaceMap.insert(materialFaceMap.begin(), numMaterials, FaceList()); // Setup the map FaceList defaultMaterialFaceList; for (unsigned int i=0; i<mesh->nfaces; ++i) { if (mesh->faces[i].material>=0) { materialFaceMap[mesh->faces[i].material].push_back(i); } else { defaultMaterialFaceList.push_back(i); } } if (materialFaceMap.empty() && defaultMaterialFaceList.empty()) { OSG_NOTICE<<"Warning : no triangles assigned to mesh '"<<mesh->name<<"'"<< std::endl; //OSG_INFO << "No material assigned to mesh '" << mesh->name << "'" << std::endl; return NULL; } else { osg::Geode* geode = new osg::Geode; geode->setName(mesh->name); if (!defaultMaterialFaceList.empty()) { StateSetInfo emptySSI; addDrawableFromFace(geode, defaultMaterialFaceList, mesh, matrix, emptySSI); } for(unsigned int imat=0; imat<numMaterials; ++imat) { addDrawableFromFace(geode, materialFaceMap[imat], mesh, matrix, drawStateMap[imat]); } if (parent) parent->addChild(geode); return geode; } } /// Returns true if a matrix is 'almost' identity, meaning that the difference between each value and the corresponding identity value is less than an epsilon value. bool isIdentityEquivalent(const osg::Matrix & mat, osg::Matrix::value_type epsilon=1e-6) { return osg::equivalent(mat(0,0), 1, epsilon) && osg::equivalent(mat(0,1), 0, epsilon) && osg::equivalent(mat(0,2), 0, epsilon) && osg::equivalent(mat(0,3), 0, epsilon) && osg::equivalent(mat(1,0), 0, epsilon) && osg::equivalent(mat(1,1), 1, epsilon) && osg::equivalent(mat(1,2), 0, epsilon) && osg::equivalent(mat(1,3), 0, epsilon) && osg::equivalent(mat(2,0), 0, epsilon) && osg::equivalent(mat(2,1), 0, epsilon) && osg::equivalent(mat(2,2), 1, epsilon) && osg::equivalent(mat(2,3), 0, epsilon) && osg::equivalent(mat(3,0), 0, epsilon) && osg::equivalent(mat(3,1), 0, epsilon) && osg::equivalent(mat(3,2), 0, epsilon) && osg::equivalent(mat(3,3), 1, epsilon); } /** How to cope with pivot points in 3ds (short version) All object coordinates in 3ds are stored in world space, this is why you can just rip out the meshes and use/draw them without meddeling further Unfortunately, this gets a bit wonky with objects with pivot points (conjecture: PP support is retro fitted into the .3ds format and so doesn't fit perfectly?) Objects with pivot points have a position relative to their PP, so they have to undergo this transform: invert the mesh matrix, apply this matrix to the object. This puts the object back at the origin Transform the object by the nodes (negative) pivot point coords, this puts the PP at the origin Transform the node by the node matrix, which does the orientation about the pivot point, (and currently) transforms the object back by a translation to the PP. */ osg::Node* ReaderWriter3DS::ReaderObject::processNode(StateSetMap& drawStateMap,Lib3dsFile *f,Lib3dsNode *node) { // Get mesh Lib3dsMeshInstanceNode * object = (node->type == LIB3DS_NODE_MESH_INSTANCE) ? reinterpret_cast<Lib3dsMeshInstanceNode *>(node) : NULL; Lib3dsMesh * mesh = lib3ds_file_mesh_for_node(f,node); assert(!(mesh && !object)); // Node must be a LIB3DS_NODE_MESH_INSTANCE if a mesh exists // Retreive LOCAL transform static const osg::Matrix::value_type MATRIX_EPSILON = 1e-10; osg::Matrix osgWorldToNodeMatrix( copyLib3dsMatrixToOsgMatrix(node->matrix) ); osg::Matrix osgWorldToParentNodeMatrix; if (node->parent) { // Matrices evaluated by lib3DS are multiplied by parents' ones osgWorldToParentNodeMatrix = copyLib3dsMatrixToOsgMatrix(node->parent->matrix); } osg::Matrix osgNodeMatrix( osgWorldToNodeMatrix * osg::Matrix::inverse(osgWorldToParentNodeMatrix) ); // Test if we should create an intermediate Group (or MatrixTransform) and which matrix we should apply to the vertices osg::Group* group = NULL; // Get pivot point osg::Vec3 pivot( object ? copyLib3dsVec3ToOsgVec3(object->pivot) : osg::Vec3() ); bool pivoted = pivot.x()!=0 || pivot.y()!=0 || pivot.z()!=0; osg::Matrix meshMat; if (mesh) { if (!noMatrixTransforms) { // There can be a transform directly on a mesh instance (= as if a osg::MatrixTransform and a osg::Geode were merged together) in object->pos/rot/scl if (pivoted) { meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * osg::Matrix::translate(-pivot); } else { meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)); } } else { if (pivoted) { meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * osg::Matrix::translate(-pivot) * osgWorldToNodeMatrix; } else { meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * osgWorldToNodeMatrix; // ==Identity when not pivoted? } osgNodeMatrix = osg::Matrix::identity(); // Not sure it's useful, but it's harmless ;) } } bool isOsgNodeMatrixIdentity = false; if (osgNodeMatrix.isIdentity() || (checkForEspilonIdentityMatrices && isIdentityEquivalent(osgNodeMatrix, MATRIX_EPSILON))) { isOsgNodeMatrixIdentity = true; } //if (node->childs != NULL || pivoted || (!isOsgNodeMatrixIdentity && !noMatrixTransforms)) if (node->childs != NULL || (!isOsgNodeMatrixIdentity && !noMatrixTransforms)) { if (isOsgNodeMatrixIdentity || noMatrixTransforms) { group = new osg::Group; } else { group = new osg::MatrixTransform(osgNodeMatrix); } } if (group) { if (strcmp(node->name, "$$$DUMMY") == 0) { if (node->type == LIB3DS_NODE_MESH_INSTANCE) group->setName(reinterpret_cast<Lib3dsMeshInstanceNode *>(node)->instance_name); } else if (node->type == LIB3DS_NODE_MESH_INSTANCE && strlen(reinterpret_cast<Lib3dsMeshInstanceNode *>(node)->instance_name) != 0) group->setName(reinterpret_cast<Lib3dsMeshInstanceNode *>(node)->instance_name); else group->setName(node->name); // Handle all children of this node for hierarchical assemblies for (Lib3dsNode *p=node->childs; p!=NULL; p=p->next) { group->addChild(processNode(drawStateMap,f,p)); } } else { assert(node->childs == NULL); // Else we must have a group to put childs into } // Handle mesh if (mesh) { osg::Matrix * meshAppliedMatPtr = NULL; if (!meshMat.isIdentity() && !(checkForEspilonIdentityMatrices && isIdentityEquivalent(meshMat, MATRIX_EPSILON))) { meshAppliedMatPtr = &meshMat; } if (group) { // add our geometry to group (where our children already are) // creates geometry under modifier node processMesh(drawStateMap,group,mesh,meshAppliedMatPtr); return group; } else { // didnt use group for children // return a ptr directly to the Geode for this mesh return processMesh(drawStateMap,NULL,mesh,meshAppliedMatPtr); } } else { // no mesh for this node - probably a camera or something of that persuasion //cout << "no mesh for object " << node->name << endl; return group; // we have no mesh, but we might have children } } static long filei_seek_func(void *self, long offset, Lib3dsIoSeek origin) { std::istream *f = reinterpret_cast<std::istream*>(self); ios_base::seekdir o = ios_base::beg; if (origin == LIB3DS_SEEK_CUR) o = ios_base::cur; else if (origin == LIB3DS_SEEK_END) o = ios_base::end; f->seekg(offset, o); return f->fail() ? -1 : 0; } static long fileo_seek_func(void *self, long offset, Lib3dsIoSeek origin) { std::ostream *f = reinterpret_cast<std::ostream*>(self); ios_base::seekdir o = ios_base::beg; if (origin == LIB3DS_SEEK_CUR) o = ios_base::cur; else if (origin == LIB3DS_SEEK_END) o = ios_base::end; f->seekp(offset, o); return f->fail() ? -1 : 0; } static long filei_tell_func(void *self) { std::istream *f = reinterpret_cast<std::istream*>(self); return f->tellg(); } static long fileo_tell_func(void *self) { std::ostream *f = reinterpret_cast<std::ostream*>(self); return f->tellp(); } static size_t filei_read_func(void *self, void *buffer, size_t size) { std::istream *f = reinterpret_cast<std::istream*>(self); f->read(reinterpret_cast<char*>(buffer), size); return f->gcount(); } static size_t fileo_write_func(void *self, const void *buffer, size_t size) { std::ostream *f = reinterpret_cast<std::ostream*>(self); f->write(static_cast<const char*>(buffer), size); return f->fail() ? 0 : size; } static void fileio_log_func(void *self, Lib3dsLogLevel level, int indent, const char *msg) { osg::NotifySeverity l = osg::INFO; // Intentionally NOT mapping 3DS levels with OSG levels if (level == LIB3DS_LOG_ERROR) l = osg::WARN; else if (level == LIB3DS_LOG_WARN) l = osg::NOTICE; else if (level == LIB3DS_LOG_INFO) l = osg::INFO; else if (level == LIB3DS_LOG_DEBUG) l = osg::DEBUG_INFO; OSG_NOTIFY(l) << msg << std::endl; } osgDB::ReaderWriter::ReadResult ReaderWriter3DS::readNode(std::istream& fin, const osgDB::ReaderWriter::Options* options) const { std::string optFileName; if (options) { optFileName = options->getPluginStringData("STREAM_FILENAME"); if (optFileName.empty()) optFileName = options->getPluginStringData("filename"); } return doReadNode(fin, options, optFileName); } osgDB::ReaderWriter::ReadResult ReaderWriter3DS::doReadNode(std::istream& fin, const osgDB::ReaderWriter::Options* options, const std::string & fileNamelib3ds) const { osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options; local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileNamelib3ds)); osgDB::ReaderWriter::ReadResult result = ReadResult::FILE_NOT_HANDLED; // Prepare io structure to tell how to read the stream Lib3dsIo io; io.self = &fin; io.seek_func = filei_seek_func; io.tell_func = filei_tell_func; io.read_func = filei_read_func; io.write_func = NULL; io.log_func = fileio_log_func; Lib3dsFile * file3ds = lib3ds_file_new(); if (lib3ds_file_read(file3ds, &io) != 0) { result = constructFrom3dsFile(file3ds,fileNamelib3ds,options); lib3ds_file_free(file3ds); } return(result); } osgDB::ReaderWriter::ReadResult ReaderWriter3DS::readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; // Do not use the lib3ds_file_open() as: // 1. It relies on FILE* instead of iostreams (less safe) // 2. It doesn't allow us to set a custom log output osgDB::ifstream fin(fileName.c_str(), std::ios_base::in | std::ios_base::binary); if (!fin.good()) return ReadResult::ERROR_IN_READING_FILE; return doReadNode(fin, options, fileName); /* osgDB::ReaderWriter::ReadResult result = ReadResult::FILE_NOT_HANDLED; Lib3dsFile *f = lib3ds_file_open(fileName.c_str()); // ,options if (f) { osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options; local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName)); result = constructFrom3dsFile(f,file,local_opt.get()); lib3ds_file_free(f); } return result; */ } osgDB::ReaderWriter::ReadResult ReaderWriter3DS::constructFrom3dsFile(Lib3dsFile *f,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const { if (f==NULL) return ReadResult::FILE_NOT_HANDLED; // MIKEC // This appears to build the matrix structures for the 3ds structure // It wasn't previously necessary because all the meshes are stored in world coordinates // but is VERY necessary if you want to use pivot points... lib3ds_file_eval(f,0.0f); // second param is time 't' for animated files ReaderObject reader(options); reader._directory = ( options && !options->getDatabasePathList().empty() ) ? options->getDatabasePathList().front() : osgDB::getFilePath(fileName); ReaderObject::StateSetMap drawStateMap; unsigned int numMaterials = f->nmaterials; drawStateMap.insert(drawStateMap.begin(), numMaterials, StateSetInfo()); // Setup the map for (unsigned int imat=0; imat<numMaterials; ++imat) { Lib3dsMaterial * mat = f->materials[imat]; drawStateMap[imat] = reader.createStateSet(mat); } if (osg::getNotifyLevel()>=osg::INFO) { int level=0; std::cout << "NODE TRAVERSAL of 3ds file "<<f->name<<std::endl; for(Lib3dsNode *node=f->nodes; node; node=node->next) { print(node,level+1); } std::cout << "MESH TRAVERSAL of 3ds file "<<f->name<<std::endl; for (int imesh=0; imesh<f->nmeshes; ++imesh){ print(f->meshes[imesh],level+1); } } // We can traverse by meshes (old method, broken for pivot points, but otherwise works), or by nodes (new method, not so well tested yet) // if your model is broken, especially wrt object positions try setting this flag. If that fixes it, // send me the model bool traverse_nodes=false; // MIKEC: have found 3ds files with NO node structure - only meshes, for this case we fall back to the old traverse-by-meshes code // Loading and re-exporting these files from 3DS produces a file with correct node structure, so perhaps these are not 100% conformant? if (f->nodes == NULL) { OSG_WARN<<"Warning: in 3ds loader: file has no nodes, traversing by meshes instead"<< std::endl; traverse_nodes=true; } osg::Node* group = NULL; if (traverse_nodes) // old method { group = new osg::Group(); for (int imesh=0; imesh<f->nmeshes; ++imesh) { reader.processMesh(drawStateMap,group->asGroup(),f->meshes[imesh],NULL); } } else { // new method Lib3dsNode *node=f->nodes; if (!node->next) { group = reader.processNode(drawStateMap,f,node); } else { group = new osg::Group(); for(; node; node=node->next) { group->asGroup()->addChild(reader.processNode(drawStateMap,f,node)); } } } if (group && group->getName().empty()) group->setName(fileName); if (osg::getNotifyLevel()>=osg::INFO) { OSG_INFO << "Final OSG node structure looks like this:"<< endl; PrintVisitor pv(osg::notify(osg::INFO)); group->accept(pv); } return group; } /** use matrix to pretransform geometry, or NULL to do nothing */ osg::Drawable* ReaderWriter3DS::ReaderObject::createDrawable(Lib3dsMesh *m,FaceList& faceList, const osg::Matrix * matrix, StateSetInfo & ssi) { osg::Geometry * geom = new osg::Geometry; unsigned int i; std::vector<int> orig2NewMapping; orig2NewMapping.reserve(m->nvertices); for(i=0;i<m->nvertices;++i) orig2NewMapping.push_back(-1); unsigned int noVertex=0; FaceList::iterator fitr; for (fitr=faceList.begin(); fitr!=faceList.end(); ++fitr) { Lib3dsFace& face = m->faces[*fitr]; if (orig2NewMapping[face.index[0]]<0) orig2NewMapping[face.index[0]] = noVertex++; if (orig2NewMapping[face.index[1]]<0) orig2NewMapping[face.index[1]] = noVertex++; if (orig2NewMapping[face.index[2]]<0) orig2NewMapping[face.index[2]] = noVertex++; } // create vertices. osg::ref_ptr<osg::Vec3Array> osg_coords = new osg::Vec3Array(noVertex); geom->setVertexArray(osg_coords.get()); for (i=0; i<m->nvertices; ++i) { if (orig2NewMapping[i]>=0) { if (matrix) { (*osg_coords)[orig2NewMapping[i]].set( copyLib3dsVec3ToOsgVec3(m->vertices[i]) * (*matrix) ); } else { // original no transform code. (*osg_coords)[orig2NewMapping[i]].set( copyLib3dsVec3ToOsgVec3(m->vertices[i]) ); } } } // create texture coords if needed. if (m->texcos) { osg::ref_ptr<osg::Vec2Array> osg_tcoords = new osg::Vec2Array(noVertex); geom->setTexCoordArray(0, osg_tcoords.get()); // Texture 0 parameters (only one texture supported for now) float scaleU(1.f), scaleV(1.f); float offsetU(0.f), offsetV(0.f); if (ssi.lib3dsmat && *(ssi.lib3dsmat->texture1_map.name)) // valid texture = name not empty { Lib3dsTextureMap & tex3ds = ssi.lib3dsmat->texture1_map; scaleU = tex3ds.scale[0]; scaleV = tex3ds.scale[1]; offsetU = tex3ds.offset[0]; offsetV = tex3ds.offset[1]; if (tex3ds.rotation != 0) OSG_NOTICE << "3DS texture rotation not supported yet" << std::endl; //TODO: tint_1, tint_2, tint_r, tint_g, tint_b } for (i=0; i<m->nvertices; ++i) { if (orig2NewMapping[i]>=0) (*osg_tcoords)[orig2NewMapping[i]].set(m->texcos[i][0]*scaleU + offsetU, m->texcos[i][1]*scaleV + offsetV); } } // create normals // Sukender: 3DS file format doesn't store normals (that is to say they're recomputed each time). // When using per vertex normals, we could use either vertex computation, or face computation (and copy the normal to each vertex). Here we use the latter one. if (_usePerVertexNormals) { //Lib3dsVector * normals = new Lib3dsVector[m->nfaces*3]; //lib3ds_mesh_calculate_vertex_normals(m, normals); scoped_array<Lib3dsVector> normals( new Lib3dsVector[m->nfaces] ); // Temporary array lib3ds_mesh_calculate_face_normals(m, normals.get()); osg::ref_ptr<osg::Vec3Array> osg_normals = new osg::Vec3Array(noVertex); // initialize normal list to zero's. for (i=0; i<noVertex; ++i) { (*osg_normals)[i].set(0.0f,0.0f,0.0f); } for (fitr=faceList.begin(); fitr!=faceList.end(); ++fitr) { Lib3dsFace& face = m->faces[*fitr]; osg::Vec3f osgNormal( copyLib3dsVec3ToOsgVec3(normals[*fitr]) ); if (matrix) osgNormal = osg::Matrix::transform3x3(osgNormal, *matrix); osgNormal.normalize(); (*osg_normals)[orig2NewMapping[face.index[0]]] = osgNormal; (*osg_normals)[orig2NewMapping[face.index[1]]] = osgNormal; (*osg_normals)[orig2NewMapping[face.index[2]]] = osgNormal; } geom->setNormalArray(osg_normals.get()); geom->setNormalBinding(osg::Geometry::BIND_PER_VERTEX); } else { scoped_array<Lib3dsVector> normals ( new Lib3dsVector[m->nfaces] ); lib3ds_mesh_calculate_face_normals(m, normals.get()); osg::ref_ptr<osg::Vec3Array> osg_normals = new osg::Vec3Array(faceList.size()); osg::Vec3Array::iterator normal_itr = osg_normals->begin(); for (fitr=faceList.begin(); fitr!=faceList.end(); ++fitr) { osg::Vec3f osgNormal( copyLib3dsVec3ToOsgVec3(normals[*fitr]) ); if (matrix) osgNormal = osg::Matrix::transform3x3(osgNormal, *matrix); osgNormal.normalize(); *(normal_itr++) = osgNormal; } geom->setNormalArray(osg_normals.get()); geom->setNormalBinding(osg::Geometry::BIND_PER_PRIMITIVE); } osg::ref_ptr<osg::Vec4ubArray> osg_colors = new osg::Vec4ubArray(1); (*osg_colors)[0].set(255,255,255,255); geom->setColorArray(osg_colors.get()); geom->setColorBinding(osg::Geometry::BIND_OVERALL); // create primitives int numIndices = faceList.size()*3; osg::ref_ptr<DrawElementsUShort> elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES,numIndices); DrawElementsUShort::iterator index_itr = elements->begin(); for (fitr=faceList.begin(); fitr!=faceList.end(); ++fitr) { Lib3dsFace& face = m->faces[*fitr]; *(index_itr++) = orig2NewMapping[face.index[0]]; *(index_itr++) = orig2NewMapping[face.index[1]]; *(index_itr++) = orig2NewMapping[face.index[2]]; } geom->addPrimitiveSet(elements.get()); #if 0 osgUtil::TriStripVisitor tsv; tsv.stripify(*geom); #endif return geom; } osg::Texture2D* ReaderWriter3DS::ReaderObject::createTexture(Lib3dsTextureMap *texture,const char* label,bool& transparency) { if (texture && *(texture->name)) { OSG_INFO<<"texture->name="<<texture->name<<", _directory="<<_directory<<std::endl; // First try already loaded textures. TexturesMap::iterator itTex = texturesMap.find(texture->name); if (itTex != texturesMap.end()) { OSG_DEBUG << "Texture '" << texture->name << "' found in cache." << std::endl; return itTex->second.get(); } // Texture not in cache: locate and load. std::string fileName = osgDB::findFileInDirectory(texture->name,_directory,osgDB::CASE_INSENSITIVE); if (fileName.empty()) { // file not found in .3ds file's directory, so we'll look in the datafile path list. fileName = osgDB::findDataFile(texture->name,options, osgDB::CASE_INSENSITIVE); OSG_INFO<<"texture->name="<<texture->name<<", _directory="<<_directory<<std::endl; } if (fileName.empty()) { if (osgDB::containsServerAddress(_directory)) { // if 3DS file is loaded from http, just attempt to load texture from same location. fileName = _directory + "/" + texture->name; } else { OSG_WARN << "texture '"<<texture->name<<"' not found"<< std::endl; return NULL; } } if (label) { OSG_DEBUG << label; } else { OSG_DEBUG << "texture name"; } OSG_DEBUG << " '"<<texture->name<<"'"<< std::endl; OSG_DEBUG << " texture flag "<<texture->flags<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_DECALE "<<((texture->flags)&LIB3DS_TEXTURE_DECALE)<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_MIRROR "<<((texture->flags)&LIB3DS_TEXTURE_MIRROR)<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_NEGATE "<<((texture->flags)&LIB3DS_TEXTURE_NEGATE)<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_NO_TILE "<<((texture->flags)&LIB3DS_TEXTURE_NO_TILE)<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_SUMMED_AREA "<<((texture->flags)&LIB3DS_TEXTURE_SUMMED_AREA)<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_ALPHA_SOURCE "<<((texture->flags)&LIB3DS_TEXTURE_ALPHA_SOURCE)<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_TINT "<<((texture->flags)&LIB3DS_TEXTURE_TINT)<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_IGNORE_ALPHA "<<((texture->flags)&LIB3DS_TEXTURE_IGNORE_ALPHA)<< std::endl; OSG_DEBUG << " LIB3DS_TEXTURE_RGB_TINT "<<((texture->flags)&LIB3DS_TEXTURE_RGB_TINT)<< std::endl; osg::ref_ptr<osg::Image> osg_image = osgDB::readRefImageFile(fileName.c_str(), options); //Absolute Path if (!osg_image.valid()) { OSG_NOTICE << "Warning: Cannot create texture "<<texture->name<< std::endl; return NULL; } if (osg_image->getFileName().empty()) // it should be done in OSG with osgDB::readRefImageFile(fileName.c_str()); osg_image->setFileName(fileName); osg::Texture2D* osg_texture = new osg::Texture2D; osg_texture->setImage(osg_image.get()); osg_texture->setName(texture->name); // does the texture support transparancy? //transparency = ((texture->flags)&LIB3DS_TEXTURE_ALPHA_SOURCE)!=0; // what is the wrap mode of the texture. osg::Texture2D::WrapMode wm = ((texture->flags)&LIB3DS_TEXTURE_NO_TILE) ? osg::Texture2D::CLAMP : osg::Texture2D::REPEAT; osg_texture->setWrap(osg::Texture2D::WRAP_S,wm); osg_texture->setWrap(osg::Texture2D::WRAP_T,wm); osg_texture->setWrap(osg::Texture2D::WRAP_R,wm); // bilinear. osg_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR_MIPMAP_NEAREST); // Insert in cache map texturesMap.insert(TexturesMap::value_type(texture->name, osg_texture)); return osg_texture; } else return NULL; } ReaderWriter3DS::StateSetInfo ReaderWriter3DS::ReaderObject::createStateSet(Lib3dsMaterial *mat) { if (mat==NULL) return StateSetInfo(); bool textureTransparency=false; bool transparency = false; float alpha = 1.0f - mat->transparency; int unit = 0; osg::StateSet* stateset = new osg::StateSet; osg::Material* material = new osg::Material; osg::Vec3 ambient(mat->ambient[0],mat->ambient[1],mat->ambient[2]); osg::Vec3 diffuse(mat->diffuse[0],mat->diffuse[1],mat->diffuse[2]); osg::Vec3 specular(mat->specular[0],mat->specular[1],mat->specular[2]); specular *= mat->shin_strength; float shininess = mat->shininess*128.0f; // diffuse osg::Texture2D* texture1_map = createTexture(&(mat->texture1_map),"texture1_map",textureTransparency); if (texture1_map) { stateset->setTextureAttributeAndModes(unit, texture1_map, osg::StateAttribute::ON); double factor = mat->texture1_map.percent; if(factor < 1.0) { osg::TexEnvCombine* texenv = new osg::TexEnvCombine(); texenv->setCombine_RGB(osg::TexEnvCombine::MODULATE); texenv->setSource0_RGB(osg::TexEnvCombine::TEXTURE); texenv->setSource1_RGB(osg::TexEnvCombine::PREVIOUS); texenv->setSource2_RGB(osg::TexEnvCombine::CONSTANT); texenv->setConstantColor(osg::Vec4(factor, factor, factor, factor)); stateset->setTextureAttributeAndModes(unit, texenv, osg::StateAttribute::ON); } else { // from an email from Eric Hamil, September 30, 2003. // According to the 3DS spec, and other // software (like Max, Lightwave, and Deep Exploration) a 3DS material that has // a non-white diffuse base color and a 100% opaque bitmap texture, will show the // texture with no influence from the base color. // so we'll override material back to white. // and no longer require the decal hack below... #if 0 // Eric original fallback osg::Vec4 white(1.0f,1.0f,1.0f,alpha); material->setAmbient(osg::Material::FRONT_AND_BACK,white); material->setDiffuse(osg::Material::FRONT_AND_BACK,white); material->setSpecular(osg::Material::FRONT_AND_BACK,white); #else // try alternative to avoid saturating with white // setting white as per OpenGL defaults. ambient.set(0.2f,0.2f,0.2f); diffuse.set(0.8f,0.8f,0.8f); specular.set(0.0f,0.0f,0.0f); #endif } unit++; } // opacity osg::Texture* opacity_map = createTexture(&(mat->opacity_map),"opacity_map", textureTransparency); if (opacity_map) { if(texture1_map->getImage()->isImageTranslucent()) { transparency = true; stateset->setTextureAttributeAndModes(unit, opacity_map, osg::StateAttribute::ON); double factor = mat->opacity_map.percent; osg::TexEnvCombine* texenv = new osg::TexEnvCombine(); texenv->setCombine_Alpha(osg::TexEnvCombine::INTERPOLATE); texenv->setSource0_Alpha(osg::TexEnvCombine::TEXTURE); texenv->setSource1_Alpha(osg::TexEnvCombine::PREVIOUS); texenv->setSource2_Alpha(osg::TexEnvCombine::CONSTANT); texenv->setConstantColor(osg::Vec4(factor, factor, factor, 1.0 - factor)); stateset->setTextureAttributeAndModes(unit, texenv, osg::StateAttribute::ON); unit++; } else { osg::notify(WARN)<<"The plugin does not support images without alpha channel for opacity"<<std::endl; } } // material material->setName(mat->name); material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(ambient, alpha)); material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(diffuse, alpha)); material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(specular, alpha)); material->setShininess(osg::Material::FRONT_AND_BACK, shininess); stateset->setAttribute(material); if ((alpha < 1.0f) || transparency) { //stateset->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); stateset->setMode(GL_BLEND,osg::StateAttribute::ON); stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); } /* osg::ref_ptr<osg::Texture> texture1_mask = createTexture(&(mat->texture1_mask),"texture1_mask",textureTransparancy); osg::ref_ptr<osg::Texture> texture2_map = createTexture(&(mat->texture2_map),"texture2_map",textureTransparancy); osg::ref_ptr<osg::Texture> texture2_mask = createTexture(&(mat->texture2_mask),"texture2_mask",textureTransparancy); osg::ref_ptr<osg::Texture> opacity_map = createTexture(&(mat->opacity_map),"opacity_map",textureTransparancy); osg::ref_ptr<osg::Texture> opacity_mask = createTexture(&(mat->opacity_mask),"opacity_mask",textureTransparancy); osg::ref_ptr<osg::Texture> bump_map = createTexture(&(mat->bump_map),"bump_map",textureTransparancy); osg::ref_ptr<osg::Texture> bump_mask = createTexture(&(mat->bump_mask),"bump_mask",textureTransparancy); osg::ref_ptr<osg::Texture> specular_map = createTexture(&(mat->specular_map),"specular_map",textureTransparancy); osg::ref_ptr<osg::Texture> specular_mask = createTexture(&(mat->specular_mask),"specular_mask",textureTransparancy); osg::ref_ptr<osg::Texture> shininess_map = createTexture(&(mat->shininess_map),"shininess_map",textureTransparancy); osg::ref_ptr<osg::Texture> shininess_mask = createTexture(&(mat->shininess_mask),"shininess_mask",textureTransparancy); osg::ref_ptr<osg::Texture> self_illum_map = createTexture(&(mat->self_illum_map),"self_illum_map",textureTransparancy); osg::ref_ptr<osg::Texture> self_illum_mask = createTexture(&(mat->self_illum_mask),"self_illum_mask",textureTransparancy); osg::ref_ptr<osg::Texture> reflection_map = createTexture(&(mat->reflection_map),"reflection_map",textureTransparancy); osg::ref_ptr<osg::Texture> reflection_mask = createTexture(&(mat->reflection_mask),"reflection_mask",textureTransparancy); */ return StateSetInfo(stateset, mat); } osgDB::ReaderWriter::WriteResult ReaderWriter3DS::writeNode(const osg::Node& node,const std::string& fileName,const Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(fileName); if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; osgDB::makeDirectoryForFile(fileName.c_str()); osgDB::ofstream fout(fileName.c_str(), std::ios_base::out | std::ios_base::binary); if (!fout.good()) return WriteResult::ERROR_IN_WRITING_FILE; return doWriteNode(node, fout, options, fileName); /* bool ok = true; Lib3dsFile * file3ds = lib3ds_file_new(); if (!file3ds) return WriteResult(WriteResult::ERROR_IN_WRITING_FILE); osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options; local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName)); if (!createFileObject(node, file3ds, fileName, local_opt)) ok = false; if (ok && !lib3ds_file_save(file3ds, fileName.c_str())) ok = false; lib3ds_file_free(file3ds); return ok ? WriteResult(WriteResult::FILE_SAVED) : WriteResult(WriteResult::ERROR_IN_WRITING_FILE); */ } osgDB::ReaderWriter::WriteResult ReaderWriter3DS::writeNode(const osg::Node& node,std::ostream& fout,const Options* options) const { //OSG_WARN << "!!WARNING!! 3DS write support is incomplete" << std::endl; std::string optFileName; if (options) { optFileName = options->getPluginStringData("STREAM_FILENAME"); } return doWriteNode(node, fout, options, optFileName); } osgDB::ReaderWriter::WriteResult ReaderWriter3DS::doWriteNode(const osg::Node& node,std::ostream& fout, const Options* options, const std::string & fileNamelib3ds) const { osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options; local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileNamelib3ds)); Lib3dsIo io; io.self = &fout; io.seek_func = fileo_seek_func; io.tell_func = fileo_tell_func; io.read_func = NULL; io.write_func = fileo_write_func; io.log_func = fileio_log_func; Lib3dsFile * file3ds = lib3ds_file_new(); if (!file3ds) return WriteResult(WriteResult::ERROR_IN_WRITING_FILE); bool ok = true; if (!createFileObject(node, file3ds, fileNamelib3ds, local_opt.get())) ok = false; if (ok && !lib3ds_file_write(file3ds, &io)) ok = false; lib3ds_file_free(file3ds); return ok ? WriteResult(WriteResult::FILE_SAVED) : WriteResult(WriteResult::ERROR_IN_WRITING_FILE); //return ok ? WriteResult(WriteResult::FILE_SAVED) : WriteResult(WriteResult::FILE_NOT_HANDLED); } bool ReaderWriter3DS::createFileObject(const osg::Node& node, Lib3dsFile * file3ds,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const { plugin3ds::WriterNodeVisitor w(file3ds, fileName, options, osgDB::getFilePath(node.getName())); const_cast<osg::Node &>(node).accept(w); // Ugly const_cast<> for visitor... if (!w.succeeded()) return false; w.writeMaterials(); return w.succeeded(); }
40.285603
377
0.643372
[ "mesh", "geometry", "object", "vector", "model", "transform", "3d" ]
39601cb2f7e0648d45a71ca1a245c7a42bdf4b68
2,209
hpp
C++
remodet_repository_wdh_part/include/caffe/mask/visual_mask_layer.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/include/caffe/mask/visual_mask_layer.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/include/caffe/mask/visual_mask_layer.hpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
#ifndef CAFFE_VISUAL_MASK_LAYER_HPP_ #define CAFFE_VISUAL_MASK_LAYER_HPP_ #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/mask/bbox_func.hpp" namespace caffe { /** * 该层作为Mask的可视化层,它提供了如下方法: * 1.可视化实例的boxes * 2.可视化实例的关节点 * 3.可视化实例的Mask */ template <typename Dtype> class VisualMaskLayer : public Layer<Dtype> { public: explicit VisualMaskLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "VisualMask"; } /** * bottom[0]: -> image data (1,3,H,W) * bottom[1]: -> ROIs (1,1,Nroi,7) * bottom[2]: -> mask/kps (Nroi,1/18,RH,RW) * bottom[3]: -> kps[optional] (Nroi,18,RH,RW) * 注意: * (1)如果只可视化mask, bottom[3]不存在 * (2)如果只可视化kps,bottom[3]不存在 * (3)如果同时可视化mask/kps, bottom[2]->mask and bottom[3]->kps * (4)如果不需要可视化mask/kps,则bottom[2]/[3]均不存在 */ virtual inline int MinBottomBlobs() const { return 2; } virtual inline int MaxBottomBlobs() const { return 4; } /** * top[0] -> (1) ignored. */ virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } /** * 将Blob数据转换为cv::Mat (unsigned char型)数据 * @param image [数据指针] * @param w [image宽度] * @param h [image高度] * @param out [输出unsigned char型数据] */ void cv_inv(const Dtype* image, const int w, const int h, unsigned char* out); // 获取时间 (us) double get_wall_time(); // 关节点的置信度阈值 Dtype kps_threshold_; // mask置信度阈值 Dtype mask_threshold_; // 是否保存视频帧 bool write_frames_; // 如果保存,指定输出路径 string output_directory_; // 是否显示mask bool show_mask_; // 是否显示kps bool show_kps_; // 是否显示box置信度信息 bool print_score_; // 可视化最大尺寸 int max_dis_size_; }; } #endif
24.544444
80
0.663196
[ "vector" ]
3962bf1e4e743e18a79ee370d7ccaff23b37240b
9,935
cpp
C++
src/cryptographic/sha1.cpp
namralkeeg/QHashlib
5b4fdb33833b6b0a1856c87a6d4696371aecfe59
[ "MIT" ]
null
null
null
src/cryptographic/sha1.cpp
namralkeeg/QHashlib
5b4fdb33833b6b0a1856c87a6d4696371aecfe59
[ "MIT" ]
null
null
null
src/cryptographic/sha1.cpp
namralkeeg/QHashlib
5b4fdb33833b6b0a1856c87a6d4696371aecfe59
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017 Larry Lopez * * 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 <cryptographic/sha1.hpp> #include <endian.hpp> #include <algorithm> //#include <iterator> namespace QHashlib { namespace cryptographic { namespace { #ifndef ROTATELEFT_M #define ROTATELEFT_M(x,y) QHashlib::rotateLeft((x),(y)) #endif // mix functions for processBlock() inline uint32_t f1(uint32_t b, uint32_t c, uint32_t d) { return d ^ (b & (c ^ d)); // original: f = (b & c) | ((~b) & d); } inline uint32_t f2(uint32_t b, uint32_t c, uint32_t d) { return b ^ c ^ d; } inline uint32_t f3(uint32_t b, uint32_t c, uint32_t d) { return (b & c) | (b & d) | (c & d); } } // anonymous namespace Sha1::Sha1() { initialize(); } QByteArray Sha1::hashFinal() { // save old hash if buffer is partially filled std::array<quint32, NUM_HASH_VALUES> oldHash{m_hash}; // for (quint32 i = 0; i < NUM_HASH_VALUES; i++) // oldHash[i] = m_hash[i]; // process remaining bytes processBuffer(); QByteArray qba; qba.reserve(m_hashSize/std::numeric_limits<quint8>::digits); // const char* bytes = reinterpret_cast<const char*>(&m_hash[0]); // QByteArray qba = QByteArray(bytes, m_hashSize / std::numeric_limits<quint8>::digits); for (quint32 i = 0; i < NUM_HASH_VALUES; i++) { // qba.append(QByteArray::number(m_hash[i])); qba.append(static_cast<char>((m_hash[i] >> 24) & 0xFF)); qba.append(static_cast<char>((m_hash[i] >> 16) & 0xFF)); qba.append(static_cast<char>((m_hash[i] >> 8) & 0xFF)); qba.append(static_cast<char>( m_hash[i] & 0xFF)); // const char * bytes = reinterpret_cast<const char*>(&m_hash[i]); // qba.append(bytes, sizeof(quint32)); } // TODO: Validate code to transform m_hash to a QByteArray // for (const auto &hash: m_hash) // qba.append(QByteArray::number(hash)); // restore old hash m_hash = oldHash; return qba; } quint32 Sha1::hashSize() { return m_hashSize; } void Sha1::initialize() { m_hashValue.clear(); m_numBytes = 0; m_bufferSize = 0; // according to RFC 1321 m_hash[0] = UINT32_C(0x67452301); m_hash[1] = UINT32_C(0xefcdab89); m_hash[2] = UINT32_C(0x98badcfe); m_hash[3] = UINT32_C(0x10325476); m_hash[4] = UINT32_C(0xc3d2e1f0); } void Sha1::hashCore(const void *data, const quint64 &dataLength, const quint64 &startIndex) { const quint8* current = static_cast<const quint8*>(data) + startIndex; quint64 numBytes = dataLength; if (m_bufferSize > 0) { while (numBytes > 0 && m_bufferSize < BLOCK_SIZE) { m_buffer[m_bufferSize++] = *current++; numBytes--; } } // full buffer if (m_bufferSize == BLOCK_SIZE) { processBlock(m_buffer.data()); m_numBytes += BLOCK_SIZE; m_bufferSize = 0; } // no more data ? if (numBytes == 0) return; // process full blocks while (numBytes >= BLOCK_SIZE) { processBlock(current); current += BLOCK_SIZE; m_numBytes += BLOCK_SIZE; numBytes -= BLOCK_SIZE; } // keep remaining bytes in buffer while (numBytes > 0) { m_buffer[m_bufferSize++] = *current++; numBytes--; } } void Sha1::processBlock(const void *data) { // get last hash quint32 a = m_hash[0]; quint32 b = m_hash[1]; quint32 c = m_hash[2]; quint32 d = m_hash[3]; quint32 e = m_hash[4]; // data represented as 16x 32-bit words const quint32* input = static_cast<const quint32*>(data); // convert to big endian std::array<quint32, 80> words; #if defined(Q_BYTE_ORDER) && (Q_BYTE_ORDER != 0) && (Q_BYTE_ORDER == Q_BIG_ENDIAN) std::copy(input, input + 16, std::begin(words)); #else // convert to big endian std::transform(input, input + 16, std::begin(words), [](const quint32 &b) -> quint32 { return QHashlib::swap(b); }); #endif // extend to 80 words for (int i = 16; i < 80; i++) words[i] = ROTATELEFT_M(words[i-3] ^ words[i-8] ^ words[i-14] ^ words[i-16], 1); // first round for (int i = 0; i < 4; i++) { int offset = 5*i; e += ROTATELEFT_M(a,5) + f1(b,c,d) + words[offset ] + 0x5a827999; b = ROTATELEFT_M(b,30); d += ROTATELEFT_M(e,5) + f1(a,b,c) + words[offset+1] + 0x5a827999; a = ROTATELEFT_M(a,30); c += ROTATELEFT_M(d,5) + f1(e,a,b) + words[offset+2] + 0x5a827999; e = ROTATELEFT_M(e,30); b += ROTATELEFT_M(c,5) + f1(d,e,a) + words[offset+3] + 0x5a827999; d = ROTATELEFT_M(d,30); a += ROTATELEFT_M(b,5) + f1(c,d,e) + words[offset+4] + 0x5a827999; c = ROTATELEFT_M(c,30); } // second round for (int i = 4; i < 8; i++) { int offset = 5*i; e += ROTATELEFT_M(a,5) + f2(b,c,d) + words[offset ] + 0x6ed9eba1; b = ROTATELEFT_M(b,30); d += ROTATELEFT_M(e,5) + f2(a,b,c) + words[offset+1] + 0x6ed9eba1; a = ROTATELEFT_M(a,30); c += ROTATELEFT_M(d,5) + f2(e,a,b) + words[offset+2] + 0x6ed9eba1; e = ROTATELEFT_M(e,30); b += ROTATELEFT_M(c,5) + f2(d,e,a) + words[offset+3] + 0x6ed9eba1; d = ROTATELEFT_M(d,30); a += ROTATELEFT_M(b,5) + f2(c,d,e) + words[offset+4] + 0x6ed9eba1; c = ROTATELEFT_M(c,30); } // third round for (int i = 8; i < 12; i++) { int offset = 5*i; e += ROTATELEFT_M(a,5) + f3(b,c,d) + words[offset ] + 0x8f1bbcdc; b = ROTATELEFT_M(b,30); d += ROTATELEFT_M(e,5) + f3(a,b,c) + words[offset+1] + 0x8f1bbcdc; a = ROTATELEFT_M(a,30); c += ROTATELEFT_M(d,5) + f3(e,a,b) + words[offset+2] + 0x8f1bbcdc; e = ROTATELEFT_M(e,30); b += ROTATELEFT_M(c,5) + f3(d,e,a) + words[offset+3] + 0x8f1bbcdc; d = ROTATELEFT_M(d,30); a += ROTATELEFT_M(b,5) + f3(c,d,e) + words[offset+4] + 0x8f1bbcdc; c = ROTATELEFT_M(c,30); } // fourth round for (int i = 12; i < 16; i++) { int offset = 5*i; e += ROTATELEFT_M(a,5) + f2(b,c,d) + words[offset ] + 0xca62c1d6; b = ROTATELEFT_M(b,30); d += ROTATELEFT_M(e,5) + f2(a,b,c) + words[offset+1] + 0xca62c1d6; a = ROTATELEFT_M(a,30); c += ROTATELEFT_M(d,5) + f2(e,a,b) + words[offset+2] + 0xca62c1d6; e = ROTATELEFT_M(e,30); b += ROTATELEFT_M(c,5) + f2(d,e,a) + words[offset+3] + 0xca62c1d6; d = ROTATELEFT_M(d,30); a += ROTATELEFT_M(b,5) + f2(c,d,e) + words[offset+4] + 0xca62c1d6; c = ROTATELEFT_M(c,30); } // update hash m_hash[0] += a; m_hash[1] += b; m_hash[2] += c; m_hash[3] += d; m_hash[4] += e; } void Sha1::processBuffer() { // the input bytes are considered as bits strings, where the first bit is the most significant bit of the byte // - append "1" bit to message // - append "0" bits until message length in bit mod 512 is 448 // - append length as 64 bit integer // number of bits quint64 paddedLength = m_bufferSize * 8; // plus one bit set to 1 (always appended) paddedLength++; // number of bits must be (numBits % 512) = 448 quint64 lower11Bits = paddedLength & 511; if (lower11Bits <= 448) paddedLength += 448 - lower11Bits; else paddedLength += 512 + 448 - lower11Bits; // convert from bits to bytes paddedLength /= 8; // only needed if additional data flows over into a second block std::array<quint8, BLOCK_SIZE> extra; // append a "1" bit, 128 => binary 10000000 if (m_bufferSize < BLOCK_SIZE) m_buffer[m_bufferSize] = 128; else extra[0] = 128; quint64 i; for (i = m_bufferSize + 1; i < BLOCK_SIZE; i++) m_buffer[i] = 0; for (; i < paddedLength; i++) extra[i - BLOCK_SIZE] = 0; // add message length in bits as 64 bit number quint64 msgBits = 8 * (m_numBytes + m_bufferSize); // find right position std::array<quint8, BLOCK_SIZE>::iterator addLength; if (paddedLength < BLOCK_SIZE) addLength = m_buffer.begin() + paddedLength; else addLength = extra.begin() + paddedLength - BLOCK_SIZE; // must be big endian *addLength++ = static_cast<quint8>((msgBits >> 56) & 0xFF); *addLength++ = static_cast<quint8>((msgBits >> 48) & 0xFF); *addLength++ = static_cast<quint8>((msgBits >> 40) & 0xFF); *addLength++ = static_cast<quint8>((msgBits >> 32) & 0xFF); *addLength++ = static_cast<quint8>((msgBits >> 24) & 0xFF); *addLength++ = static_cast<quint8>((msgBits >> 16) & 0xFF); *addLength++ = static_cast<quint8>((msgBits >> 8) & 0xFF); *addLength = static_cast<quint8>( msgBits & 0xFF); // process blocks processBlock(m_buffer.data()); // flowed over into a second block ? if (paddedLength > BLOCK_SIZE) processBlock(extra.data()); } } // namespace cryptographic } // namespace QHashlib
32.788779
114
0.611173
[ "transform" ]
3967d808ee28fee13bd73813892f955ca51c07eb
1,570
cpp
C++
library/computationalGeometry/convexFunctions.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
40
2017-11-26T05:29:18.000Z
2020-11-13T00:29:26.000Z
library/computationalGeometry/convexFunctions.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
101
2019-02-09T06:06:09.000Z
2021-12-25T16:55:37.000Z
library/computationalGeometry/convexFunctions.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
6
2017-01-03T14:17:58.000Z
2021-01-22T10:37:04.000Z
#include <cmath> #include <tuple> #include <functional> #include <vector> #include <algorithm> using namespace std; #include "convexFunctions.h" #include "../math/ternarySearch3D.h" /////////// For Testing /////////////////////////////////////////////////////// #include <time.h> #include <cassert> #include <string> #include <iostream> #include "../common/iostreamhelper.h" #include "../common/profile.h" #include "../common/rand.h" void testConvexFunctions() { //return; //TODO: if you want to test functions of this file, make this line a comment. cout << "--- Convex Functions (polygon, ellipse, ...) ---------------------" << endl; { const double EPSILON = 1e-4; vector<vector<pair<int, int>>> polygons{ { { 0, 0 }, { 2, 0 }, { 2, 1 }, { 0, 1 } }, { { -1, -1 }, { 5, 1 }, { 0, 5 } } }; vector<tuple<pair<int, int>, pair<int, int>, int>> ellipses{ { { 1, 2 }, { 1, 4 }, 2} }; auto ans = ternarySearchMax3D(-10, -10, 10, 10, [&](double x, double y) { return min(ConvexFunctions<int, double>::evalPointToPolygonsMax(polygons, x, y), ConvexFunctions<int, double>::evalPointToEllipsesMax(ellipses, x, y)); }, 1e-9); if (abs(ans.first.first - 1.0) > EPSILON || abs(ans.first.second - 1.0) > EPSILON) cout << "Mismatched : ans = " << ans.first << ", gt = (1, 1)" << endl; assert(abs(ans.first.first - 1.0) <= EPSILON && abs(ans.first.second - 1.0) <= EPSILON); } cout << "OK!" << endl; }
32.708333
96
0.527389
[ "vector" ]
3968a4f868ce5789a1e45a5c8fca586c061d37b4
2,613
cpp
C++
Sample022/src/mesh_instance.cpp
Monsho/D3D12Samples
4624fd64b57c12fee1085ecfba1f770f802a236c
[ "MIT" ]
32
2017-10-11T00:23:17.000Z
2022-01-02T14:08:56.000Z
Sample022/src/mesh_instance.cpp
Monsho/D3D12Samples
4624fd64b57c12fee1085ecfba1f770f802a236c
[ "MIT" ]
null
null
null
Sample022/src/mesh_instance.cpp
Monsho/D3D12Samples
4624fd64b57c12fee1085ecfba1f770f802a236c
[ "MIT" ]
6
2019-01-18T13:16:01.000Z
2021-09-07T09:43:20.000Z
#include "mesh_instance.h" namespace sl12 { //---- bool MeshletRenderComponent::Initialize(Device* pDev, const std::vector<ResourceItemMesh::Meshlet>& meshlets) { struct MeshletData { DirectX::XMFLOAT3 aabbMin; u32 indexOffset; DirectX::XMFLOAT3 aabbMax; u32 indexCount; }; if (!meshletB_.Initialize(pDev, sizeof(MeshletData) * meshlets.size(), sizeof(MeshletData), BufferUsage::ShaderResource, D3D12_RESOURCE_STATE_GENERIC_READ, true, false)) { return false; } if (!meshletBV_.Initialize(pDev, &meshletB_, 0, (u32)meshlets.size(), sizeof(MeshletData))) { return false; } if (!indirectArgumentB_.Initialize(pDev, sizeof(D3D12_DRAW_INDEXED_ARGUMENTS) * meshlets.size(), sizeof(D3D12_DRAW_INDEXED_ARGUMENTS), BufferUsage::ShaderResource, D3D12_RESOURCE_STATE_GENERIC_READ, false, true)) { return false; } if (!indirectArgumentUAV_.Initialize(pDev, &indirectArgumentB_, 0, (u32)meshlets.size(), sizeof(D3D12_DRAW_INDEXED_ARGUMENTS), 0)) { return false; } { MeshletData* data = (MeshletData*)meshletB_.Map(nullptr); for (auto&& m : meshlets) { data->aabbMin = m.boundingInfo.box.aabbMin; data->aabbMax = m.boundingInfo.box.aabbMax; data->indexOffset = m.indexOffset; data->indexCount = m.indexCount; data++; } meshletB_.Unmap(); } return true; } //---- void MeshletRenderComponent::Destroy() { meshletBV_.Destroy(); meshletB_.Destroy(); indirectArgumentUAV_.Destroy(); indirectArgumentB_.Destroy(); } //---- void MeshletRenderComponent::TransitionIndirectArgument(CommandList* pCmdList, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { pCmdList->TransitionBarrier(&indirectArgumentB_, before, after); } //---- bool MeshInstance::Initialize(Device* pDevice, ResourceHandle res) { pParentDevice_ = pDevice; hResMesh_ = res; auto id = DirectX::XMMatrixIdentity(); DirectX::XMStoreFloat4x4(&mtxTransform_, id); auto mesh_item = res.GetItem<ResourceItemMesh>(); if (!mesh_item->GetSubmeshes()[0].meshlets.empty()) { auto&& submeshes = mesh_item->GetSubmeshes(); meshletComponents_.reserve(submeshes.size()); for (auto&& submesh : submeshes) { MeshletRenderComponent* comp = new MeshletRenderComponent(); if (!comp->Initialize(pDevice, submesh.meshlets)) { return false; } meshletComponents_.push_back(comp); } } return true; } //---- void MeshInstance::Destroy() { for (auto&& item : meshletComponents_) pParentDevice_->KillObject(item); meshletComponents_.clear(); } } // namespace sl12 // EOF
24.650943
214
0.704171
[ "vector" ]
39691d87d790a4c313c1d29834b2c89219ad59ff
392
cpp
C++
src/core/EmptyScene.cpp
kyle-piddington/SharkProject
d34d27cd7a7fbd385dd9edccd69b2d2257be70f2
[ "MIT" ]
2
2015-11-27T10:15:37.000Z
2020-10-17T23:57:11.000Z
src/core/EmptyScene.cpp
kyle-piddington/SharkProject
d34d27cd7a7fbd385dd9edccd69b2d2257be70f2
[ "MIT" ]
null
null
null
src/core/EmptyScene.cpp
kyle-piddington/SharkProject
d34d27cd7a7fbd385dd9edccd69b2d2257be70f2
[ "MIT" ]
1
2021-02-18T14:42:03.000Z
2021-02-18T14:42:03.000Z
#include "EmptyScene.h" EmptyScene::EmptyScene() : Scene() { } EmptyScene::~EmptyScene() { } void EmptyScene::initPrograms() { } void EmptyScene::initialBind() { glClearColor(0.75f, 0.52f, 0.3f, 1.0f); glEnable(GL_DEPTH_TEST); } void EmptyScene::render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void EmptyScene::update() { } void EmptyScene::cleanup() { }
12.25
54
0.681122
[ "render" ]
3971dda86531e1ecdd5d8c4bceec3e7e18cb273b
2,328
cpp
C++
modules/goblin/register_types.cpp
filipworksdev/goblin-test
c2a251fc66e43f7e74327cbec73b1d1fc5aa4b1d
[ "MIT", "Apache-2.0", "Unlicense" ]
9
2022-02-07T09:53:17.000Z
2022-03-31T17:50:38.000Z
modules/goblin/register_types.cpp
filipworksdev/goblin-test
c2a251fc66e43f7e74327cbec73b1d1fc5aa4b1d
[ "MIT", "Apache-2.0", "Unlicense" ]
null
null
null
modules/goblin/register_types.cpp
filipworksdev/goblin-test
c2a251fc66e43f7e74327cbec73b1d1fc5aa4b1d
[ "MIT", "Apache-2.0", "Unlicense" ]
6
2021-11-27T17:31:06.000Z
2022-03-26T02:22:11.000Z
/* register_types.cpp */ #include "core/class_db.h" #include "register_types.h" #include "editor/editor_node.h" #include "editor/mixin_script_editor.h" #include "editor/mixin_script_editor_plugin.h" #include "mixin_script.h" #include "core/script_language.h" #include "image_indexed.h" #include "io/image_loader_indexed_png.h" #include "io/resource_saver_indexed_png.h" #include "midi_player.h" #include "rand.h" static ImageLoaderIndexedPNG *image_loader_indexed_png; static Ref<ResourceSaverIndexedPNG> resource_saver_indexed_png; static MixinScriptLanguage *script_mixin_script = nullptr; static Ref<Rand> rand_ref; #if defined(TOOLS_ENABLED) static ScriptEditorBase *create_editor(const RES &p_resource) { if (Object::cast_to<MixinScript>(*p_resource)) { return memnew(MixinScriptEditor); } return nullptr; } static void mixin_script_register_editor_callback() { ScriptEditor::register_create_script_editor_function(create_editor); } #endif void register_goblin_types() { ClassDB::register_class<ImageIndexed>(); image_loader_indexed_png = memnew(ImageLoaderIndexedPNG); ImageLoader::add_image_format_loader(image_loader_indexed_png); resource_saver_indexed_png.instance(); ResourceSaver::add_resource_format_saver(resource_saver_indexed_png); script_mixin_script = memnew(MixinScriptLanguage); ScriptServer::register_language(script_mixin_script); ClassDB::register_class<MixinScript>(); ClassDB::register_class<Mixin>(); ClassDB::register_class<MidiPlayer>(); ClassDB::register_class<MidiFile>(); rand_ref.instance(); ClassDB::register_class<Rand>(); Engine::get_singleton()->add_singleton(Engine::Singleton("Rand", Object::cast_to<Object>(Rand::get_singleton()))); #ifdef TOOLS_ENABLED EditorNode::add_plugin_init_callback(mixin_script_register_editor_callback); EditorPlugins::add_by_type<MixinScriptEditorPlugin>(); if (Engine::get_singleton()->is_editor_hint()) { Ref<ResourceImporterMidiFile> midiobject; midiobject.instance(); ResourceFormatImporter::get_singleton()->add_importer(midiobject); } #endif } void unregister_goblin_types() { ResourceSaver::remove_resource_format_saver(resource_saver_indexed_png); resource_saver_indexed_png.unref(); ScriptServer::unregister_language(script_mixin_script); memdelete(script_mixin_script); rand_ref.unref(); }
29.1
115
0.808419
[ "object" ]
397722edd69628c4d2050a244605bf61a76b14f3
7,129
cpp
C++
test/api_ConsoleTest.cpp
smorey2/litehtml
9400244dba01f7239e40d3468b020f2c4a1acca2
[ "BSD-3-Clause" ]
null
null
null
test/api_ConsoleTest.cpp
smorey2/litehtml
9400244dba01f7239e40d3468b020f2c4a1acca2
[ "BSD-3-Clause" ]
null
null
null
test/api_ConsoleTest.cpp
smorey2/litehtml
9400244dba01f7239e40d3468b020f2c4a1acca2
[ "BSD-3-Clause" ]
null
null
null
#include <assert.h> #include "litehtml.h" #include "test/container_test.h" using namespace litehtml; static context ctx; static container_test container; static document::ptr MakeDocument(wchar_t* source) { return document::createFromString(source, &container, &ctx); } static void Test() { Console* console; document::ptr thedoc; // https://www.w3schools.com/jsref/met_console_assert.asp { auto document = thedoc = MakeDocument(LR"xyz( <html> <body> <p id="demo"></p> </body> </html>)xyz"); { console->assert_(document->getElementById(_t("demo")), _t("You have no element with ID 'demo'")); } { std::map<tstring, tstring> myObj = { {_t("firstname"), _t("John")}, {_t("lastname"), _t("Doe")} }; console->assert_(document->getElementById(_t("demo")), myObj); } { tstring myArr[] = { _t("Orange"), _t("Banana"), _t("Mango"), _t("Kiwi") }; console->assert_(document->getElementById(_t("demo")), myArr); } } // https://www.w3schools.com/jsref/met_console_clear.asp { { console->clear(); } } // https://www.w3schools.com/jsref/met_console_count.asp { { int i; for (i = 0; i < 10; i++) { console->count(); } } { console->count(); console->count(); } { console->count(_t("")); console->count(_t("")); } { console->count(_t("myLabel")); console->count(_t("myLabel")); } } // https://www.w3schools.com/jsref/met_console_error.asp { { console->error(_t("You made a mistake")); } { std::map<tstring, tstring> myObj = { {_t("firstname"), _t("John")}, {_t("lastname"), _t("Doe")} }; console->error(myObj); } { tstring myArr[] = { _t("Orange"), _t("Banana"), _t("Mango"), _t("Kiwi") }; console->error(myArr); } } // https://www.w3schools.com/jsref/met_console_group.asp { { console->log(_t("Hello world!")); console->group(); console->log(_t("Hello again, this time inside a group!")); } { console->log(_t("Hello world!")); console->group(); console->log(_t("Hello again, this time inside a group!")); console->groupEnd(); console->log(_t("and we are back.")); } { console->log(_t("Hello world!")); console->group(_t("myLabel")); console->log(_t("Hello again, this time inside a group, with a label!")); } } // https://www.w3schools.com/jsref/met_console_groupcollapsed.asp { { console->log(_t("Hello world!")); console->groupCollapsed(); console->log(_t("Hello again, this time inside a collapsed group!")); } { console->log(_t("Hello world!")); console->groupCollapsed(); console->log(_t("Hello again, this time inside a collapsed group!")); console->groupEnd(); console->log(_t("and we are back.")); } { console->log(_t("Hello world!")); console->groupCollapsed(_t("myLabel")); console->log(_t("Hello again, this time inside a collapsed group, with a label!")); } } // https://www.w3schools.com/jsref/met_console_groupend.asp { { console->log(_t("Hello world!")); console->group(); console->log(_t("Hello again, this time inside a group!")); console->groupEnd(); console->log(_t("and we are back.")); } } // https://www.w3schools.com/jsref/met_console_info.asp { { console->info(_t("Hello world!")); } { std::map<tstring, tstring> myObj = { {_t("firstname"), _t("John")}, {_t("lastname"), _t("Doe")} }; console->info(myObj); } { tstring myArr[] = { _t("Orange"), _t("Banana"), _t("Mango"), _t("Kiwi") }; console->info(myArr); } } // https://www.w3schools.com/jsref/met_console_log.asp { { console->log(_t("Hello world!")); } { std::map<tstring, tstring> myObj = { {_t("firstname"), _t("John")}, {_t("lastname"), _t("Doe")} }; console->log(myObj); } { tstring myArr[] = { _t("Orange"), _t("Banana"), _t("Mango"), _t("Kiwi") }; console->log(myArr); } } // https://www.w3schools.com/jsref/met_console_table.asp { { tstring p0[] = { _t("Audi"), _t("Volvo"), _t("Ford") }; console->table(p0); } { std::map<tstring, tstring> myObj = { { _t("firstname"), _t("John") }, { _t("lastname"), _t("Doe") } }; } { std::map<tstring, tstring> car1 = { {_t("name"), _t("Audi")}, {_t("model"), _t("A4")} }; std::map<tstring, tstring> car2 = { {_t("name"), _t("Volvo")}, {_t("model"), _t("XC90")} }; std::map<tstring, tstring> car3 = { {_t("name"), _t("Ford")}, {_t("model"), _t("Fusion")} }; std::map<tstring, tstring> p0[] = { car1, car2, car3 }; console->table(p0); } { std::map<tstring, tstring> car1 = { {_t("name"), _t("Audi")}, {_t("model"), _t("A4")} }; std::map<tstring, tstring> car2 = { {_t("name"), _t("Volvo")}, {_t("model"), _t("XC90")} }; std::map<tstring, tstring> car3 = { {_t("name"), _t("Ford")}, {_t("model"), _t("Fusion")} }; std::map<tstring, tstring> p0[] = { car1, car2, car3 }; tstring p1[] = { _t("model") }; console->table(p0, p1); } } // https://www.w3schools.com/jsref/met_console_time.asp { { console->time(); for (int i = 0; i < 100000; i++) { // some code } console->timeEnd(); } { console->time(_t("test1")); for (int i = 0; i < 100000; i++) { // some code } console->timeEnd(_t("test1")); } { int i; console->time(_t("test for loop")); for (i = 0; i < 100000; i++) { // some code } console->timeEnd(_t("test for loop")); i = 0; console->time(_t("test while loop")); while (i < 1000000) { i++; } console->timeEnd(_t("test while loop")); } } // https://www.w3schools.com/jsref/met_console_timeend.asp { { console->time(); for (int i = 0; i < 100000; i++) { // some code } console->timeEnd(); } { console->time(_t("test1")); for (int i = 0; i < 100000; i++) { // some code } console->timeEnd(_t("test1")); } { int i; console->time(_t("test for loop")); for (i = 0; i < 100000; i++) { // some code } console->timeEnd(_t("test for loop")); i = 0; console->time(_t("test while loop")); while (i < 1000000) { i++; } console->timeEnd(_t("test while loop")); } } // https://www.w3schools.com/jsref/met_console_trace.asp { { std::function<void()> myOtherFunction; std::function<void()> myFunction = [myOtherFunction]() { myOtherFunction(); }; myOtherFunction = [console]() { console->trace(); }; myFunction(); } } // https://www.w3schools.com/jsref/met_console_warn.asp { { console->warn(_t("This is a warning!")); } { std::map<tstring, tstring> myObj = { { _t("firstname"), _t("John") }, { _t("lastname"), _t("Doe") } }; console->warn(myObj); } { tstring myArr[] = { _t("Orange"), _t("Banana"), _t("Mango"), _t("Kiwi") }; console->warn(myArr); } } } void api_ConsoleTest() { Test(); }
23.684385
116
0.54622
[ "model" ]
39776bab99acdf4f0defa5dfb58d69dec583298c
520
cpp
C++
arrayLeftRotation/sol.cpp
SandSnip3r/HackerRankCTCI
47f670c5cfa5a68f278ea50079825c8be6bc4347
[ "MIT" ]
null
null
null
arrayLeftRotation/sol.cpp
SandSnip3r/HackerRankCTCI
47f670c5cfa5a68f278ea50079825c8be6bc4347
[ "MIT" ]
null
null
null
arrayLeftRotation/sol.cpp
SandSnip3r/HackerRankCTCI
47f670c5cfa5a68f278ea50079825c8be6bc4347
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <iterator> #include <vector> using namespace std; int main() { int numberOfElements, rotationCount; cin >> numberOfElements >> rotationCount; vector<int> myNums; myNums.reserve(numberOfElements); for (int i=0; i<numberOfElements; ++i) { int temp; cin >> temp; myNums.emplace_back(temp); } rotate(myNums.begin(), myNums.begin()+rotationCount, myNums.end()); copy(myNums.begin(), myNums.end(), ostream_iterator<int>(cout, " ")); cout << '\n'; return 0; }
23.636364
70
0.696154
[ "vector" ]
397bc75b2e7509564774ebe011a2a8fe407a7bca
11,864
cpp
C++
src/RTL/Component/Common/CIFXHashMap.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
44
2016-05-06T00:47:11.000Z
2022-02-11T06:51:37.000Z
src/RTL/Component/Common/CIFXHashMap.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
3
2016-06-27T12:37:31.000Z
2021-03-24T12:39:48.000Z
src/RTL/Component/Common/CIFXHashMap.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
15
2016-02-28T11:08:30.000Z
2021-06-01T03:32:01.000Z
//*************************************************************************** // // Copyright (c) 1999 - 2006 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //*************************************************************************** /** @file CIFXHashMap.cpp Main implementation file for the hash map subsystem. */ #include <string.h> #include "CIFXHashMap.h" #include "FNVPlusPlus.h" //--------------------------------------------------------------------------- // CIFXHashMap constructor // // This method initializes the refCount to 0 //--------------------------------------------------------------------------- CIFXHashMap::CIFXHashMap() { m_uRefCount=0; m_ppHashTable=NULL; m_uHashTableSize=0; } //--------------------------------------------------------------------------- // CIFXHashMap destructor // // This method does nothing! //--------------------------------------------------------------------------- CIFXHashMap::~CIFXHashMap() { DeleteTable(); } //--------------------------------------------------------------------------- // CIFXHashMap::AddRef // // This method increments the reference count for an interface on a // component. It should be called for every new copy of a pointer to an // interface on a given component. It returns a U32 that contains a value // from 1 to 2^32 - 1 that defines the new reference count. The return // value should only be used for debugging purposes. //--------------------------------------------------------------------------- U32 CIFXHashMap::AddRef(void) { return ++m_uRefCount; } //--------------------------------------------------------------------------- // CIFXHashMap::Release // // This method decrements the reference count for the calling interface on a // component. It returns a U32 that contains a value from 1 to 2^32 - 1 // that defines the new reference count. The return value should only be // used for debugging purposes. If the reference count on a component falls // to zero, the component is destroyed. //--------------------------------------------------------------------------- U32 CIFXHashMap::Release(void) { if ( !( --m_uRefCount ) ) { delete this; // This second return point is used so that the deleted object's // reference count isn't referenced after the memory is released. return 0; } return m_uRefCount; } //--------------------------------------------------------------------------- // CIFXHashMap::QueryInterface // // This method provides access to the various interfaces supported by a // component. Upon success, it increments the component's reference count, // hands back a pointer to the specified interface and returns IFX_OK. // Otherwise, it returns either IFX_E_INVALID_POINTER or IFX_E_UNSUPPORTED. // // A number of rules must be adhered to by all implementations of // QueryInterface. For a list of such rules, refer to the Microsoft COM // description of the IUnknown::QueryInterface method. //--------------------------------------------------------------------------- IFXRESULT CIFXHashMap::QueryInterface( IFXREFIID interfaceId, void** ppInterface ) { IFXRESULT result = IFX_OK; if ( ppInterface ) { if ( interfaceId == IID_IFXHashMap || interfaceId == IID_IFXUnknown ) *ppInterface = ( CIFXHashMap* ) this; else { *ppInterface = NULL; result = IFX_E_UNSUPPORTED; } if ( IFXSUCCESS( result ) ) ( ( IFXUnknown* ) *ppInterface )->AddRef(); } else result = IFX_E_INVALID_POINTER; return result; } // IFXHashMap methods //--------------------------------------------------------------------------- // CIFXHashMap::Initialize // // This method creates a table of pointers to HashMap structs and initalizes // them all to NULL as well as sets up all other variables. //--------------------------------------------------------------------------- IFXRESULT CIFXHashMap::Initialize(U32 uHashSize) { IFXRESULT iResult=IFX_OK; if(uHashSize==0) iResult=IFX_E_INVALID_RANGE; if(IFXSUCCESS(iResult)) { if(m_ppHashTable) DeleteTable(); m_ppHashTable=new HashMapObject*[uHashSize]; if(m_ppHashTable==NULL) iResult=IFX_E_OUT_OF_MEMORY; if(IFXSUCCESS(iResult)) { m_uHashTableSize=uHashSize; U32 uIndex; for(uIndex=0; uIndex<m_uHashTableSize; uIndex++) m_ppHashTable[uIndex]=NULL; } } return iResult; } //--------------------------------------------------------------------------- // CIFXHashMap::Add // // This method provides adds a new hash object to the hash table in // the appropriate bucket. //--------------------------------------------------------------------------- IFXRESULT CIFXHashMap::Add(IFXString* pString, U32 uID) { IFXRESULT iResult=IFX_OK; if(m_ppHashTable==NULL) iResult=IFX_E_NOT_INITIALIZED; if(pString==NULL) iResult=IFX_E_INVALID_POINTER; if(IFXSUCCESS(iResult)) { U32 uHashIndex=0; HashMapObject* pHashEntry=new HashMapObject(); if(pHashEntry==NULL) iResult=IFX_E_OUT_OF_MEMORY; if (IFXSUCCESS(iResult)) { pHashEntry->pName=new IFXString(pString); if (pHashEntry->pName == NULL) iResult=IFX_E_INVALID_POINTER; else pHashEntry->uID=uID; pHashEntry->pNext=NULL; } if (IFXSUCCESS(iResult)) iResult=HashFunction(pString, &uHashIndex); // repoint the hash table to account for this new object and fix the objects // next pointer if (IFXSUCCESS(iResult)) { pHashEntry->pNext=(HashMapObject*)m_ppHashTable[uHashIndex]; m_ppHashTable[uHashIndex]=pHashEntry; } } return iResult; } //--------------------------------------------------------------------------- // CIFXHashMap::Delete // // This method provides removes and deallocates a hash object stored in a // hash table bucket. //--------------------------------------------------------------------------- IFXRESULT CIFXHashMap::Delete(IFXString* pString) { IFXRESULT iResult=IFX_OK; if(m_ppHashTable==NULL) iResult=IFX_E_NOT_INITIALIZED; if(pString==NULL) iResult=IFX_E_INVALID_POINTER; if(IFXSUCCESS(iResult)) { U32 uHashIndex; // hash the object name to get what bucket it should be in iResult=HashFunction(pString, &uHashIndex); if(IFXSUCCESS(iResult)) { // item doesn't exist because bucket is empty if(m_ppHashTable[uHashIndex]==NULL) { iResult=IFX_E_CANNOT_FIND; } // bucket not empty, scan the chain for the right value BOOL bFound=FALSE; HashMapObject* pCurrent=m_ppHashTable[uHashIndex]; HashMapObject* pPrevious=m_ppHashTable[uHashIndex]; // is it the first element in the bucket? if(pCurrent) { if(pCurrent->pName->Compare(pString)== 0) { bFound=TRUE; m_ppHashTable[uHashIndex]=pCurrent->pNext; if(pCurrent->pName) delete pCurrent->pName; delete pCurrent; } else { // no, so scan down the bucket to find it while(!bFound && pCurrent!=NULL) { if(pCurrent->pName->Compare(pString)==0) { bFound=TRUE; pPrevious->pNext=pCurrent->pNext; if(pCurrent->pName) delete pCurrent->pName; delete pCurrent; } else { pPrevious=pCurrent; pCurrent=pCurrent->pNext; } } } } if(!bFound) { iResult=IFX_E_CANNOT_FIND; } } } return iResult; } //--------------------------------------------------------------------------- // CIFXHashMap::Find // // This method finds a hash object based on its name, and returns a pointer // to the appropriate hash object. It addref()'s the object, so it is // necissary to release it when done using it. //--------------------------------------------------------------------------- IFXRESULT CIFXHashMap::Find(IFXString* pString, U32* pID) { IFXRESULT iResult=IFX_OK; if(pID==NULL) iResult=IFX_E_INVALID_POINTER; if(m_ppHashTable==NULL) iResult=IFX_E_NOT_INITIALIZED; if(pString==NULL) iResult=IFX_E_INVALID_POINTER; if(IFXSUCCESS(iResult)) { U32 uHashIndex; iResult=HashFunction(pString, &uHashIndex); if(IFXSUCCESS(iResult)) { BOOL bFound=IFX_FALSE; HashMapObject* pCurrent=m_ppHashTable[uHashIndex]; // scan down bucket until you hit the element or null while(!bFound && pCurrent!=NULL) { if(pCurrent->pName->Compare(pString)==0) bFound=IFX_TRUE; else pCurrent=pCurrent->pNext; } if(bFound) { *pID=pCurrent->uID; iResult=IFX_OK; } else { *pID=0; iResult=IFX_E_CANNOT_FIND; } } } return iResult; } //--------------------------------------------------------------------------- // CIFXHashMap::HashFunction // // This method hashes the current string value and returns an index between // 0 and m_uHashTableSize. // // The particular hashing function used is the Fowler/Noll/Vo- hash, // specifically the 32-bit FNV-1a version. Refer to the module in which // it's defined for additional details. //--------------------------------------------------------------------------- IFXRESULT CIFXHashMap::HashFunction(IFXString* pName, U32* pIndex) { IFXRESULT iResult=IFX_OK; if(pIndex==NULL) iResult=IFX_E_INVALID_POINTER; if(IFXSUCCESS(iResult)) { if(m_uHashTableSize==1) { *pIndex=0; } else { *pIndex = fnv_32_str_with_hash_size( ( char* ) pName->Raw(), FNV1_32A_INIT, m_uHashTableSize ); } } return iResult; } //--------------------------------------------------------------------------- // CIFXHashMap::DeleteTable // // This method deletes all the entries in the hash table, and then the // table itself afterwards to clean up all memory //--------------------------------------------------------------------------- IFXRESULT CIFXHashMap::DeleteTable() { IFXRESULT iResult=IFX_OK; if( m_ppHashTable ) { HashMapObject* pCurrent=NULL; HashMapObject* pNext=NULL; U32 uIndex; for(uIndex=0; uIndex<m_uHashTableSize; uIndex++) { pCurrent=m_ppHashTable[uIndex]; m_ppHashTable[uIndex] = NULL; while ( pCurrent ) { pNext=pCurrent->pNext; if(pCurrent->pName) delete pCurrent->pName; delete pCurrent; pCurrent=pNext; } } delete[] m_ppHashTable; } return iResult; } //--------------------------------------------------------------------------- // CIFXHashMap_Factory (non-singleton) // // This is the CIFXHashMap component factory function. The // CIFXHashMap component is NOT a singleton. This function creates the // HashMap object, addref()'s it and returns it. //--------------------------------------------------------------------------- IFXRESULT IFXAPI_CALLTYPE CIFXHashMap_Factory( IFXREFIID interfaceId, void** ppInterface ) { IFXRESULT result; if ( ppInterface ) { // It doesn't exist, so try to create it. CIFXHashMap *pComponent = new CIFXHashMap; if ( pComponent ) { // Perform a temporary AddRef for our usage of the component. pComponent->AddRef(); // Attempt to obtain a pointer to the requested interface. result = pComponent->QueryInterface( interfaceId, ppInterface ); // Perform a Release since our usage of the component is now // complete. Note: If the QI fails, this will cause the // component to be destroyed. pComponent->Release(); } else result = IFX_E_OUT_OF_MEMORY; } else result = IFX_E_INVALID_POINTER; return result; }
26.189845
82
0.580748
[ "object" ]
303eb29797846da5d1889996c2e615422714f17d
7,159
cpp
C++
tools/generators/grpc/ClassDescriptor.cpp
b-com-software-basis/xpcf
26ce21929ff6209ef69117270cf49844348c988f
[ "Apache-2.0" ]
null
null
null
tools/generators/grpc/ClassDescriptor.cpp
b-com-software-basis/xpcf
26ce21929ff6209ef69117270cf49844348c988f
[ "Apache-2.0" ]
7
2020-02-13T20:35:16.000Z
2021-11-19T17:46:15.000Z
tools/generators/grpc/ClassDescriptor.cpp
b-com-software-basis/xpcf
26ce21929ff6209ef69117270cf49844348c988f
[ "Apache-2.0" ]
1
2018-02-26T14:10:43.000Z
2018-02-26T14:10:43.000Z
#include "ClassDescriptor.h" #include <iostream> #include "MethodDescriptor.h" #include <cppast/cpp_entity_kind.hpp> #include <xpcf/core/helpers.h> #include <boost/algorithm/string.hpp> namespace xpcf = org::bcom::xpcf; ClassDescriptor::ClassDescriptor(const cppast::cpp_entity& c, const std::string & nameSpace, const std::string & filePath):m_baseClass(static_cast<const cppast::cpp_class&>(c)) { m_metadata[MetadataType::INTERFACENAMESPACE] = nameSpace; m_metadata[MetadataType::INTERFACEFILEPATH] = filePath; } ClassDescriptor::ClassDescriptor(const cppast::cpp_class& c):m_baseClass(c) { } std::string ClassDescriptor::getFullName() const { if (m_metadata.at(MetadataType::INTERFACENAMESPACE).empty()) { return m_baseClass.name(); } return m_metadata.at(MetadataType::INTERFACENAMESPACE) + "::" + m_baseClass.name(); } void ClassDescriptor::setXpcfTrait(const org::bcom::xpcf::Traits & trait) { m_xpcfTrait.uuid = trait.uuid; m_xpcfTrait.name = trait.name; m_xpcfTrait.description = trait.description; } const org::bcom::xpcf::uuids::uuid & ClassDescriptor::createClientUUID() const { xpcf::uuids::random_generator gen; m_clientUUID = gen(); return m_clientUUID; } const org::bcom::xpcf::uuids::uuid & ClassDescriptor::createServerUUID() const { xpcf::uuids::random_generator gen; m_serverUUID = gen(); return m_serverUUID; } void ClassDescriptor::generateRpcMapping(const std::map<std::string, std::vector<std::size_t>> & virtualMethodsMap) { for (auto & [name, indexArray] : virtualMethodsMap) { if (indexArray.size() > 1) { std::size_t methodIndex = 0; for (auto & index : indexArray) { std::string grpcMethodName = name + "_grpc" + std::to_string(methodIndex++); m_virtualMethods[index]->m_rpcName = grpcMethodName; } } else { m_virtualMethods[indexArray[0]]->m_rpcName = name; } } } void ClassDescriptor::parseMethods(const cppast::cpp_class & c, std::map<std::string, std::vector<std::size_t>> & virtualMethodsMap, const cppast::cpp_entity_index& index) { for (auto & base: c.bases()) { std::cout<<"parseMethods::Base name="<<base.name()<<std::endl; if (base.name() == "org::bcom::xpcf::ComponentBase" || base.name() == "org::bcom::xpcf::ConfigurableBase") { m_isXpcfComponent = true; } if (base.name() == "org::bcom::xpcf::IComponentIntrospect") { m_isXpcfInterface = true; } auto baseClassRef = cppast::get_class(index,base); if (baseClassRef.has_value()) { auto & baseClass = baseClassRef.value(); // avoid to add twice methods from diamond interface inheritance. // WARNING: reminder : may have a conflict as the class name is not namespaced here ! if (!xpcf::mapContains(m_classParsed,baseClass.name())) { m_classParsed[baseClass.name()] = true; parseMethods(baseClass, virtualMethodsMap, index); } } } for (auto & m : c) { if (m.kind() == cppast::cpp_entity_kind::member_function_t) { // cast to member_function SRef<MethodDescriptor> desc = xpcf::utils::make_shared<MethodDescriptor>(static_cast<const cppast::cpp_member_function&>(m)); desc->parse(index); if (desc->isPureVirtual()) { m_virtualMethods.push_back(desc); virtualMethodsMap[desc->getName()].push_back(m_virtualMethods.size() - 1); } } } } bool ClassDescriptor::parse(const cppast::cpp_entity_index& index) { std::map<std::string, std::vector<std::size_t>> virtualMethodsMap; std::cout << " ==> parsing class "<<m_baseClass.name()<<" scope "<<std::endl; if (!m_baseClass.attributes().empty()) { // handle attrib for (auto & attrib : m_baseClass.attributes()) { if (attrib.scope().has_value()) { if (attrib.scope().value() == "xpcf") { if (attrib.name() == "ignore") { m_ignored = true; return true; } if (attrib.name() == "clientUUID") { if (attrib.arguments().has_value()) { std::string clientUUIDStr = attrib.arguments().value().as_string(); boost::algorithm::erase_all(clientUUIDStr,"\""); m_clientUUID = xpcf::toUUID(clientUUIDStr); } } if (attrib.name() == "serverUUID") { if (attrib.arguments().has_value()) { std::string serverUUIDStr = attrib.arguments().value().as_string(); boost::algorithm::erase_all(serverUUIDStr,"\""); m_serverUUID = xpcf::toUUID(serverUUIDStr); } } } if (attrib.scope().value() == "grpc") { if (attrib.name() == "client_receiveSize") { if (attrib.arguments().has_value()) { //when no attrib : howto figure out to not specify channel arguments ? std::string recvSizeStr = attrib.arguments().value().as_string(); boost::algorithm::erase_all(recvSizeStr,"\""); m_clientReceiveSizeOverriden = true; m_clientReceiveSize = std::atol(recvSizeStr.c_str()); } } else if (attrib.name() == "client_sendSize") { if (attrib.arguments().has_value()) { std::string sndSizeStr = attrib.arguments().value().as_string(); boost::algorithm::erase_all(sndSizeStr,"\""); m_clientSendSizeOverriden = true; m_clientSendSize = std::atol(sndSizeStr.c_str()); } } } } } } if (cppast::is_templated(m_baseClass)) { // template class is ignored : not part of services : need an instantiation return false; } for (auto & base: m_baseClass.bases()) { std::cout<<"Base name="<<base.name()<<std::endl; m_bases.push_back(base.name()); if (base.scope_name().has_value()) { std::cout<<"Base scope_name="<<base.scope_name().value().name()<<std::endl; } } parseMethods(m_baseClass,virtualMethodsMap,index); m_isInterface = !m_isXpcfComponent && (m_virtualMethods.size() > 0) && m_isXpcfInterface;// && ICompIns is ancestor direct or indirect if (isInterface()) { generateRpcMapping(virtualMethodsMap); } else { // search for xpcf::ISerializable inheritance // otherwise fall offs } //TODO : check ICompIntros is in inheritance tree !! return true; }
40.446328
176
0.563626
[ "vector" ]