hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
20419ff541ea6aea735c6d5731d25609bde79291
2,752
cpp
C++
cpp_harness/HarnessUtils.cpp
13ofClubs/parHarness
1e82dfabc64af8bced353a5236d1888def8f5dab
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
cpp_harness/HarnessUtils.cpp
13ofClubs/parHarness
1e82dfabc64af8bced353a5236d1888def8f5dab
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
cpp_harness/HarnessUtils.cpp
13ofClubs/parHarness
1e82dfabc64af8bced353a5236d1888def8f5dab
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* Copyright 2015 University of Rochester 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 "HarnessUtils.hpp" #include <list> #include <iostream> using namespace std; void errexit (const char *err_str) { fprintf (stderr, "%s\n", err_str); throw 1; } void faultHandler(int sig) { void *buf[30]; size_t sz; // scrape backtrace sz = backtrace(buf, 30); // print error msg fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(buf, sz, STDERR_FILENO); exit(1); } bool isInteger(const std::string &s){ // check for empty case, and easy fail at start of string if(s.empty() || ( (s[0] != '-') && (s[0] != '+') && (!isdigit(s[0])) ) ){ return false; } // strol parses only if valid long. char* buf; strtol(s.c_str(), &buf, 60); return (*buf == 0); } std::string machineName(){ char hostname[1024]; hostname[1023] = '\0'; gethostname(hostname, 1023); return std::string(hostname); } int numCores(){ return sysconf( _SC_NPROCESSORS_ONLN ); } int archBits(){ if(sizeof(void*) == 8){ return 64; } else if(sizeof(void*) == 16){ return 128; } else if(sizeof(void*) == 4){ return 32; } else if(sizeof(void*) == 2){ return 8; } } unsigned int nextRand(unsigned int last) { unsigned int next = last; next = next * 1103515245 + 12345; return((unsigned)(next/65536) % 32768); } int warmMemory(unsigned int megabytes){ uint64_t preheat = megabytes*(2<<20); int blockSize = sysconf(_SC_PAGESIZE); int toAlloc = preheat / blockSize; list<void*> allocd; int ret = 0; for(int i = 0; i<toAlloc; i++){ int32_t* ptr = (int32_t*)malloc(blockSize); // ptr2,3 reserves space in case the list needs room // this prevents seg faults, but we may be killed anyway // if the system runs out of memory ("Killed" vs "Segmentation Fault") int32_t* ptr2 = (int32_t*)malloc(blockSize); int32_t* ptr3 = (int32_t*)malloc(blockSize); if(ptr==NULL || ptr2==NULL || ptr3==NULL){ ret = -1; break; } free(ptr2); free(ptr3); ptr[0]=1; allocd.push_back(ptr); } for(int i = 0; i<toAlloc; i++){ void* ptr = allocd.back(); allocd.pop_back(); free(ptr); } return ret; }
22.193548
75
0.640625
13ofClubs
20444e6d590c5db5d1d6fec05643d8a6815ecde1
1,360
cpp
C++
BOJ/boj13549_2.cpp
SukJinKim/Algo-Rhythm
db78de61643e9110ff0e721124a744e3b0ae27f0
[ "MIT" ]
null
null
null
BOJ/boj13549_2.cpp
SukJinKim/Algo-Rhythm
db78de61643e9110ff0e721124a744e3b0ae27f0
[ "MIT" ]
null
null
null
BOJ/boj13549_2.cpp
SukJinKim/Algo-Rhythm
db78de61643e9110ff0e721124a744e3b0ae27f0
[ "MIT" ]
null
null
null
#include <array> #include <deque> #include <cstdio> #include <limits> #include <algorithm> using namespace std; const int MIN = 0; const int MAX = (int)1e5; const int INF = numeric_limits<int>::max(); array<int, MAX + 1> Time; deque<int> dq; bool inRange(int pos) { return (MIN <= pos && pos <= MAX); } int main() { int src, dest; int currPos, teleportPos, forwardPos, backwardPos; scanf("%d %d", &src, &dest); fill(Time.begin(), Time.end(), INF); Time[src] = 0; dq.push_front(src); while(!dq.empty()) { currPos = dq.front(); dq.pop_front(); if(currPos == dest) break; backwardPos = currPos - 1; forwardPos = currPos + 1; teleportPos = currPos * 2; if(inRange(backwardPos) && Time[currPos] + 1 < Time[backwardPos]) { dq.push_back(backwardPos); Time[backwardPos] = Time[currPos] + 1; } if(inRange(forwardPos) && Time[currPos] + 1 < Time[forwardPos]) { dq.push_back(forwardPos); Time[forwardPos] = Time[currPos] + 1; } if(inRange(teleportPos) && Time[currPos] < Time[teleportPos]) { dq.push_front(teleportPos); Time[teleportPos] = Time[currPos]; } } printf("%d\n", Time[dest]); return 0; }
21.25
73
0.544118
SukJinKim
20499339390607b74e0dd42cd5506c14ce40cde5
1,230
cpp
C++
examples/cpp/reflection/nested_set_member/src/main.cpp
teh-cmc/flecs
ef6c366bae1142fa501d505ccb28d3e23d27ebc2
[ "MIT" ]
18
2021-09-17T16:41:14.000Z
2022-02-01T15:22:20.000Z
examples/cpp/reflection/nested_set_member/src/main.cpp
teh-cmc/flecs
ef6c366bae1142fa501d505ccb28d3e23d27ebc2
[ "MIT" ]
36
2021-09-21T10:22:16.000Z
2022-01-22T10:25:11.000Z
examples/cpp/reflection/nested_set_member/src/main.cpp
teh-cmc/flecs
ef6c366bae1142fa501d505ccb28d3e23d27ebc2
[ "MIT" ]
6
2021-09-26T11:06:32.000Z
2022-01-21T15:07:05.000Z
#include <nested_set_member.h> #include <iostream> struct Point { float x; float y; }; struct Line { Point start; Point stop; }; int main(int, char *[]) { flecs::world ecs; ecs.component<Point>() .member<float>("x") .member<float>("y"); ecs.component<Line>() .member<Point>("start") .member<Point>("stop"); // Create entity, set value of Line using reflection API auto e = ecs.entity(); Line *ptr = e.get_mut<Line>(); auto cur = ecs.cursor<Line>(ptr); cur.push(); // { cur.member("start"); // start: cur.push(); // { cur.member("x"); // x: cur.set_float(10); // 10 cur.member("y"); // y: cur.set_float(20); // 20 cur.pop(); // } cur.member("stop"); // stop: cur.push(); // { cur.member("x"); // x: cur.set_float(30); // 30 cur.member("y"); // y: cur.set_float(40); // 40 cur.pop(); // } cur.pop(); // } // Convert component to string std::cout << ecs.to_expr(ptr).c_str() << "\n"; // {start: {x: 10.00, y: 20.00}, stop: {x: 30.00, y: 40.00}} }
24.117647
64
0.462602
teh-cmc
204f6459fdb6c2bea4b77a8d5378c20ebf959e0c
6,821
cpp
C++
pcim.cpp
cshelton/pcim-plain
e48fa9ce3130f38a6b8da95d3fe121070d66d27d
[ "MIT" ]
2
2018-09-17T10:03:12.000Z
2021-01-10T03:09:14.000Z
pcim.cpp
cshelton/pcim-plain
e48fa9ce3130f38a6b8da95d3fe121070d66d27d
[ "MIT" ]
null
null
null
pcim.cpp
cshelton/pcim-plain
e48fa9ce3130f38a6b8da95d3fe121070d66d27d
[ "MIT" ]
2
2018-04-13T01:37:28.000Z
2019-02-01T16:44:33.000Z
#include "pcim.h" #include <algorithm> #include <cmath> #include <mutex> #include <future> #include <queue> #include "serial.h" using namespace std; inline vector<vartrajrange> torange(const vector<traj> &data) { vector<vartrajrange> ret; if (data.empty()) return ret; int nv = data[0].size(); for(auto &x : data) for(int v=0;v<nv;v++) ret.emplace_back(&x,v); return ret; } pcim::pcim(const vector<traj> &data, const vector<shptr<pcimtest>> &tests, const pcimparams &params) { const vector<vartrajrange> &d = torange(data); ss s = suffstats(d); build(d,s,tests,score(s,params),params); } inline vector<vartrajrange> torange(const vector<traj *> & data) { vector<vartrajrange> ret; if (data.empty()) return ret; int nv = data[0]->size(); for(auto x : data) for(int v = 0; v < nv; v++) ret.emplace_back(x, v); return ret; } pcim::pcim(const vector<traj *> & data, const vector<shptr<pcimtest>> & tests, const pcimparams & params) { const vector<vartrajrange> & d = torange(data); ss s = suffstats(d); build(d , s, tests, score(s, params), params); } pcim::ss pcim::suffstats(const std::vector<vartrajrange> &data) { ss ret; ret.n=0.0; ret.t=0.0; for(const auto &x : data) { ret.t += x.range.second-x.range.first; const vartraj &vtr = (*(x.tr))[x.var]; auto i0 = vtr.upper_bound(x.range.first); auto i1 = vtr.upper_bound(x.range.second); ret.n += distance(i0,i1); } return ret; } double pcim::score(const ss &d, const pcimparams &p) { double a_n = p.a+d.n; double b_n = p.b+d.t; double hn = d.n/2.0; return p.lk + lgamma(a_n) - p.lga + p.alb - a_n*log(b_n); } void pcim::calcleaf(const ss &d, const pcimparams &p) { rate = (p.a+d.n)/(p.b+d.t); } pcim::pcim(const vector<vartrajrange> &data, const pcim::ss &s, const vector<shptr<pcimtest>> &tests, double basescore, const pcimparams &params) { build(data,s,tests,basescore,params); } pcim::testpick pcim::picktest(const vector<vartrajrange> &data, const vector<shptr<pcimtest>> &tests, const pcimparams &params, int procnum, int nproc) const { double sc = -numeric_limits<double>::infinity(); testpick ret; ret.testnum = -1; ret.s1 = ret.s2 = sc; for(int i=procnum;i<tests.size();i+=nproc) { auto &t = tests[i]; vector<vartrajrange> td1,td2; for(auto &x : data) t->chop(x,td1,td2); if (td1.empty() || td2.empty()) continue; ss tss1 = suffstats(td1), tss2 = suffstats(td2); if (tss1.n<params.mne || tss2.n<params.mne) continue; double rs1 = score(tss1,params); double rs2 = score(tss2,params); if (rs1+rs2>sc) { ret.testnum = i; ret.s1 = rs1; ret.s2=rs2; sc = rs1+rs2; ret.ss1 = move(tss1); ret.ss2 = move(tss2); ret.test = t; ret.d1 = move(td1); ret.d2 = move(td2); } } return ret; } void pcim::build(const vector<vartrajrange> &data, const ss &s, const vector<shptr<pcimtest>> &tests, double basescore, const pcimparams &params) { assert(!data.empty()); vector<vartrajrange> d1,d2; test.reset(); double sc = basescore; testpick pick; if (params.nproc<=1) { pick = picktest(data,tests,params); if (pick.s1+pick.s2>sc) sc = pick.s1+pick.s2; } else { vector<future<testpick>> futs(params.nproc); for(int i=0;i<params.nproc;i++) futs[i] = async(launch::async,&pcim::picktest, this,data,tests,params,i,params.nproc); int picki = tests.size(); for(auto &f : futs) { testpick p = f.get(); double newsc = p.s1+p.s2; if (newsc>sc || (newsc==sc && p.testnum<picki)) { pick = move(p); picki = p.testnum; sc = newsc; } } } if (sc > basescore) { test = pick.test; ttree = shptr<pcim>(new pcim(pick.d1,pick.ss1, tests,pick.s1,params)); ftree = shptr<pcim>(new pcim(pick.d2,pick.ss2, tests,pick.s2,params)); } else { ttree.reset(); ftree.reset(); } calcleaf(s,params); stats = s; } double pcim::getevent(const traj &tr, double &t, double expsamp, double unisamp, int &var, double maxt) const { double until; vector<const pcim *> leaves; double r = getrate(tr,t,until,leaves); while(expsamp>(until-t)*r) { expsamp -= (until-t)*r; if (until>maxt) return maxt; t = until; r = getrate(tr,t,until,leaves); } var = leaves.size()-1; for(int i=0;i<leaves.size();i++) { unisamp -= leaves[i]->rate/r; if (unisamp<=0) { var = i; break; } } return t+expsamp/r; } double pcim::getrate(const traj &tr, double t, double &until, vector<const pcim *> &ret) const { until = numeric_limits<double>::infinity(); ret.resize(tr.size()); double r = 0.0; for(int i=0;i<tr.size();i++) r += getratevar(tr,i,t,until,ret[i]); return r; } double pcim::getratevar(const traj &tr, int var, double t, double &until, const pcim *&leaf) const { if (!test) { leaf = this; return rate; } double til; bool dir = test->eval(tr,var,t,til); if (til<until) until = til; return (dir ? ttree : ftree)->getratevar(tr,var,t,until,leaf); } void pcim::print(ostream &os) const { printhelp(os,0); } void pcim::print(ostream &os, const datainfo &info) const { printhelp(os,0,&info); } void pcim::todot(ostream &os, const datainfo &info) const { os << "digraph {" << endl; int nn = 0; todothelp(os,-1,false,nn,info); os << "}" << endl; } void pcim::todothelp(ostream &os, int par, bool istrue, int &nn, const datainfo &info) const { int mynode = nn++; os << "\tNODE" << mynode << " [label=\""; if (!ttree) os << "rate = " << rate; else test->print(os,info); os << "\"];" << endl; if (par>=0) os << "\tNODE" << par << " -> NODE" << mynode << " [label=\"" << (istrue ? "Y: " : "N: ") << stats.n << ',' << stats.t << "\"];" << endl; if (ttree) { ttree->todothelp(os,mynode,true,nn,info); ftree->todothelp(os,mynode,false,nn,info); } } void pcim::printhelp(ostream &os, int lvl, const datainfo *info) const { for(int i=0;i<lvl;i++) os << " "; if (!ttree) os << "rate = " << rate << " [" << stats.n << ',' << stats.t << "]" << endl; else { os << "if "; if (info!=nullptr) test->print(os,*info); else test->print(os); os << " [" << stats.n << ',' << stats.t << "]" << endl; ttree->printhelp(os,lvl+1,info); for(int i=0;i<lvl;i++) os << " "; os << "else" << endl; ftree->printhelp(os,lvl+1,info); } } double pcim::llh(const std::vector<vartrajrange> &tr) const { if (!ttree) { ss d = suffstats(tr); return d.n*std::log(rate) - rate*d.t; } else { vector<vartrajrange> ttr,ftr; for(auto &x : tr) test->chop(x,ttr,ftr); return ttree->llh(ttr) + ftree->llh(ftr); } } BOOST_CLASS_EXPORT_IMPLEMENT(pcimtest) BOOST_CLASS_EXPORT_IMPLEMENT(timetest) BOOST_CLASS_EXPORT_IMPLEMENT(counttest) BOOST_CLASS_EXPORT_IMPLEMENT(varstattest<counttest>) BOOST_CLASS_EXPORT_IMPLEMENT(vartest) BOOST_CLASS_EXPORT_IMPLEMENT(staticgreqtest) BOOST_CLASS_EXPORT_IMPLEMENT(staticeqtest) BOOST_CLASS_EXPORT_IMPLEMENT(pcim)
27.393574
94
0.634218
cshelton
20556f7754c6f75e2f7ae5e881b60b422dae31dd
7,378
cpp
C++
src/diffdrive_orientation.cpp
srmanikandasriram/ev3-ros
8233c90934defd1db0616f8f83bc576e898c2a26
[ "MIT" ]
3
2016-11-30T19:23:16.000Z
2020-07-13T12:16:08.000Z
src/diffdrive_orientation.cpp
srmanikandasriram/ev3-ros
8233c90934defd1db0616f8f83bc576e898c2a26
[ "MIT" ]
null
null
null
src/diffdrive_orientation.cpp
srmanikandasriram/ev3-ros
8233c90934defd1db0616f8f83bc576e898c2a26
[ "MIT" ]
3
2016-11-30T19:23:19.000Z
2019-06-19T14:46:18.000Z
/*the srv file headers_ev3/go_to_goal.h should be of the form float64 vecx float64 vecy --- float64 x float64 y float64 tf This porgram enables the robot to orient itself along the vector (vecx,vecy) passed as request in rosservice call */ //Header files required to run ROS #include <ros.h> #include <nav_msgs/Odometry.h> #include <std_msgs/String.h> #include <geometry_msgs/Twist.h> #include <tf/transform_broadcaster.h> #include <tf/tf.h> #include <headers/orientation.h> //Header files required to run EV3dev #include <iostream> #include "ev3dev.h" #include <thread> #include <string.h> #include <math.h> #include <chrono> //#include <errno.h> using namespace std; using namespace ev3dev; using headers::orientation; ros::NodeHandle nh; //string ns = "/robot3/"; const float deg2rad = M_PI/180.0;//conversion from degrees to radians float xc = 0, yc = 0 ,tc = 0; //current co-ordinates float x = 0.0, y = 0.0, t = 0.0, t_offset = 0.0;//dynamic value of co-ordinates float vx = 0, wt = 0, vl, vr,td = 0,t_error = 0,cerror = 0,L = 0.12,tIerror = 0,tDerror = 0, old_t_error = 0;//t_error = error in theta float t_kp = 3 , t_ki = 0.05 , t_kd = 0.001; char* srvrIP; motor left_motor = OUTPUT_C, right_motor = OUTPUT_B; sensor gsense = INPUT_4; sensor us = INPUT_1; float R=0.03, speed = R*deg2rad ;//conversion factor of linear speed to angular speed in rad/s; int encoder[2]={0,0}, prev_encoder[2] = {0,0}, dl, dr,q,k ; string left_motor_port, right_motor_port, sensor_port ; float t_PID() { t_kp = 4 ; t_ki = 0; t_kd = 0; float omega = 0 ; tDerror = t_error - old_t_error; tIerror = tIerror + t_error; omega = t_kp * t_error + t_ki * tIerror + t_kd * tDerror; old_t_error = t_error; //cout << "omega = "<< omega << endl; return omega ; } void svcCallback(const orientation::Request & req, orientation::Response & res) { int count = 0; float xg, yg; xg = req.vecx ; //obtaining goal's x-coordinate yg = req.vecy ; //obtaining goal's y-coordinate td = atan((yg - yc)/(xg - xc));//calculating theta desired if((xg-xc>0)&&(yg-yc>0) || (xg-xc>0)&&(yg-yc<0)) td = td + 0; if((xg-xc<0)&&(yg-yc>0)) td = M_PI - abs(td); if((xg-xc<0)&&(yg-yc<0)) td = -M_PI + td; cout<<"desired = "<<td/deg2rad <<endl; cout<< "current ="<<tc/deg2rad <<endl; t_error = td - tc ; while(abs(t_error) >=0.01) { count++; t_error = td - tc ; wt = t_PID(); /* bang bang control if(t_error > 0) wt = 0.2; else if(t_error < 0) wt = -0.2;*/ vx = 0; vr = (vx+L/2*wt)/(speed); vl = (vx-L/2*wt)/(speed); //cout<<"left , right = "<<vl <<" "<<vr <<endl; left_motor.set_speed_regulation_enabled("on"); right_motor.set_speed_regulation_enabled("on"); if(vl!=0) { left_motor.set_speed_sp(vl); left_motor.set_command("run-forever"); } else { left_motor.set_speed_sp(0); left_motor.set_command("run-forever"); } if(vr!=0) { right_motor.set_speed_sp(vr); right_motor.set_command("run-forever"); } else { right_motor.set_speed_sp(0); right_motor.set_command("run-forever"); } } res.x = xc ; res.y = yc ; res.tf = tc/deg2rad ; td = 0; tIerror = 0; old_t_error = 0; cout <<"error = "<<t_error<< endl; cout<<"counts = "<< count <<endl; cout<<"Service request message: ("<<req.vecx<<","<<req.vecy<<") received \n ";//responding with:("<< res.x<<","<<res.y<<","<<res.tf/deg2rad<<")\n"; cout<<"Current co-ordinates are \n (x,y,theta(degress)) == ("<<xc<<","<<yc<<","<<tc/deg2rad<<") \n"; vl = 0.0 , vr = 0.0 ; left_motor.set_speed_sp(0); left_motor.set_command("run-forever"); right_motor.set_speed_sp(0); right_motor.set_command("run-forever"); } ros::ServiceServer<orientation::Request, orientation::Response> server("ori_srv",&svcCallback); void odometry() //function to calculate the odometry { int encoder[2]={0,0}, prev_encoder[2] = {0,0}, dl, dr; while(1) { encoder[0] = left_motor.position(); encoder[1] = right_motor.position(); //obtaining angle rotated by left and right wheels in 100 ms dl = encoder[0]-prev_encoder[0]; dr = encoder[1]-prev_encoder[1]; t = -gsense.value()*deg2rad - t_offset;//storing angle in radians after callibration t = t/deg2rad; if(t>0) { k = t/360; t = t - k*360; if(t>0&&t<90) q =1; if(t>90&&t<180) q = 2; if(t>180&&t<270) q = 3; if(t>270&&t<360) q = 4; if(q==1||q==2) t = t + 0; if(q==4||q==3) t = -360 + t ; } if(t<0) { k = -t/360; t = t + k*360; if(t<0 && t>-90) q =4; if(t<-90&&t>-180) q = 3; if(t<-180&&t>-270) q = 2; if(t<-270&&t>-360) q = 1; if(q==4||q==3) t = t + 0; if(q==1||q==2) t = 360 + t ; } t*=deg2rad; tc = t; //cout << "current value = "<<tc<<endl; //converting angle rotated by wheels to linear displacement and printing it x += cos(t)*speed*(dl+dr)/2.0; xc = x; y += sin(t)*speed*(dl+dr)/2.0; yc = y; cout<<"(x,y,theta) = "<<"("<<x<<","<<y<<","<<t/deg2rad<<")"<<endl ; prev_encoder[0] = encoder[0]; prev_encoder[1] = encoder[1]; //motor.speed() returns speed in rad/s vl = left_motor.speed(); vr = right_motor.speed(); //remmapping linear and angular velocity of centroid from vl, vr vx = (vl+vr)/2*speed; wt = (vl-vr)/L*speed; this_thread::sleep_for(chrono::milliseconds(100)); } } int main(int argc, char* argv[]) { if(argc<5) { cerr<<"Usage: "<<argv[0]<<" <IP address> <left motor port> <right motor port> <<gyro sensor port>\n"; cout<<"motor port options : outA outB outC outD \n"; cout<<"sensor port options : inA inB inC inD \n"; return 1; } else { srvrIP = (argv[1]); left_motor_port = (argv[2]); right_motor_port = (argv[3]); sensor_port = (argv[4]); gsense = sensor(sensor_port); } left_motor = motor(left_motor_port); left_motor.reset(); left_motor.set_position(0); left_motor.set_speed_regulation_enabled("on"); right_motor = motor(right_motor_port); right_motor.reset(); right_motor.set_position(0); right_motor.set_speed_regulation_enabled("on"); nh.initNode(srvrIP); nh.advertiseService(server); int milliseconds = 100; // Set mode //gsense = sensor(sensor_port); string mode="GYRO-G&A"; gsense.set_mode(mode); t_offset = -gsense.value()*deg2rad;//obtaining initial angle to callibrate //cout<<"t_offset = "<< t_offset <<endl; cout<<"gyroscope is callibrated"<<endl ; thread odom (odometry);//'threading' odometry and the main functions while(1) { nh.spinOnce(); sleep(1); this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); // sets frequency } odom.join(); return 0; }
27.325926
149
0.561941
srmanikandasriram
2057181232b97d1b2157c851f24e60a42af468e8
197
cpp
C++
Content/Simulation/BodyInfo.cpp
jodavis42/NBody
91a40ca60625494a27c517590d12df4a77f776b4
[ "Unlicense" ]
null
null
null
Content/Simulation/BodyInfo.cpp
jodavis42/NBody
91a40ca60625494a27c517590d12df4a77f776b4
[ "Unlicense" ]
null
null
null
Content/Simulation/BodyInfo.cpp
jodavis42/NBody
91a40ca60625494a27c517590d12df4a77f776b4
[ "Unlicense" ]
1
2018-12-07T22:19:06.000Z
2018-12-07T22:19:06.000Z
#include "SimulationPrecompiled.hpp" void BodyInfo::Load(Cog* cog) { mCog = cog; mPosition = cog->has(Transform)->GetWorldTranslation(); mMass = cog->has(RigidBody)->GetMass(); }
19.7
58
0.659898
jodavis42
20594cf85d943b944ec1da286269fbb073d497e5
1,544
hpp
C++
include/codegen/include/GlobalNamespace/ObstacleType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/ObstacleType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/ObstacleType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: namespace GlobalNamespace { // Autogenerated type: ObstacleType struct ObstacleType : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public ObstacleType FullHeight static constexpr const int FullHeight = 0; // Get static field: static public ObstacleType FullHeight static GlobalNamespace::ObstacleType _get_FullHeight(); // Set static field: static public ObstacleType FullHeight static void _set_FullHeight(GlobalNamespace::ObstacleType value); // static field const value: static public ObstacleType Top static constexpr const int Top = 1; // Get static field: static public ObstacleType Top static GlobalNamespace::ObstacleType _get_Top(); // Set static field: static public ObstacleType Top static void _set_Top(GlobalNamespace::ObstacleType value); // Creating value type constructor for type: ObstacleType ObstacleType(int value_ = {}) : value{value_} {} }; // ObstacleType } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ObstacleType, "", "ObstacleType"); #pragma pack(pop)
40.631579
76
0.709845
Futuremappermydud
205aaacb2624ffa1bf1f848f953d7ab4eaae8a7f
18,461
cpp
C++
ardupilot/libraries/AP_HAL_Linux/RCInput_Navio.cpp
quadrotor-IITKgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
1
2021-07-17T11:37:16.000Z
2021-07-17T11:37:16.000Z
ardupilot/libraries/AP_HAL_Linux/RCInput_Navio.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
ardupilot/libraries/AP_HAL_Linux/RCInput_Navio.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
#include <AP_HAL/AP_HAL.h> #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_NAVIO #include "GPIO.h" #include "RCInput_Navio.h" #include "Util_RPI.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <stdint.h> #include <sys/ioctl.h> #include <pthread.h> #include <string.h> #include <errno.h> #include <stdint.h> #include <time.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <assert.h> //Parametres #define RCIN_NAVIO_BUFFER_LENGTH 8 #define RCIN_NAVIO_SAMPLE_FREQ 500 #define RCIN_NAVIO_DMA_CHANNEL 0 #define RCIN_NAVIO_MAX_COUNTER 1300 #define PPM_INPUT_NAVIO RPI_GPIO_4 #define RCIN_NAVIO_MAX_SIZE_LINE 50 //Memory Addresses #define RCIN_NAVIO_RPI1_DMA_BASE 0x20007000 #define RCIN_NAVIO_RPI1_CLK_BASE 0x20101000 #define RCIN_NAVIO_RPI1_PCM_BASE 0x20203000 #define RCIN_NAVIO_RPI2_DMA_BASE 0x3F007000 #define RCIN_NAVIO_RPI2_CLK_BASE 0x3F101000 #define RCIN_NAVIO_RPI2_PCM_BASE 0x3F203000 #define RCIN_NAVIO_GPIO_LEV0_ADDR 0x7e200034 #define RCIN_NAVIO_DMA_LEN 0x1000 #define RCIN_NAVIO_CLK_LEN 0xA8 #define RCIN_NAVIO_PCM_LEN 0x24 #define RCIN_NAVIO_TIMER_BASE 0x7e003004 #define RCIN_NAVIO_DMA_SRC_INC (1<<8) #define RCIN_NAVIO_DMA_DEST_INC (1<<4) #define RCIN_NAVIO_DMA_NO_WIDE_BURSTS (1<<26) #define RCIN_NAVIO_DMA_WAIT_RESP (1<<3) #define RCIN_NAVIO_DMA_D_DREQ (1<<6) #define RCIN_NAVIO_DMA_PER_MAP(x) ((x)<<16) #define RCIN_NAVIO_DMA_END (1<<1) #define RCIN_NAVIO_DMA_RESET (1<<31) #define RCIN_NAVIO_DMA_INT (1<<2) #define RCIN_NAVIO_DMA_CS (0x00/4) #define RCIN_NAVIO_DMA_CONBLK_AD (0x04/4) #define RCIN_NAVIO_DMA_DEBUG (0x20/4) #define RCIN_NAVIO_PCM_CS_A (0x00/4) #define RCIN_NAVIO_PCM_FIFO_A (0x04/4) #define RCIN_NAVIO_PCM_MODE_A (0x08/4) #define RCIN_NAVIO_PCM_RXC_A (0x0c/4) #define RCIN_NAVIO_PCM_TXC_A (0x10/4) #define RCIN_NAVIO_PCM_DREQ_A (0x14/4) #define RCIN_NAVIO_PCM_INTEN_A (0x18/4) #define RCIN_NAVIO_PCM_INT_STC_A (0x1c/4) #define RCIN_NAVIO_PCM_GRAY (0x20/4) #define RCIN_NAVIO_PCMCLK_CNTL 38 #define RCIN_NAVIO_PCMCLK_DIV 39 extern const AP_HAL::HAL& hal; using namespace Linux; volatile uint32_t *RCInput_Navio::pcm_reg; volatile uint32_t *RCInput_Navio::clk_reg; volatile uint32_t *RCInput_Navio::dma_reg; Memory_table::Memory_table() { _page_count = 0; } //Init Memory table Memory_table::Memory_table(uint32_t page_count, int version) { uint32_t i; int fdMem, file; //Cache coherent adresses depends on RPI's version uint32_t bus = version == 1 ? 0x40000000 : 0xC0000000; uint64_t pageInfo; void* offset; _virt_pages = (void**)malloc(page_count * sizeof(void*)); _phys_pages = (void**)malloc(page_count * sizeof(void*)); _page_count = page_count; if ((fdMem = open("/dev/mem", O_RDWR | O_SYNC)) < 0) { fprintf(stderr,"Failed to open /dev/mem\n"); exit(-1); } if ((file = open("/proc/self/pagemap", O_RDWR | O_SYNC)) < 0) { fprintf(stderr,"Failed to open /proc/self/pagemap\n"); exit(-1); } //Magic to determine the physical address for this page: offset = mmap(0, _page_count*PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS|MAP_NORESERVE|MAP_LOCKED,-1,0); lseek(file, ((uintptr_t)offset)/PAGE_SIZE*8, SEEK_SET); //Get list of available cache coherent physical addresses for (i = 0; i < _page_count; i++) { _virt_pages[i] = mmap(0, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS|MAP_NORESERVE|MAP_LOCKED,-1,0); ::read(file, &pageInfo, 8); _phys_pages[i] = (void*)((uintptr_t)(pageInfo*PAGE_SIZE) | bus); } //Map physical addresses to virtual memory for (i = 0; i < _page_count; i++) { munmap(_virt_pages[i], PAGE_SIZE); _virt_pages[i] = mmap(_virt_pages[i], PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_FIXED|MAP_NORESERVE|MAP_LOCKED, fdMem, ((uintptr_t)_phys_pages[i] & (version == 1 ? 0xFFFFFFFF : ~bus))); memset(_virt_pages[i], 0xee, PAGE_SIZE); } close(file); close(fdMem); } Memory_table::~Memory_table() { free(_virt_pages); free(_phys_pages); } // This function returns physical address with help of pointer, which is offset from the beginning of the buffer. void* Memory_table::get_page(void** const pages, uint32_t addr) const { if (addr >= PAGE_SIZE * _page_count) { return NULL; } return (uint8_t*)pages[(uint32_t) addr / 4096] + addr % 4096; } //Get virtual address from the corresponding physical address from memory_table. void* Memory_table::get_virt_addr(const uint32_t phys_addr) const { // FIXME: Can't the address be calculated directly? // FIXME: if the address room in _phys_pages is not fragmented one may avoid a complete loop .. uint32_t i = 0; for (; i < _page_count; i++) { if ((uintptr_t) _phys_pages[i] == (((uintptr_t) phys_addr) & 0xFFFFF000)) { return (void*) ((uintptr_t) _virt_pages[i] + (phys_addr & 0xFFF)); } } return NULL; } // FIXME: in-congruent function style see above // This function returns offset from the beginning of the buffer using virtual address and memory_table. uint32_t Memory_table::get_offset(void ** const pages, const uint32_t addr) const { uint32_t i = 0; for (; i < _page_count; i++) { if ((uintptr_t) pages[i] == (addr & 0xFFFFF000) ) { return (i*PAGE_SIZE + (addr & 0xFFF)); } } return -1; } //How many bytes are available for reading in circle buffer? uint32_t Memory_table::bytes_available(const uint32_t read_addr, const uint32_t write_addr) const { if (write_addr > read_addr) { return (write_addr - read_addr); } else { return _page_count * PAGE_SIZE - (read_addr - write_addr); } } uint32_t Memory_table::get_page_count() const { return _page_count; } //Physical addresses of peripheral depends on Raspberry Pi's version void RCInput_Navio::set_physical_addresses(int version) { if (version == 1) { dma_base = RCIN_NAVIO_RPI1_DMA_BASE; clk_base = RCIN_NAVIO_RPI1_CLK_BASE; pcm_base = RCIN_NAVIO_RPI1_PCM_BASE; } else if (version == 2) { dma_base = RCIN_NAVIO_RPI2_DMA_BASE; clk_base = RCIN_NAVIO_RPI2_CLK_BASE; pcm_base = RCIN_NAVIO_RPI2_PCM_BASE; } } //Map peripheral to virtual memory void* RCInput_Navio::map_peripheral(uint32_t base, uint32_t len) { int fd = open("/dev/mem", O_RDWR); void * vaddr; if (fd < 0) { printf("Failed to open /dev/mem: %m\n"); return NULL; } vaddr = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, base); if (vaddr == MAP_FAILED) { printf("rpio-pwm: Failed to map peripheral at 0x%08x: %m\n", base); } close(fd); return vaddr; } //Method to init DMA control block void RCInput_Navio::init_dma_cb(dma_cb_t** cbp, uint32_t mode, uint32_t source, uint32_t dest, uint32_t length, uint32_t stride, uint32_t next_cb) { (*cbp)->info = mode; (*cbp)->src = source; (*cbp)->dst = dest; (*cbp)->length = length; (*cbp)->next = next_cb; (*cbp)->stride = stride; } void RCInput_Navio::stop_dma() { dma_reg[RCIN_NAVIO_DMA_CS | RCIN_NAVIO_DMA_CHANNEL << 8] = 0; } /* We need to be sure that the DMA is stopped upon termination */ void RCInput_Navio::termination_handler(int signum) { stop_dma(); hal.scheduler->panic("Interrupted"); } //This function is used to init DMA control blocks (setting sampling GPIO register, destination adresses, synchronization) void RCInput_Navio::init_ctrl_data() { uint32_t phys_fifo_addr; uint32_t dest = 0; uint32_t cbp = 0; dma_cb_t* cbp_curr; //Set fifo addr (for delay) phys_fifo_addr = ((pcm_base + 0x04) & 0x00FFFFFF) | 0x7e000000; //Init dma control blocks. /*We are transferring 1 byte of GPIO register. Every 56th iteration we are sampling TIMER register, which length is 8 bytes. So, for every 56 samples of GPIO we need 56 * 1 + 8 = 64 bytes of buffer. Value 56 was selected specially to have a 64-byte "block" TIMER - GPIO. So, we have integer count of such "blocks" at one virtual page. (4096 / 64 = 64 "blocks" per page. As minimum, we must have 2 virtual pages of buffer (to have integer count of vitual pages for control blocks): for every 56 iterations (64 bytes of buffer) we need 56 control blocks for GPIO sampling, 56 control blocks for setting frequency and 1 control block for sampling timer, so, we need 56 + 56 + 1 = 113 control blocks. For integer value, we need 113 pages of control blocks. Each control block length is 32 bytes. In 113 pages we will have (113 * 4096 / 32) = 113 * 128 control blocks. 113 * 128 control blocks = 64 * 128 bytes of buffer = 2 pages of buffer. So, for 56 * 64 * 2 iteration we init DMA for sampling GPIO and timer to (64 * 64 * 2) = 8192 bytes = 2 pages of buffer. */ // fprintf(stderr, "ERROR SEARCH1\n"); uint32_t i = 0; for (i = 0; i < 56 * 128 * RCIN_NAVIO_BUFFER_LENGTH; i++) // 8 * 56 * 128 == 57344 { //Transfer timer every 56th sample if(i % 56 == 0) { cbp_curr = (dma_cb_t*)con_blocks->get_page(con_blocks->_virt_pages, cbp); init_dma_cb(&cbp_curr, RCIN_NAVIO_DMA_NO_WIDE_BURSTS | RCIN_NAVIO_DMA_WAIT_RESP | RCIN_NAVIO_DMA_DEST_INC | RCIN_NAVIO_DMA_SRC_INC, RCIN_NAVIO_TIMER_BASE, (uintptr_t) circle_buffer->get_page(circle_buffer->_phys_pages, dest), 8, 0, (uintptr_t) con_blocks->get_page(con_blocks->_phys_pages, cbp + sizeof(dma_cb_t) ) ); dest += 8; cbp += sizeof(dma_cb_t); } // Transfer GPIO (1 byte) cbp_curr = (dma_cb_t*)con_blocks->get_page(con_blocks->_virt_pages, cbp); init_dma_cb(&cbp_curr, RCIN_NAVIO_DMA_NO_WIDE_BURSTS | RCIN_NAVIO_DMA_WAIT_RESP, RCIN_NAVIO_GPIO_LEV0_ADDR, (uintptr_t) circle_buffer->get_page(circle_buffer->_phys_pages, dest), 1, 0, (uintptr_t) con_blocks->get_page(con_blocks->_phys_pages, cbp + sizeof(dma_cb_t) ) ); dest += 1; cbp += sizeof(dma_cb_t); // Delay (for setting sampling frequency) /* DMA is waiting data request signal (DREQ) from PCM. PCM is set for 1 MhZ freqency, so, each sample of GPIO is limited by writing to PCA queue. */ cbp_curr = (dma_cb_t*)con_blocks->get_page(con_blocks->_virt_pages, cbp); init_dma_cb(&cbp_curr, RCIN_NAVIO_DMA_NO_WIDE_BURSTS | RCIN_NAVIO_DMA_WAIT_RESP | RCIN_NAVIO_DMA_D_DREQ | RCIN_NAVIO_DMA_PER_MAP(2), RCIN_NAVIO_TIMER_BASE, phys_fifo_addr, 4, 0, (uintptr_t)con_blocks->get_page(con_blocks->_phys_pages, cbp + sizeof(dma_cb_t) ) ); cbp += sizeof(dma_cb_t); } //Make last control block point to the first (to make circle) cbp -= sizeof(dma_cb_t); ((dma_cb_t*)con_blocks->get_page(con_blocks->_virt_pages, cbp))->next = (uintptr_t) con_blocks->get_page(con_blocks->_phys_pages, 0); } /*Initialise PCM See BCM2835 documentation: http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf */ void RCInput_Navio::init_PCM() { pcm_reg[RCIN_NAVIO_PCM_CS_A] = 1; // Disable Rx+Tx, Enable PCM block hal.scheduler->delay_microseconds(100); clk_reg[RCIN_NAVIO_PCMCLK_CNTL] = 0x5A000006; // Source=PLLD (500MHz) hal.scheduler->delay_microseconds(100); clk_reg[RCIN_NAVIO_PCMCLK_DIV] = 0x5A000000 | ((50000/RCIN_NAVIO_SAMPLE_FREQ)<<12); // Set pcm div. If we need to configure DMA frequency. hal.scheduler->delay_microseconds(100); clk_reg[RCIN_NAVIO_PCMCLK_CNTL] = 0x5A000016; // Source=PLLD and enable hal.scheduler->delay_microseconds(100); pcm_reg[RCIN_NAVIO_PCM_TXC_A] = 0<<31 | 1<<30 | 0<<20 | 0<<16; // 1 channel, 8 bits hal.scheduler->delay_microseconds(100); pcm_reg[RCIN_NAVIO_PCM_MODE_A] = (10 - 1) << 10; //PCM mode hal.scheduler->delay_microseconds(100); pcm_reg[RCIN_NAVIO_PCM_CS_A] |= 1<<4 | 1<<3; // Clear FIFOs hal.scheduler->delay_microseconds(100); pcm_reg[RCIN_NAVIO_PCM_DREQ_A] = 64<<24 | 64<<8; // DMA Req when one slot is free? hal.scheduler->delay_microseconds(100); pcm_reg[RCIN_NAVIO_PCM_CS_A] |= 1<<9; // Enable DMA hal.scheduler->delay_microseconds(100); pcm_reg[RCIN_NAVIO_PCM_CS_A] |= 1<<2; // Enable Tx hal.scheduler->delay_microseconds(100); } /*Initialise DMA See BCM2835 documentation: http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf */ void RCInput_Navio::init_DMA() { dma_reg[RCIN_NAVIO_DMA_CS | RCIN_NAVIO_DMA_CHANNEL << 8] = RCIN_NAVIO_DMA_RESET; //Reset DMA hal.scheduler->delay_microseconds(100); dma_reg[RCIN_NAVIO_DMA_CS | RCIN_NAVIO_DMA_CHANNEL << 8] = RCIN_NAVIO_DMA_INT | RCIN_NAVIO_DMA_END; dma_reg[RCIN_NAVIO_DMA_CONBLK_AD | RCIN_NAVIO_DMA_CHANNEL << 8] = reinterpret_cast<uintptr_t>(con_blocks->get_page(con_blocks->_phys_pages, 0));//Set first control block address dma_reg[RCIN_NAVIO_DMA_DEBUG | RCIN_NAVIO_DMA_CHANNEL << 8] = 7; // clear debug error flags dma_reg[RCIN_NAVIO_DMA_CS | RCIN_NAVIO_DMA_CHANNEL << 8] = 0x10880001; // go, mid priority, wait for outstanding writes } //We must stop DMA when the process is killed void RCInput_Navio::set_sigaction() { for (int i = 0; i < 64; i++) { //catch all signals (like ctrl+c, ctrl+z, ...) to ensure DMA is disabled struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = RCInput_Navio::termination_handler; sigaction(i, &sa, NULL); } } //Initial setup of variables RCInput_Navio::RCInput_Navio(): prev_tick(0), delta_time(0), curr_tick_inc(1000/RCIN_NAVIO_SAMPLE_FREQ), curr_pointer(0), curr_channel(0), width_s0(0), curr_signal(0), last_signal(228), state(RCIN_NAVIO_INITIAL_STATE) { int version = UtilRPI::from(hal.util)->get_rpi_version(); set_physical_addresses(version); //Init memory for buffer and for DMA control blocks. See comments in "init_ctrl_data()" to understand values "2" and "113" circle_buffer = new Memory_table(RCIN_NAVIO_BUFFER_LENGTH * 2, version); con_blocks = new Memory_table(RCIN_NAVIO_BUFFER_LENGTH * 113, version); } RCInput_Navio::~RCInput_Navio() { delete circle_buffer; delete con_blocks; } void RCInput_Navio::deinit() { stop_dma(); } //Initializing necessary registers void RCInput_Navio::init_registers() { dma_reg = (uint32_t*)map_peripheral(dma_base, RCIN_NAVIO_DMA_LEN); pcm_reg = (uint32_t*)map_peripheral(pcm_base, RCIN_NAVIO_PCM_LEN); clk_reg = (uint32_t*)map_peripheral(clk_base, RCIN_NAVIO_CLK_LEN); } void RCInput_Navio::init(void*) { init_registers(); //Enable PPM input enable_pin = hal.gpio->channel(PPM_INPUT_NAVIO); enable_pin->mode(HAL_GPIO_INPUT); //Configuration set_sigaction(); init_ctrl_data(); init_PCM(); init_DMA(); //wait a bit to let DMA fill queues and come to stable sampling hal.scheduler->delay(300); //Reading first sample curr_tick = *((uint64_t*) circle_buffer->get_page(circle_buffer->_virt_pages, curr_pointer)); prev_tick = curr_tick; curr_pointer += 8; curr_signal = *((uint8_t*) circle_buffer->get_page(circle_buffer->_virt_pages, curr_pointer)) & 0x10 ? 1 : 0; last_signal = curr_signal; curr_pointer++; } //Processing signal void RCInput_Navio::_timer_tick() { int j; void* x; //Now we are getting address in which DMAC is writing at current moment dma_cb_t* ad = (dma_cb_t*) con_blocks->get_virt_addr(dma_reg[RCIN_NAVIO_DMA_CONBLK_AD | RCIN_NAVIO_DMA_CHANNEL << 8]); for(j = 1; j >= -1; j--){ x = circle_buffer->get_virt_addr((ad + j)->dst); if(x != NULL) { break;} } //How many bytes have DMA transfered (and we can process)? counter = circle_buffer->bytes_available(curr_pointer, circle_buffer->get_offset(circle_buffer->_virt_pages, (uintptr_t)x)); //We can't stay in method for a long time, because it may lead to delays if (counter > RCIN_NAVIO_MAX_COUNTER) { counter = RCIN_NAVIO_MAX_COUNTER; } //Processing ready bytes for (;counter > 0x40;counter--) { //Is it timer samle? if (curr_pointer % (64) == 0) { curr_tick = *((uint64_t*) circle_buffer->get_page(circle_buffer->_virt_pages, curr_pointer)); curr_pointer+=8; counter-=8; } //Reading required bit curr_signal = *((uint8_t*) circle_buffer->get_page(circle_buffer->_virt_pages, curr_pointer)) & 0x10 ? 1 : 0; //If the signal changed if (curr_signal != last_signal) { delta_time = curr_tick - prev_tick; prev_tick = curr_tick; switch (state) { case RCIN_NAVIO_INITIAL_STATE: state = RCIN_NAVIO_ZERO_STATE; break; case RCIN_NAVIO_ZERO_STATE: if (curr_signal == 0) { width_s0 = (uint16_t) delta_time; state = RCIN_NAVIO_ONE_STATE; break; } else break; case RCIN_NAVIO_ONE_STATE: if (curr_signal == 1) { width_s1 = (uint16_t) delta_time; state = RCIN_NAVIO_ZERO_STATE; _process_rc_pulse(width_s0, width_s1); break; } else break; } } last_signal = curr_signal; curr_pointer++; if (curr_pointer >= circle_buffer->get_page_count()*PAGE_SIZE) { curr_pointer = 0; } curr_tick+=curr_tick_inc; } } #endif // CONFIG_HAL_BOARD_SUBTYPE
35.70793
200
0.657386
quadrotor-IITKgp
205c73ec2df4c3f9c85c202af7aaad2b4ad2eddb
196
cpp
C++
src/better_ChatEntry.cpp
ddarknut/better
47d801c4fa8de6c32dff933de7d25b559421ce09
[ "Apache-2.0" ]
5
2020-11-21T03:44:17.000Z
2021-07-10T22:51:28.000Z
src/better_ChatEntry.cpp
ddarknut/better
47d801c4fa8de6c32dff933de7d25b559421ce09
[ "Apache-2.0" ]
null
null
null
src/better_ChatEntry.cpp
ddarknut/better
47d801c4fa8de6c32dff933de7d25b559421ce09
[ "Apache-2.0" ]
1
2021-03-24T20:33:57.000Z
2021-03-24T20:33:57.000Z
#include <cstdlib> #include "better_ChatEntry.h" #include "better_alloc.h" void ChatEntry_free(ChatEntry* ce) { if (ce->name) BETTER_FREE(ce->name); if (ce->msg) BETTER_FREE(ce->msg); }
19.6
40
0.688776
ddarknut
205d4591ca401d01d1c69f660ebf63b30638c5a4
1,203
cpp
C++
LeetCode/cpp/127.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
279
2019-02-19T16:00:32.000Z
2022-03-23T12:16:30.000Z
LeetCode/cpp/127.cpp
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
2
2019-03-31T08:03:06.000Z
2021-03-07T04:54:32.000Z
LeetCode/cpp/127.cpp
ZintrulCre/LeetCode_Crawler
de23e16ead29336b5ee7aa1898a392a5d6463d27
[ "MIT" ]
12
2019-01-29T11:45:32.000Z
2019-02-04T16:31:46.000Z
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string> &wordList) { int n = beginWord.size(), count = 0; if (n != endWord.size()) return 0; unordered_map<string, bool> words; for (auto &l:wordList) words[l] = true; queue<string> que; int size = 1; que.push(beginWord); string word = que.front(); while (!que.empty()) { word = que.front(); if (word == endWord) break; que.pop(); for (int i = 0; i < word.size(); ++i) { string temp = word; for (int j = 0; j < 26; ++j) { if ('a' + j == word[i]) continue; temp[i] = 'a' + j; if (words.find(temp) != words.end()) { que.push(temp); words.erase(temp); } } } --size; if (size == 0) { size = que.size(); ++count; } } return word == endWord ? count + 1 : 0; } };
30.846154
82
0.375727
ZintrulCre
205dbf81d1b2330b449caf7633e049408c5c1eba
189
cpp
C++
recipes/imagl/all/test_package/example.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
562
2019-09-04T12:23:43.000Z
2022-03-29T16:41:43.000Z
recipes/imagl/all/test_package/example.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
9,799
2019-09-04T12:02:11.000Z
2022-03-31T23:55:45.000Z
recipes/imagl/all/test_package/example.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
1,126
2019-09-04T11:57:46.000Z
2022-03-31T16:43:38.000Z
#include <iostream> #include <imaGL/imaGL.h> int main() { try { imaGL::CImaGL img("notfound.png"); } catch(...) { } std::cout << "It works!\n"; return 0; }
14.538462
42
0.502646
rockandsalt
206014f9e1269c5b0983deaea1dd932752f2a279
2,447
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcReferentTypeEnum.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
426
2015-04-12T10:00:46.000Z
2022-03-29T11:03:02.000Z
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcReferentTypeEnum.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
124
2015-05-15T05:51:00.000Z
2022-02-09T15:25:12.000Z
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcReferentTypeEnum.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
214
2015-05-06T07:30:37.000Z
2022-03-26T16:14:04.000Z
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/IFC4/include/IfcReferentTypeEnum.h" // TYPE IfcReferentTypeEnum = ENUMERATION OF (KILOPOINT ,MILEPOINT ,STATION ,USERDEFINED ,NOTDEFINED); shared_ptr<BuildingObject> IfcReferentTypeEnum::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcReferentTypeEnum> copy_self( new IfcReferentTypeEnum() ); copy_self->m_enum = m_enum; return copy_self; } void IfcReferentTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCREFERENTTYPEENUM("; } switch( m_enum ) { case ENUM_KILOPOINT: stream << ".KILOPOINT."; break; case ENUM_MILEPOINT: stream << ".MILEPOINT."; break; case ENUM_STATION: stream << ".STATION."; break; case ENUM_USERDEFINED: stream << ".USERDEFINED."; break; case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break; } if( is_select_type ) { stream << ")"; } } const std::wstring IfcReferentTypeEnum::toString() const { switch( m_enum ) { case ENUM_KILOPOINT: return L"KILOPOINT"; case ENUM_MILEPOINT: return L"MILEPOINT"; case ENUM_STATION: return L"STATION"; case ENUM_USERDEFINED: return L"USERDEFINED"; case ENUM_NOTDEFINED: return L"NOTDEFINED"; } return L""; } shared_ptr<IfcReferentTypeEnum> IfcReferentTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map ) { if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcReferentTypeEnum>(); } if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcReferentTypeEnum>(); } shared_ptr<IfcReferentTypeEnum> type_object( new IfcReferentTypeEnum() ); if( std_iequal( arg, L".KILOPOINT." ) ) { type_object->m_enum = IfcReferentTypeEnum::ENUM_KILOPOINT; } else if( std_iequal( arg, L".MILEPOINT." ) ) { type_object->m_enum = IfcReferentTypeEnum::ENUM_MILEPOINT; } else if( std_iequal( arg, L".STATION." ) ) { type_object->m_enum = IfcReferentTypeEnum::ENUM_STATION; } else if( std_iequal( arg, L".USERDEFINED." ) ) { type_object->m_enum = IfcReferentTypeEnum::ENUM_USERDEFINED; } else if( std_iequal( arg, L".NOTDEFINED." ) ) { type_object->m_enum = IfcReferentTypeEnum::ENUM_NOTDEFINED; } return type_object; }
34.464789
154
0.734369
AlexVlk
20605f6282406f6912e3e3f5bd55441cfc49d0b0
617
cpp
C++
mine/46-permutations.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
mine/46-permutations.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
mine/46-permutations.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> ans; void recursiveBody(vector<int>& nums, int sz, vector<int>& perm){ if(sz == 0) { ans.push_back(perm); return; } for(int i = 0; i < sz; ++i){ perm.push_back(nums[i]); nums.erase(nums.begin()+i); recursiveBody(nums, sz-1, perm); nums.insert(nums.begin()+i, perm.back()); perm.pop_back(); } } vector<vector<int>> permute(vector<int>& nums) { vector<int> perm; recursiveBody(nums, nums.size(), perm); return ans; } };
29.380952
70
0.504052
Junlin-Yin
206439cbbf0308036f2856125ffde097e5b80495
8,088
hpp
C++
keychain_lib/include/keychain_lib/secmod_protocol.hpp
jokefor300/array-io-keychain
1c281b76332af339f0456de51caf65cae9950c91
[ "MIT" ]
29
2018-03-21T09:21:18.000Z
2020-09-22T16:31:03.000Z
keychain_lib/include/keychain_lib/secmod_protocol.hpp
jokefor300/array-io-keychain
1c281b76332af339f0456de51caf65cae9950c91
[ "MIT" ]
119
2018-03-16T14:02:04.000Z
2019-04-16T21:16:32.000Z
keychain_lib/include/keychain_lib/secmod_protocol.hpp
jokefor300/array-io-keychain
1c281b76332af339f0456de51caf65cae9950c91
[ "MIT" ]
3
2018-03-21T15:00:16.000Z
2019-12-25T09:03:58.000Z
// Created by roman on 8/12/18. // #ifndef KEYCHAINAPP_KEYCHAIN_SEC_MOD_PROTOCOL_HPP #define KEYCHAINAPP_KEYCHAIN_SEC_MOD_PROTOCOL_HPP #include <string> #include <fc_light/variant.hpp> #include <fc_light/io/json.hpp> #include <fc_light/reflect/reflect.hpp> #include <fc_light/reflect/variant.hpp> #include "bitcoin_transaction.hpp" namespace keychain_app { using byte_seq_t = std::vector<char>; namespace secmod_commands { enum struct blockchain_secmod_te { unknown = 0, ethereum, bitcoin, ethereum_swap, //HACK: }; template<blockchain_secmod_te blockchain_type> struct transaction_view { using type = std::string; // if transaction cannot be parsed }; struct ethereum_trx_t { ethereum_trx_t() : chainid(0) {} std::string nonce, gasPrice, gas; int chainid; std::string to, value, data; }; template<> struct transaction_view<blockchain_secmod_te::ethereum> { struct secmod_command_ethereum { secmod_command_ethereum() {} secmod_command_ethereum(std::string &&from_, ethereum_trx_t &&trx_) : from(from_), trx_info(trx_) {} std::string from; ethereum_trx_t trx_info; }; using type = secmod_command_ethereum; }; template<> struct transaction_view<blockchain_secmod_te::ethereum_swap> { struct secmod_command_swap { enum struct action_te { create_swap = 0, refund, withdraw }; struct swap_t { action_te action; std::string hash; std::string address; std::string secret; }; secmod_command_swap() {} secmod_command_swap(std::string &&from_, ethereum_trx_t &&trx_, swap_t &&swap_info_) : from(from_), trx_info(trx_), swap_info(swap_info_) {} std::string from; ethereum_trx_t trx_info; swap_t swap_info; }; using type = secmod_command_swap; }; template<> struct transaction_view<blockchain_secmod_te::bitcoin> { struct secmod_command_bitcoin { secmod_command_bitcoin() {} secmod_command_bitcoin(std::string &&from_, bitcoin_transaction_t &&trx_) : from(from_), trx_info(trx_) {} std::string from; bitcoin_transaction_t trx_info; }; using type = secmod_command_bitcoin; }; enum struct events_te { unknown = 0, create_key, sign_trx, sign_hash, unlock, edit_key, remove_key, export_keys, import_keys, print_mnemonic, last }; template<events_te event> struct secmod_event { using params_t = void; }; template<> struct secmod_event<events_te::create_key> { struct params { params(): keyname(""){} params(params&& a): keyname(a.keyname){} std::string keyname; }; using params_t = params; }; template<> struct secmod_event<events_te::sign_trx> { struct params { params() : is_parsed(false), no_password(false), unlock_time(0) {} params(params&& a ):is_parsed(a.is_parsed), no_password(a.no_password), keyname(a.keyname), blockchain(a.blockchain), unlock_time(a.unlock_time), trx_view(a.trx_view) {} bool is_parsed; bool no_password; std::string keyname; blockchain_secmod_te blockchain; int unlock_time; fc_light::variant trx_view; template <blockchain_secmod_te blockchain_type> typename transaction_view<blockchain_type>::type get_trx_view() const { using return_t = typename transaction_view<blockchain_type>::type; return trx_view.as<return_t>(); } }; using params_t = params; }; template<> struct secmod_event<events_te::sign_hash> { struct params { params(): no_password(false), keyname(""), from(""), hash(""){}; params(params&& a): no_password(a.no_password), keyname(a.keyname), from(a.from), hash(a.hash){} bool no_password = false; std::string keyname; std::string from; std::string hash; }; using params_t = params; }; template<> struct secmod_event<events_te::unlock> { struct params { params(): no_password(false), unlock_time(0){} params(params&& a): no_password(a.no_password), keyname(a.keyname), unlock_time(a.unlock_time){} bool no_password; std::string keyname; int unlock_time; }; using params_t = params; }; template<> struct secmod_event<events_te::edit_key> { struct params { params() : unlock_time(0) {} params(params&& a): keyname(a.keyname), unlock_time(a.unlock_time){} std::string keyname; int unlock_time; }; using params_t = params; }; template<> struct secmod_event<events_te::remove_key> { struct params { params(params &&a): keyname(a.keyname){} std::string keyname; }; using params_t = params; }; template<> struct secmod_event<events_te::export_keys> { using params_t = void; }; template<> struct secmod_event<events_te::import_keys> { using params_t = void; }; template<> struct secmod_event<events_te::print_mnemonic> { using params_t = void; //TODO: will be implemented in future }; struct secmod_command { secmod_command() : etype(secmod_commands::events_te::unknown) {} events_te etype; fc_light::variant params; }; enum struct response_te { null = 0, password, boolean, canceled }; template <response_te response_type> struct secmod_response { using params_t = void; }; template <> struct secmod_response<response_te::password> { using params_t = byte_seq_t; }; template <> struct secmod_response<response_te::boolean> { using params_t = bool; }; struct secmod_response_common { secmod_response_common() : etype(secmod_commands::response_te::null) {} response_te etype; fc_light::variant params; }; } } FC_LIGHT_REFLECT_ENUM(keychain_app::secmod_commands::blockchain_secmod_te, (unknown)(ethereum)(bitcoin)(ethereum_swap)) FC_LIGHT_REFLECT_ENUM(keychain_app::secmod_commands::events_te, (unknown)(create_key)(sign_trx)(sign_hash)(unlock)(edit_key)(remove_key)(export_keys)(import_keys)(print_mnemonic)) FC_LIGHT_REFLECT_ENUM(keychain_app::secmod_commands::response_te, (null)(password)(boolean)(canceled)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::create_key>::params_t, (keyname)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::sign_trx>::params_t, (is_parsed)(no_password)(keyname)(blockchain)(unlock_time)(trx_view)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::sign_hash>::params_t, (no_password)(keyname)(from)(hash)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::unlock>::params_t, (no_password)(keyname)(unlock_time)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::edit_key>::params_t, (keyname)(unlock_time)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::remove_key>::params_t, (keyname)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::ethereum_trx_t, (nonce)(gasPrice)(gas)(to)(value)(data)(chainid)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::ethereum>::type, (from)(trx_info)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::bitcoin>::type, (from)(trx_info)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::ethereum_swap>::type, (from)(trx_info)(swap_info)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_command, (etype)(params)) FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_response_common, (etype)(params)) FC_LIGHT_REFLECT_ENUM( keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::ethereum_swap>::type::action_te, (create_swap)(refund)(withdraw)) FC_LIGHT_REFLECT( keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::ethereum_swap>::type::swap_t, (action)(hash)(address)(secret)) #endif //KEYCHAINAPP_KEYCHAIN_SEC_MOD_PROTOCOL_HPP
26.781457
193
0.740232
jokefor300
206455e8ab5621e90739dc80f9a12d67d0628933
1,703
hpp
C++
include/problem/composition_8.hpp
tsakiridis/deplusplus
383754182c929ab51d9af045bbf138d6d74c009c
[ "MIT" ]
null
null
null
include/problem/composition_8.hpp
tsakiridis/deplusplus
383754182c929ab51d9af045bbf138d6d74c009c
[ "MIT" ]
null
null
null
include/problem/composition_8.hpp
tsakiridis/deplusplus
383754182c929ab51d9af045bbf138d6d74c009c
[ "MIT" ]
null
null
null
#ifndef DE_OPTIMIZATION_PROBLEM_COMPOSITION_FUNCTION_8_HPP #define DE_OPTIMIZATION_PROBLEM_COMPOSITION_FUNCTION_8_HPP #include "problem/cec_composition_function.hpp" #include "problem/ackley.hpp" #include "problem/griewank.hpp" #include "problem/discus.hpp" #include "problem/rosenbrock.hpp" #include "problem/happycat.hpp" #include "problem/schaffer.hpp" namespace DE { namespace Problem { /*! * \class CompositionFunction8 * \brief Composition function 8 of CEC-2017 */ class CompositionFunction8 : public CECComposition<double> { public: CompositionFunction8(const std::size_t D, const char* shift_file = nullptr, const char* rotation_file = nullptr) : CECComposition<double>(D, "Composition Function 8") { auto bias = std::vector<double>{0.0, 100.0, 200.0, 300.0, 400.0, 500.0}; functions_ = {BasicFunction(new AckleyFunction(D), 10, 10, bias[0]), BasicFunction(new GriewankFunction(D), 20, 10, bias[1]), BasicFunction(new DiscusFunction(D), 30, 1e-6, bias[2]), BasicFunction(new RosenbrockFunction(D), 40, 1, bias[3]), BasicFunction(new HappyCatFunction(D), 50, 1, bias[4]), BasicFunction(new SchafferFunction(D), 60, 5e-4, bias[5])}; if (shift_file) for (std::size_t i = 0; i < functions_.size(); ++i) functions_[i].func->parse_shift_file(shift_file, i); if (rotation_file) for (std::size_t i = 0; i < functions_.size(); ++i) functions_[i].func->parse_rotation_file(rotation_file, i * D); } }; } // namespace Problem } // namespace DE #endif // DE_OPTIMIZATION_PROBLEM_COMPOSITION_FUNCTION_8_HPP
38.704545
77
0.669407
tsakiridis
206561929d985c270fafe9ca79f362fc0f9868a9
374
cpp
C++
ComputerGraphics/src/Main.cpp
gerrygoo/graficas
443832dc6820c0a93c8291831109e3248f57f9b0
[ "MIT" ]
null
null
null
ComputerGraphics/src/Main.cpp
gerrygoo/graficas
443832dc6820c0a93c8291831109e3248f57f9b0
[ "MIT" ]
null
null
null
ComputerGraphics/src/Main.cpp
gerrygoo/graficas
443832dc6820c0a93c8291831109e3248f57f9b0
[ "MIT" ]
null
null
null
// #include <string> // #include "scene_manager.h" // #include <glad/glad.h> // int main(int argc, char* argv[]) // { // scene_manager::start(argc, argv, "Hello, World!", 800, 800); // return 0; // } #include <iostream> #include "scene_manager.h" #include <vector> int main(int argc, char* argv[]) { scene_manager::start(argc, argv, "Hello World!", 1000, 1000); }
19.684211
65
0.631016
gerrygoo
206a5c78743dfa16273ef830cac78f9fc98e52c3
225
cc
C++
build/ARM/python/m5/internal/param_ClockDomain.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
build/ARM/python/m5/internal/param_ClockDomain.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
build/ARM/python/m5/internal/param_ClockDomain.i_init.cc
Jakgn/gem5_test
0ba7cc5213cf513cf205af7fc995cf679ebc1a3f
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" extern "C" { void init_param_ClockDomain(); } EmbeddedSwig embed_swig_param_ClockDomain(init_param_ClockDomain, "m5.internal._param_ClockDomain");
25
108
0.617778
Jakgn
206fce9b09872b55229c545460ca01e62d203ac9
3,152
cpp
C++
aws-cpp-sdk-ce/source/model/PlatformDifference.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-ce/source/model/PlatformDifference.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ce/source/model/PlatformDifference.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ce/model/PlatformDifference.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace CostExplorer { namespace Model { namespace PlatformDifferenceMapper { static const int HYPERVISOR_HASH = HashingUtils::HashString("HYPERVISOR"); static const int NETWORK_INTERFACE_HASH = HashingUtils::HashString("NETWORK_INTERFACE"); static const int STORAGE_INTERFACE_HASH = HashingUtils::HashString("STORAGE_INTERFACE"); static const int INSTANCE_STORE_AVAILABILITY_HASH = HashingUtils::HashString("INSTANCE_STORE_AVAILABILITY"); static const int VIRTUALIZATION_TYPE_HASH = HashingUtils::HashString("VIRTUALIZATION_TYPE"); PlatformDifference GetPlatformDifferenceForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == HYPERVISOR_HASH) { return PlatformDifference::HYPERVISOR; } else if (hashCode == NETWORK_INTERFACE_HASH) { return PlatformDifference::NETWORK_INTERFACE; } else if (hashCode == STORAGE_INTERFACE_HASH) { return PlatformDifference::STORAGE_INTERFACE; } else if (hashCode == INSTANCE_STORE_AVAILABILITY_HASH) { return PlatformDifference::INSTANCE_STORE_AVAILABILITY; } else if (hashCode == VIRTUALIZATION_TYPE_HASH) { return PlatformDifference::VIRTUALIZATION_TYPE; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<PlatformDifference>(hashCode); } return PlatformDifference::NOT_SET; } Aws::String GetNameForPlatformDifference(PlatformDifference enumValue) { switch(enumValue) { case PlatformDifference::HYPERVISOR: return "HYPERVISOR"; case PlatformDifference::NETWORK_INTERFACE: return "NETWORK_INTERFACE"; case PlatformDifference::STORAGE_INTERFACE: return "STORAGE_INTERFACE"; case PlatformDifference::INSTANCE_STORE_AVAILABILITY: return "INSTANCE_STORE_AVAILABILITY"; case PlatformDifference::VIRTUALIZATION_TYPE: return "VIRTUALIZATION_TYPE"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace PlatformDifferenceMapper } // namespace Model } // namespace CostExplorer } // namespace Aws
34.26087
116
0.650381
perfectrecall
2071919f1d637958bc0d7a11ee95de66e045a410
3,176
cpp
C++
modules/filters/src/detection/detectedObject.cpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
modules/filters/src/detection/detectedObject.cpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
modules/filters/src/detection/detectedObject.cpp
voxel-dot-at/toffy
e9f14b186cf57225ad9eae99f227f894f0e5f940
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Simon Vogl <svogl@voxel.at> Angel Merino-Sastre <amerino@voxel.at> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <boost/log/trivial.hpp> #include "toffy/detection/detectedObject.hpp" using namespace toffy::detection; using namespace cv; int DetectedObject::COUNTER = 0; DetectedObject::DetectedObject(): first_fc(-1) { id = COUNTER++; RNG rng(id); color = Scalar( rng.uniform(0,255), rng.uniform(0,255), rng.uniform(0,255) ); } DetectedObject::DetectedObject(const DetectedObject& object): id(object.id), color(object.color) { *this = object; /*contour = object.contour; contours = object.contours; hierarchy = object.hierarchy; mo = object.mo; massCenter = object.massCenter; idx = object.idx; size = object.size; first_fc = object.first_fc; first_cts = object.first_cts; first_ts = object.first_ts; fc = object.fc; cts = object.cts; ts = object.ts; size = object.size;*/ } DetectedObject::~DetectedObject() { while (record && !record->empty()) { delete *record->begin(); record->pop_front(); } } DetectedObject* DetectedObject::clone(const DetectedObject& object) { DetectedObject *newObject = new DetectedObject(object); return newObject; } DetectedObject& DetectedObject::operator=( const DetectedObject& newDO ) { contour = newDO.contour; contours = newDO.contours; hierarchy = newDO.hierarchy; mo = newDO.mo; massCenter = newDO.massCenter; idx = newDO.idx; size = newDO.size; first_fc = newDO.first_fc; first_cts = newDO.first_cts; first_ts = newDO.first_ts; fc = newDO.fc; cts = newDO.cts; ts = newDO.ts; size = newDO.size; massCenter3D = newDO.massCenter3D; massCenterZ = newDO.massCenterZ; return *this; } void DetectedObject::init() { if (record) { BOOST_LOG_TRIVIAL(warning) << "Detected object already initialized!"; } first_fc = fc; first_cts = cts; first_ts = ts; firstCenter = massCenter; size = contourArea(contour); record.reset(new boost::circular_buffer<detection::DetectedObject* >(10)); } void DetectedObject::update(const DetectedObject& newDO) { if (record->full()) { DetectedObject *last = record->back(); *last = *this; record->push_front(last); } else record->push_front(new DetectedObject(*this)); *this = newDO; //TODO Get new Stats here when object gets new state //3d points -> // pointTo3D(cv::Point point, float depthValue) or toffy::commons::pointTo3D(center, z, _cameraMatrix, depth->size()); }
25.821138
122
0.67034
voxel-dot-at
207342662282666246cb8a5668cbfc47b41a78d9
261
cpp
C++
recipes/platform.exceptions/all/test_package/test_package.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
562
2019-09-04T12:23:43.000Z
2022-03-29T16:41:43.000Z
recipes/platform.exceptions/all/test_package/test_package.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
9,799
2019-09-04T12:02:11.000Z
2022-03-31T23:55:45.000Z
recipes/platform.exceptions/all/test_package/test_package.cpp
rockandsalt/conan-center-index
d739adcec3e4dd4c250eff559ceb738e420673dd
[ "MIT" ]
1,126
2019-09-04T11:57:46.000Z
2022-03-31T16:43:38.000Z
#include <Platform.Exceptions.h> #include <iostream> using namespace Platform::Exceptions; auto main() -> int { try { Ensure::Always::ArgumentNotNull(nullptr); } catch (std::exception& e) { std::cout << e.what() << std::endl; } }
18.642857
49
0.605364
rockandsalt
2077a119247db1b7412879ef7d764425b631c1cc
840
hpp
C++
src/map.hpp
REPOmAN2v2/Mindstorm-rover
1529a02f246eaa5132be2b34bba27df6dc776ead
[ "MIT", "Unlicense" ]
null
null
null
src/map.hpp
REPOmAN2v2/Mindstorm-rover
1529a02f246eaa5132be2b34bba27df6dc776ead
[ "MIT", "Unlicense" ]
null
null
null
src/map.hpp
REPOmAN2v2/Mindstorm-rover
1529a02f246eaa5132be2b34bba27df6dc776ead
[ "MIT", "Unlicense" ]
null
null
null
#ifndef MAP_HPP_INCLUDED #define MAP_HPP_INCLUDED #include <vector> #include <utility> #include <queue> #include "cell.hpp" class Map { public: // The map is composed of a 2D vector of cells std::vector< std::vector< Cell > > cells; // Queue of map states (a new state is created everytime something changes // on the map) std::queue< std::vector< std::vector< Cell > > > history; Map(); explicit Map(int); explicit Map(int, int); Cell getCell(size_t y, size_t x); void updateRobotPos(std::pair<int,int> oldPos, std::pair<int,int> newPos); bool validCoord(int y, int x) {return !(y < 0 || x < 0 || y >= vCells || x >= hCells);}; std::pair<int,int> getDest(); size_t height() {return vCells;}; size_t width() {return hCells;}; private: // height and width of the map size_t hCells, vCells; void generateMaze(); }; #endif
26.25
89
0.680952
REPOmAN2v2
20783817b2a92a9eb6b7514b6567d1121da4aa8f
13,253
cpp
C++
ugene/src/corelibs/U2Formats/src/MSFFormat.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2Formats/src/MSFFormat.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2Formats/src/MSFFormat.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * 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. */ #include "MSFFormat.h" #include <U2Formats/DocumentFormatUtils.h> #include <U2Core/U2OpStatus.h> #include <U2Core/DNAAlphabet.h> #include <U2Core/IOAdapter.h> #include <U2Core/L10n.h> #include <U2Core/GObjectTypes.h> #include <U2Core/MAlignmentObject.h> #include <U2Core/TextUtils.h> #include <U2Core/MSAUtils.h> #include <U2Core/U2SafePoints.h> #include <U2Core/U2AlphabetUtils.h> #include <U2Core/U2DbiUtils.h> namespace U2 { const int MSFFormat::CHECK_SUM_MOD = 10000; const QByteArray MSFFormat::MSF_FIELD = "MSF:"; const QByteArray MSFFormat::CHECK_FIELD = "Check:"; const QByteArray MSFFormat::LEN_FIELD = "Len:"; const QByteArray MSFFormat::NAME_FIELD = "Name:"; const QByteArray MSFFormat::TYPE_FIELD = "Type:"; const QByteArray MSFFormat::WEIGHT_FIELD = "Weight:"; const QByteArray MSFFormat::TYPE_VALUE_PROTEIN = "P"; const QByteArray MSFFormat::TYPE_VALUE_NUCLEIC = "N"; const double MSFFormat::WEIGHT_VALUE = 1.0; const QByteArray MSFFormat::END_OF_HEADER_LINE = ".."; const QByteArray MSFFormat::SECTION_SEPARATOR = "//"; const int MSFFormat::CHARS_IN_ROW = 50; const int MSFFormat::CHARS_IN_WORD = 10; /* TRANSLATOR U2::MSFFormat */ //TODO: recheck if it does support streaming! Fix isObjectOpSupported if not! MSFFormat::MSFFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlag_SupportWriting, QStringList("msf")) { formatName = tr("MSF"); supportedObjectTypes+=GObjectTypes::MULTIPLE_ALIGNMENT; formatDescription = tr("MSF format is used to store multiple aligned sequences. Files include the sequence name and the sequence itself, which is usually aligned with other sequences in the file."); } static bool getNextLine(IOAdapter* io, QByteArray& line) { static int READ_BUFF_SIZE = 1024; QByteArray readBuffer(READ_BUFF_SIZE, '\0'); char* buff = readBuffer.data(); qint64 len; bool eolFound = false, eof = false; while (!eolFound) { len = io->readLine(buff, READ_BUFF_SIZE, &eolFound); if (len < READ_BUFF_SIZE && !eolFound) { eolFound = eof = true; } line += readBuffer; } if (len != READ_BUFF_SIZE) { line.resize(line.size() + len - READ_BUFF_SIZE); } line = line.simplified(); return eof; } static QByteArray getField(const QByteArray& line, const QByteArray& name) { int p = line.indexOf(name); if (p >= 0) { p += name.length(); if (line[p] == ' ') ++p; int q = line.indexOf(' ', p); if (q >= 0) return line.mid(p, q - p); else return line.mid(p); } return QByteArray(); } int MSFFormat::getCheckSum(const QByteArray& seq) { int sum = 0; static int CHECK_SUM_COUNTER_MOD = 57; for (int i = 0; i < seq.length(); ++i) { char ch = seq[i]; if (ch >= 'a' && ch <= 'z') { ch = ch + 'A' - 'a'; } sum = (sum + ((i % CHECK_SUM_COUNTER_MOD) + 1) * ch) % MSFFormat::CHECK_SUM_MOD; } return sum; } void MSFFormat::load(IOAdapter* io, QList<GObject*>& objects, U2OpStatus& ti) { MAlignment al(io->getURL().baseFileName()); //skip comments int checkSum = -1; while (!ti.isCoR() && checkSum < 0) { QByteArray line; if (getNextLine(io, line)) { ti.setError(MSFFormat::tr("Incorrect format")); return; } if (line.endsWith(END_OF_HEADER_LINE)) { bool ok; checkSum = getField(line, CHECK_FIELD).toInt(&ok); if (!ok || checkSum < 0) checkSum = CHECK_SUM_MOD; } ti.setProgress(io->getProgress()); } //read info int sum = 0; QMap <QString, int> seqs; while (!ti.isCoR()) { QByteArray line; if (getNextLine(io, line)) { ti.setError(MSFFormat::tr("Unexpected end of file")); return; } if (line.startsWith(SECTION_SEPARATOR)) break; bool ok = false; QString name = QString::fromLocal8Bit(getField(line, NAME_FIELD).data()); if (name.isEmpty()) { continue; } int check = getField(line, CHECK_FIELD).toInt(&ok); if (!ok || check < 0) { sum = check = CHECK_SUM_MOD; } seqs.insert(name, check); al.addRow(MAlignmentRow(name)); if (sum < CHECK_SUM_MOD) { sum = (sum + check) % CHECK_SUM_MOD; } ti.setProgress(io->getProgress()); } if (checkSum < CHECK_SUM_MOD && sum < CHECK_SUM_MOD && sum != checkSum) { ti.setError(MSFFormat::tr("Check sum test failed")); return; } //read data bool eof = false; while (!eof && !ti.isCoR()) { QByteArray line; eof = getNextLine(io, line); if (line.isEmpty()) { continue; } int i = 0, n = al.getNumRows(); for (; i < n; i++) { const MAlignmentRow& row = al.getRow(i); QByteArray t = row.getName().toLocal8Bit(); if (line.startsWith(t) && line[t.length()] == ' ') { break; } } if (i == n) { continue; } for (int q, p = line.indexOf(' ') + 1; p > 0; p = q + 1) { q = line.indexOf(' ', p); QByteArray subSeq = (q < 0) ? line.mid(p) : line.mid(p, q - p); al.appendChars(i, subSeq.constData(), subSeq.length()); } ti.setProgress(io->getProgress()); } //checksum for (int i=0; i<al.getNumRows(); i++) { const MAlignmentRow& row = al.getRow(i); int expectedCheckSum = seqs[row.getName()]; int sequenceCheckSum = getCheckSum(row.toByteArray(al.getLength())); if ( expectedCheckSum < CHECK_SUM_MOD && sequenceCheckSum != expectedCheckSum) { ti.setError(MSFFormat::tr("Check sum test failed")); return; } al.replaceChars(i, '.', MAlignment_GapChar); al.replaceChars(i, '~', MAlignment_GapChar); } U2AlphabetUtils::assignAlphabet(al); CHECK_EXT(al.getAlphabet() != NULL, ti.setError(MSFFormat::tr("Alphabet unknown")), ); MAlignmentObject* obj = new MAlignmentObject(al); objects.append(obj); } Document* MSFFormat::loadDocument(IOAdapter* io, const U2DbiRef& dbiRef, const QVariantMap& fs, U2OpStatus& os){ QList<GObject*> objs; load(io, objs, os); CHECK_OP_EXT(os, qDeleteAll(objs), NULL); return new Document(this, io->getFactory(), io->getURL(), dbiRef, objs, fs); } static bool writeBlock(IOAdapter *io, U2OpStatus& ti, const QByteArray& buf) { int len = io->writeBlock(buf); if (len != buf.length()) { ti.setError(L10N::errorTitle()); return true; } return false; } void MSFFormat::storeDocument(Document* d, IOAdapter* io, U2OpStatus& os) { MAlignmentObject* obj = NULL; if((d->getObjects().size() != 1) || ((obj = qobject_cast<MAlignmentObject*>(d->getObjects().first())) == NULL)) { os.setError("No data to write;"); return; } QList<GObject*> als; als << obj; QMap< GObjectType, QList<GObject*> > objectsMap; objectsMap[GObjectTypes::MULTIPLE_ALIGNMENT] = als; storeEntry(io, objectsMap, os); CHECK_EXT(!os.isCoR(), os.setError(L10N::errorWritingFile(d->getURL())), ); } void MSFFormat::storeEntry(IOAdapter *io, const QMap< GObjectType, QList<GObject*> > &objectsMap, U2OpStatus &os) { SAFE_POINT(objectsMap.contains(GObjectTypes::MULTIPLE_ALIGNMENT), "MSF entry storing: no alignment", ); const QList<GObject*> &als = objectsMap[GObjectTypes::MULTIPLE_ALIGNMENT]; SAFE_POINT(1 == als.size(), "MSF entry storing: alignment objects count error", ); const MAlignmentObject* obj = dynamic_cast<MAlignmentObject*>(als.first()); SAFE_POINT(NULL != obj, "MSF entry storing: NULL alignment object", ); const MAlignment& ma = obj->getMAlignment(); //precalculate seq writing params int maxNameLen = 0, maLen = ma.getLength(), checkSum = 0; static int maxCheckSumLen = 4; QMap <QString, int> checkSums; foreach(const MAlignmentRow& row , ma.getRows()) { QByteArray sequence = row.toByteArray(maLen).replace(MAlignment_GapChar, '.'); int seqCheckSum = getCheckSum(sequence); checkSums.insert(row.getName(), seqCheckSum); checkSum = (checkSum + seqCheckSum) % CHECK_SUM_MOD; maxNameLen = qMax(maxNameLen, row.getName().length()); } int maxLengthLen = QString::number(maLen).length(); //write first line QByteArray line = " " + MSF_FIELD; line += " " + QByteArray::number(maLen); line += " " + TYPE_FIELD; line += " " + ( obj->getAlphabet()->isAmino() ? TYPE_VALUE_PROTEIN : TYPE_VALUE_NUCLEIC ); line += " " + QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm"); line += " " + CHECK_FIELD; line += " " + QByteArray::number(checkSum); line += " " + END_OF_HEADER_LINE + "\n\n"; if (writeBlock(io, os, line)) return; //write info foreach(const MAlignmentRow& row, ma.getRows()) { QByteArray line = " " + NAME_FIELD; line += " " + QString(row.getName()).replace(' ', '_').leftJustified(maxNameLen+1); // since ' ' is a delimeter for MSF parser spaces in name not suppoted line += " " + LEN_FIELD; line += " " + QString("%1").arg(maLen, -maxLengthLen); line += " " + CHECK_FIELD; line += " " + QString("%1").arg(checkSums[row.getName()], -maxCheckSumLen); line += " " + WEIGHT_FIELD; line += " " + QByteArray::number(WEIGHT_VALUE) + "\n"; if (writeBlock(io, os, line)) { return; } } if (writeBlock(io, os, "\n" + SECTION_SEPARATOR + "\n\n")) { return; } for (int i = 0; !os.isCoR() && i < maLen; i += CHARS_IN_ROW) { /* write numbers */ { QByteArray line(maxNameLen + 2, ' '); QString t = QString("%1").arg(i + 1); QString s = QString("%1").arg(i + CHARS_IN_ROW < maLen ? i + CHARS_IN_ROW : maLen); int r = maLen - i < CHARS_IN_ROW ? maLen % CHARS_IN_ROW : CHARS_IN_ROW; r += (r - 1) / CHARS_IN_WORD - (t.length() + s.length()); line += t; if (r > 0) { line += QByteArray(r, ' '); line += s; } line += '\n'; if (writeBlock(io, os, line)) { return; } } //write sequence foreach(const MAlignmentRow& row, ma.getRows()) { QByteArray line = row.getName().toLocal8Bit(); line.replace(' ', '_'); // since ' ' is a delimiter for MSF parser spaces in name not supported line = line.leftJustified(maxNameLen+1); for (int j = 0; j < CHARS_IN_ROW && i + j < maLen; j += CHARS_IN_WORD) { line += ' '; int nChars = qMin(CHARS_IN_WORD, maLen - (i + j)); line += row.mid(i + j, nChars).toByteArray(nChars).replace(MAlignment_GapChar, '.'); } line += '\n'; if (writeBlock(io, os, line)) { return; } } if (writeBlock(io, os, "\n")) { return; } } } FormatCheckResult MSFFormat::checkRawData(const QByteArray& rawData, const GUrl&) const { const char* data = rawData.constData(); int size = rawData.size(); bool hasBinaryData = TextUtils::contains(TextUtils::BINARY, data, size); if (hasBinaryData) { return FormatDetection_NotMatched; } if (rawData.contains("MSF:") || rawData.contains("!!AA_MULTIPLE_ALIGNMENT 1.0") || rawData.contains("!!NA_MULTIPLE_ALIGNMENT 1.0") || (rawData.contains("Name:") && rawData.contains("Len:") && rawData.contains("Check:") && rawData.contains("Weight:"))) { return FormatDetection_VeryHighSimilarity; } if (rawData.contains("GDC ")) { return FormatDetection_AverageSimilarity; } //MSF documents may contain unlimited number of comment lines in header -> //it is impossible to determine if file has MSF format by some predefined //amount of raw data read from it. if (rawData.contains("GCG ") || rawData.contains("MSF ")) { return FormatDetection_LowSimilarity; } return FormatDetection_VeryLowSimilarity; } } //namespace U2
35.722372
202
0.600015
iganna
207933cf4a9423cc0d3fde9eb79e0c3c1e95c057
213
cpp
C++
DSA/Bit Manipulation/5.Find position of the only set bit.cpp
mridul8920/winter-of-contributing
9ee7c32cf6568c01f6a5263f4130e8edebb442fb
[ "MIT" ]
null
null
null
DSA/Bit Manipulation/5.Find position of the only set bit.cpp
mridul8920/winter-of-contributing
9ee7c32cf6568c01f6a5263f4130e8edebb442fb
[ "MIT" ]
null
null
null
DSA/Bit Manipulation/5.Find position of the only set bit.cpp
mridul8920/winter-of-contributing
9ee7c32cf6568c01f6a5263f4130e8edebb442fb
[ "MIT" ]
null
null
null
int findPosition(int N) { int pos = 0, count = 0; while (N != 0) { if (N & 1 == 1) { count++; } pos++; N = N >> 1; } if (count == 0 || count > 1) { return -1; } return pos; }
14.2
32
0.399061
mridul8920
207cf53ad626a85fd8461da773ae0dd74669854a
10,573
cpp
C++
WTesterClient/widget_answer.cpp
RockRockWhite/WTester
50a9de8ba7c48738eb054680d6eae0a2fc0c06e3
[ "MIT" ]
null
null
null
WTesterClient/widget_answer.cpp
RockRockWhite/WTester
50a9de8ba7c48738eb054680d6eae0a2fc0c06e3
[ "MIT" ]
null
null
null
WTesterClient/widget_answer.cpp
RockRockWhite/WTester
50a9de8ba7c48738eb054680d6eae0a2fc0c06e3
[ "MIT" ]
null
null
null
#include "widget_answer.h" #include "ui_widget_answer.h" #include <QMessageBox> #include <cmath> #include <QTimer> #include <QTextEdit> #include <QCheckBox> #include <QTcpSocket> #pragma execution_character_set("utf-8") extern QStringList question; extern QString time; QString errorNum; QStringList answer,answer_u,empty,grade; QLabel* imageLabel; int m,h,question_left_count=0; int size_y=5,totalGrade=0,totalGrade_u=0; QTimer* timer=new QTimer(); widget_answer::widget_answer(QWidget *parent) : QWidget(parent), ui(new Ui::widget_answer) { ui->setupUi(this); QObject::connect(timer,SIGNAL(timeout()),this,SLOT(timing())); imageLabel = new QLabel(this); ui->scrollArea->setWidgetResizable(1); } widget_answer::~widget_answer() { delete ui; } void widget_answer::init() { m=time.toInt()%60; h=(time.toInt()-h)/60; question_left_count=question.count()-1; //设置时间 this->ui->timeEdit->setTime(QTime(h,m,0)); //启动倒计时 timer->start(1000); size_y=0; totalGrade=0; totalGrade_u=0; errorNum=""; //清理链表 answer.clear(); grade.clear(); empty.clear(); //释放内存 delete imageLabel; //防止空指针 imageLabel=0; imageLabel = new QLabel(this); //重新设置按钮可用 ui->pushButton_ok->setEnabled(1); this->fresh(); } void widget_answer::timing() { if(ui->timeEdit->time().hour()==0&&ui->timeEdit->time().minute()==0&&ui->timeEdit->time().second()==0) { QMessageBox::information(this,"","时间结束"); for(int i=0;i<question_left_count;i++) { QCheckBox *checkBoxA=QObject::findChild<QCheckBox *>("QCheckBoxA"+QString::number(i)); QCheckBox *checkBoxB=QObject::findChild<QCheckBox *>("QCheckBoxB"+QString::number(i)); QCheckBox *checkBoxC=QObject::findChild<QCheckBox *>("QCheckBoxC"+QString::number(i)); QCheckBox *checkBoxD=QObject::findChild<QCheckBox *>("QCheckBoxD"+QString::number(i)); bool isEmpty=1; QString a=""; //选择A if(checkBoxA->isChecked()) { a=a+"A"; isEmpty=0; } //选择B if(checkBoxB->isChecked()) { if(isEmpty) { a="B"; } else { a=a+",B"; } isEmpty=0; } //选择C if(checkBoxC->isChecked()) { if(isEmpty) { a="C"; } else { a=a+",C"; } isEmpty=0; } //选择D if(checkBoxD->isChecked()) { if(isEmpty) { a="D"; } else { a=a+",D"; } isEmpty=0; } //储存答案 if(isEmpty) { answer_u<<"EMPTY"; empty<<QString::number(i+1); } else { answer_u<<a; } } if(empty.isEmpty()) { QMessageBox::information(this,"恭喜","没有漏题!"); } else { QString empty_num; for(int n=0;n<empty.count();n++) { if(n==0) { empty_num=empty[n]; } else { empty_num=empty_num+" "+empty[n]; } } QMessageBox::information(this,"提示",empty_num+"题还没有作答!"); } ui->pushButton_ok->setEnabled(0); this->check(); timer->stop(); } else { ui->timeEdit->setTime(ui->timeEdit->time().addSecs(-1)); } } void widget_answer::fresh() { for(int i=0;i<question_left_count;i++) { size_y+=350; //创建题目编辑框 QTextEdit *textEdit=new QTextEdit(); textEdit ->setObjectName("QLineEdit"+QString::number(i)); textEdit->setFont(QFont("Microsoft YaHei", 12, QFont::Normal)); textEdit->setGeometry(20,5+350*i,620,150); textEdit->setParent( imageLabel); textEdit->setEnabled(0); //读取题目 int n=rand()%(question_left_count-i); QStringList q_data=question[n].split("/"); question.removeAt(n); if(q_data[5]=="0") { textEdit->setText(QString::number(i+1)+"."+q_data[0]+"(单选) "+q_data[7]+"分"); } else { textEdit->setText(QString::number(i+1)+"."+q_data[0]+"(多选) "+q_data[7]+"分"); } //创建答案选择框 //A QCheckBox *checkBoxA=new QCheckBox("A."+q_data[1]+" "); checkBoxA->setObjectName("QCheckBoxA"+QString::number(i)); checkBoxA->setFont(QFont("Microsoft YaHei", 12, QFont::Normal)); checkBoxA->setParent( imageLabel); checkBoxA->setGeometry(30,5+350*i+150,620,50); //B QCheckBox *checkBoxB=new QCheckBox("B."+q_data[2]+" "); checkBoxB->setObjectName("QCheckBoxB"+QString::number(i)); checkBoxB->setFont(QFont("Microsoft YaHei", 12, QFont::Normal)); checkBoxB->setParent(imageLabel); checkBoxB->setGeometry(30,5+350*i+200,620,50); //C QCheckBox *checkBoxC=new QCheckBox("C."+q_data[3]+" "); checkBoxC->setObjectName("QCheckBoxC"+QString::number(i)); checkBoxC->setFont(QFont("Microsoft YaHei", 12, QFont::Normal)); checkBoxC->setParent( imageLabel); checkBoxC->setGeometry(30,5+350*i+250,620,50); //D QCheckBox *checkBoxD=new QCheckBox("D."+q_data[4]+" "); checkBoxD->setObjectName("QCheckBoxD"+QString::number(i)); checkBoxD->setFont(QFont("Microsoft YaHei", 12, QFont::Normal)); checkBoxD->setParent( imageLabel); checkBoxD->setGeometry(30,5+350*i+300,620,50); //储存答案 answer<<q_data[6]; grade<<q_data[7]; } //调整滚动框 QPixmap pixmap(":/ui/nothing"); pixmap = pixmap.scaled(620, size_y); imageLabel->setPixmap(pixmap); ui->scrollArea->setWidget(imageLabel); } void widget_answer::on_pushButton_ok_clicked() { QMessageBox msgBox; empty.clear(); if(msgBox.question(this,"提交答案","确定提交您的答案,若提交将不可修改?")==QMessageBox::Yes) { for(int i=0;i<question_left_count;i++) { QCheckBox *checkBoxA=QObject::findChild<QCheckBox *>("QCheckBoxA"+QString::number(i)); QCheckBox *checkBoxB=QObject::findChild<QCheckBox *>("QCheckBoxB"+QString::number(i)); QCheckBox *checkBoxC=QObject::findChild<QCheckBox *>("QCheckBoxC"+QString::number(i)); QCheckBox *checkBoxD=QObject::findChild<QCheckBox *>("QCheckBoxD"+QString::number(i)); bool isEmpty=1; QString a=""; //选择A if(checkBoxA->isChecked()) { a=a+"A"; isEmpty=0; } //选择B if(checkBoxB->isChecked()) { if(isEmpty) { a="B"; } else { a=a+",B"; } isEmpty=0; } //选择C if(checkBoxC->isChecked()) { if(isEmpty) { a="C"; } else { a=a+",C"; } isEmpty=0; } //选择D if(checkBoxD->isChecked()) { if(isEmpty) { a="D"; } else { a=a+",D"; } isEmpty=0; } //储存答案 if(isEmpty) { answer_u<<"EMPTY"; empty<<QString::number(i+1); } else { answer_u<<a; QMessageBox::information(this,"",a); } } if(empty.isEmpty()) { QMessageBox::information(this,"恭喜","没有漏题!"); this->check(); ui->pushButton_ok->setEnabled(0); } else { QString empty_num; for(int n=0;n<empty.count();n++) { if(n==0) { empty_num=empty[n]; } else { empty_num=empty_num+" "+empty[n]; } } if(msgBox.question(this,"警告",empty_num+"题还没有作答,确认提交?")==QMessageBox::Yes) { this->check(); ui->pushButton_ok->setEnabled(0); } else { } } } } void widget_answer::check() { for(int i=0;i<question_left_count;i++) { if(answer_u[i]==answer[i]) { QString g=grade[i]; totalGrade_u+=g.toFloat(); } else { errorNum+=" "+QString::number(i+1); } } extern QTcpSocket* tcpSocket; extern QString loginedID; extern QString qusetionName; QDateTime current_date_time =QDateTime::currentDateTime(); QString date =current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz ddd"); tcpSocket->write("GRADE|"+loginedID.toUtf8()+"|"+qusetionName.toUtf8()+" 得分:"+QString::number(totalGrade_u).toUtf8()+" 完成时间:"+date.toUtf8()); if(tcpSocket->waitForReadyRead()) { QString d=tcpSocket->readAll(); } else { QMessageBox::information(this,"提交成绩失败","服务器连接超时,请检查您的网络配置."); } QMessageBox::information(this,"得分","您的得分为:"+QString::number(totalGrade_u)+"\n错误题号:"+errorNum); }
27.823684
207
0.449352
RockRockWhite
207d572ba60eeb4b1900d9ccacff00a0cb24ca2e
600
cpp
C++
plugins/single_plugins/autostart.cpp
SirCmpwn/wayfire
007452f6ccc07ceca51879187bba142431832382
[ "MIT" ]
3
2019-01-16T14:43:24.000Z
2019-10-09T10:07:33.000Z
plugins/single_plugins/autostart.cpp
SirCmpwn/wayfire
007452f6ccc07ceca51879187bba142431832382
[ "MIT" ]
null
null
null
plugins/single_plugins/autostart.cpp
SirCmpwn/wayfire
007452f6ccc07ceca51879187bba142431832382
[ "MIT" ]
1
2019-05-07T09:46:58.000Z
2019-05-07T09:46:58.000Z
#include <plugin.hpp> #include "../../shared/config.hpp" #include <core.hpp> class wayfire_autostart : public wayfire_plugin_t { public: void init(wayfire_config *config) { /* make sure we are run only when adding the first output */ if (core->get_next_output(output) != output) return; auto section = config->get_section("autostart"); for (const auto& command : section->options) core->run(command.second.c_str()); } }; extern "C" { wayfire_plugin_t *newInstance() { return new wayfire_autostart(); } }
21.428571
68
0.613333
SirCmpwn
2081557d8fa7550407dbe187a0206f3a7139fc53
6,493
cpp
C++
third_party/CppAD/test_more/general/sparse_sub_hes.cpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
1
2019-11-05T02:23:47.000Z
2019-11-05T02:23:47.000Z
third_party/CppAD/test_more/general/sparse_sub_hes.cpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
third_party/CppAD/test_more/general/sparse_sub_hes.cpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
1
2019-11-05T02:23:51.000Z
2019-11-05T02:23:51.000Z
/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-18 Bradley M. Bell CppAD is distributed under the terms of the Eclipse Public License Version 2.0. This Source Code may also be made available under the following Secondary License when the conditions for such availability set forth in the Eclipse Public License, Version 2.0 are satisfied: GNU General Public License, Version 2.0 or later. ---------------------------------------------------------------------------- */ /* $begin sparse_sub_hes.cpp$$ $spell $$ $section Sparse Hessian on Subset of Variables: Example and Test$$ $head Purpose$$ This example uses a $cref/column subset/sparse_hessian/p/Column Subset/$$ of the sparsity pattern to compute the Hessian for a subset of the variables. The values in the rest of the sparsity pattern do not matter. $head See Also$$ $cref sub_sparse_hes.cpp$$ $code $comment%example/sparse/sparse_sub_hes.cpp%0%// BEGIN C++%// END C++%1%$$ $$ $end */ // BEGIN C++ # include <cppad/cppad.hpp> namespace { // BEGIN_EMPTY_NAMESPACE // -------------------------------------------------------------------------- void record_function(CppAD::ADFun<double>& f, size_t n) { // must be greater than or equal 3; see n_sweep below assert( n >= 3 ); // using CppAD::AD; typedef CppAD::vector< AD<double> > a_vector; // // domain space vector a_vector a_x(n); for(size_t j = 0; j < n; j++) a_x[j] = AD<double> (0); // declare independent variables and starting recording CppAD::Independent(a_x); // range space vector size_t m = 1; a_vector a_y(m); a_y[0] = 0.0; for(size_t j = 1; j < n; j++) a_y[0] += a_x[j-1] * a_x[j] * a_x[j]; // create f: x -> y and stop tape recording // (without executing zero order forward calculation) f.Dependent(a_x, a_y); // return; } // -------------------------------------------------------------------------- bool test_set(const char* color_method) { bool ok = true; // typedef CppAD::vector< double > d_vector; typedef CppAD::vector<size_t> i_vector; typedef CppAD::vector< std::set<size_t> > s_vector; // size_t n = 12; CppAD::ADFun<double> f; record_function(f, n); // // sparsity patteren for the sub-set of variables we are computing // the hessian w.r.t. size_t n_sub = 4; s_vector r(n); for(size_t j = 0; j < n_sub; j++) { assert( r[j].empty() ); r[j].insert(j); } // store forward sparsity for J(x) = F^{(1)} (x) * R f.ForSparseJac(n_sub, r); // compute sparsity pattern for H(x) = (S * F)^{(2)} ( x ) * R s_vector s(1); assert( s[0].empty() ); s[0].insert(0); bool transpose = true; s_vector h = f.RevSparseHes(n_sub, s, transpose); // set the row and column indices that correspond to lower triangle i_vector row, col; for(size_t i = 0; i < n_sub; i++) { if( i > 0 ) { // diagonal element row.push_back(i); col.push_back(i); // lower diagonal element row.push_back(i); col.push_back(i-1); } } // weighting for the Hessian d_vector w(1); w[0] = 1.0; // compute Hessian CppAD::sparse_hessian_work work; work.color_method = color_method; d_vector x(n), hes( row.size() ); for(size_t j = 0; j < n; j++) x[j] = double(j+1); f.SparseHessian(x, w, h, row, col, hes, work); // check the values in the sparse hessian for(size_t ell = 0; ell < row.size(); ell++) { size_t i = row[ell]; size_t j = col[ell]; if( i == j ) ok &= hes[ell] == 2.0 * x[i-1]; else { ok &= j+1 == i; ok &= hes[ell] == 2.0 * x[i]; } } return ok; } // -------------------------------------------------------------------------- bool test_bool(const char* color_method) { bool ok = true; // typedef CppAD::vector< double > d_vector; typedef CppAD::vector<size_t> i_vector; typedef CppAD::vector<bool> s_vector; // size_t n = 12; CppAD::ADFun<double> f; record_function(f, n); // // sparsity patteren for the sub-set of variables we are computing // the hessian w.r.t. size_t n_sub = 4; s_vector r(n * n_sub); for(size_t i = 0; i < n; i++) { for(size_t j = 0; j < n_sub; j++) r[ i * n_sub + j ] = (i == j); } // store forward sparsity for J(x) = F^{(1)} (x) * R f.ForSparseJac(n_sub, r); // compute sparsity pattern for H(x) = (S * F)^{(2)} ( x ) * R s_vector s(1); s[0] = true; bool transpose = true; s_vector h = f.RevSparseHes(n_sub, s, transpose); // set the row and column indices that correspond to lower triangle i_vector row, col; for(size_t i = 0; i < n_sub; i++) { if( i > 0 ) { // diagonal element row.push_back(i); col.push_back(i); // lower diagonal element row.push_back(i); col.push_back(i-1); } } // weighting for the Hessian d_vector w(1); w[0] = 1.0; // extend sparsity pattern (values in extended columns do not matter) s_vector h_extended(n * n); for(size_t i = 0; i < n; i++) { for(size_t j = 0; j < n_sub; j++) h_extended[ i * n + j ] = h[ i * n_sub + j ]; for(size_t j = n_sub; j < n; j++) h_extended[ i * n + j ] = false; } // compute Hessian CppAD::sparse_hessian_work work; work.color_method = color_method; d_vector x(n), hes( row.size() ); for(size_t j = 0; j < n; j++) x[j] = double(j+1); f.SparseHessian(x, w, h_extended, row, col, hes, work); // check the values in the sparse hessian for(size_t ell = 0; ell < row.size(); ell++) { size_t i = row[ell]; size_t j = col[ell]; if( i == j ) ok &= hes[ell] == 2.0 * x[i-1]; else { ok &= j+1 == i; ok &= hes[ell] == 2.0 * x[i]; } } return ok; } } // END_EMPTY_NAMESPACE bool sparse_sub_hes(void) { bool ok = true; ok &= test_set("cppad.symmetric"); ok &= test_set("cppad.general"); // ok &= test_bool("cppad.symmetric"); ok &= test_bool("cppad.general"); return ok; } // END C++
28.857778
79
0.525027
eric-heiden
2083b0b313c271d325b3c26f93d5e7b738e8d634
657
cpp
C++
DxLibEngine/base/Input.cpp
darknesswind/LiteSTG
ec24641948369e6ee1a3bdcc0d6b78515f1a0374
[ "MIT" ]
2
2015-09-11T08:17:20.000Z
2018-03-13T07:21:15.000Z
DxLibEngine/base/Input.cpp
darknesswind/LiteSTG
ec24641948369e6ee1a3bdcc0d6b78515f1a0374
[ "MIT" ]
null
null
null
DxLibEngine/base/Input.cpp
darknesswind/LiteSTG
ec24641948369e6ee1a3bdcc0d6b78515f1a0374
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Input.h" LInput::LInput(void) : m_nJoyNum(0) { m_curKeyState.fill(0); m_keyList.fill(KeyState::None); m_logicKeyMap.fill(Keys::None); m_nJoyNum = DxLib::GetJoypadNum(); } LInput::~LInput(void) { } bool LInput::update() { const bool bSucceed = (0 == DxLib::GetHitKeyStateAll(m_curKeyState.data())); for (int i = 0; i < KeyCount; ++i) { // keyList[i] = (KeyState)(((keyList[i] | 2) == 2 ? 0 : 2) | curKeyState[i]); m_keyList[i] = static_cast<KeyState>(((static_cast<uchar>(m_keyList[i]) << 1) & 0x2) | m_curKeyState[i]); } CheckRes(DxLib::GetMousePoint(&m_mousePos.rx(), &m_mousePos.ry())); return bSucceed; }
22.655172
107
0.656012
darknesswind
20891035a5804095b2634ce802a9eb9d4f7f906b
2,244
cpp
C++
Source/Application.cpp
michal-z/PerfExperiments
4431a74cb90407d7cd3645c4f218eaccd8516ea1
[ "MIT" ]
1
2021-11-07T07:22:47.000Z
2021-11-07T07:22:47.000Z
Source/Application.cpp
michal-z/MyPerfExperiments
4431a74cb90407d7cd3645c4f218eaccd8516ea1
[ "MIT" ]
null
null
null
Source/Application.cpp
michal-z/MyPerfExperiments
4431a74cb90407d7cd3645c4f218eaccd8516ea1
[ "MIT" ]
null
null
null
#include "Pch.h" #include "Application.h" FApplication GApp; void FApplication::Initialize() { QueryPerformanceCounter(&StartCounter); QueryPerformanceFrequency(&Frequency); SetProcessDPIAware(); MakeWindow(1280, 720); } void FApplication::Update() { UpdateFrameTime(); } double FApplication::GetTime() { LARGE_INTEGER Counter; QueryPerformanceCounter(&Counter); return (Counter.QuadPart - StartCounter.QuadPart) / (double)Frequency.QuadPart; } void FApplication::UpdateFrameTime() { static double LastTime = -1.0; static double LastFpsTime = 0.0; static unsigned FpsFrame = 0; if (LastTime < 0.0) { LastTime = GetTime(); LastFpsTime = LastTime; } FrameTime = GetTime(); FrameDeltaTime = (float)(FrameTime - LastTime); LastTime = FrameTime; if ((FrameTime - LastFpsTime) >= 1.0) { double Fps = FpsFrame / (FrameTime - LastFpsTime); double AvgFrameTime = (1.0 / Fps) * 1000000.0; char Text[256]; wsprintf(Text, "[%d fps %d us] %s", (int)Fps, (int)AvgFrameTime, ApplicationName); SetWindowText(Window, Text); LastFpsTime = FrameTime; FpsFrame = 0; } FpsFrame++; } LRESULT CALLBACK FApplication::ProcessWindowMessage(HWND InWindow, UINT Message, WPARAM WParam, LPARAM LParam) { switch (Message) { case WM_KEYDOWN: if (WParam == VK_ESCAPE) { PostQuitMessage(0); return 0; } break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(InWindow, Message, WParam, LParam); } void FApplication::MakeWindow(uint32_t ResolutionX, uint32_t ResolutionY) { WNDCLASS Winclass = {}; Winclass.lpfnWndProc = ProcessWindowMessage; Winclass.hInstance = GetModuleHandle(nullptr); Winclass.hCursor = LoadCursor(nullptr, IDC_ARROW); Winclass.lpszClassName = ApplicationName; if (!RegisterClass(&Winclass)) { assert(0); } RECT Rect = { 0, 0, (int32_t)ResolutionX, (int32_t)ResolutionY }; if (!AdjustWindowRect(&Rect, WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX, 0)) { assert(0); } Window = CreateWindowEx( 0, ApplicationName, ApplicationName, WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, Rect.right - Rect.left, Rect.bottom - Rect.top, NULL, NULL, NULL, 0); assert(Window); }
22.44
110
0.720588
michal-z
20899eef7027a43b056777e704f0326e9a4149b3
3,226
hpp
C++
src/ibeo_8l_sdk/src/ibeosdk/devices/IbeoEcu.hpp
tomcamp0228/ibeo_ros2
ff56c88d6e82440ae3ce4de08f2745707c354604
[ "MIT" ]
1
2020-06-19T11:01:49.000Z
2020-06-19T11:01:49.000Z
include/ibeosdk/devices/IbeoEcu.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
null
null
null
include/ibeosdk/devices/IbeoEcu.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
2
2020-06-19T11:01:48.000Z
2020-10-29T03:07:14.000Z
//====================================================================== /*! \file IbeoEcu.hpp * * \copydoc Copyright * \author Mario Brumm (mb) * \date Apr 24, 2012 *///------------------------------------------------------------------- #ifndef IBEOSDK_IBEOECU_HPP_SEEN #define IBEOSDK_IBEOECU_HPP_SEEN //====================================================================== #include <ibeosdk/misc/WinCompatibility.hpp> #include <ibeosdk/devices/IbeoDevice.hpp> //====================================================================== namespace ibeosdk { //====================================================================== class IbeoEcu : public IbeoDevice<IbeoEcu> { public: //======================================== /*!\brief Create an IbeoEcu (connection class). * * This constructor will create an IbeoEcu class object * which will try to connect to an ECU, * using the given IP address and port number. * * \param[in] ip IP address of the ECU * to be connected with. * \param[in] port Port number for the connection * with the scanner. *///------------------------------------- IbeoEcu(const std::string& ip, const unsigned short port = 12002); //======================================== /*!\brief Destructor. * * Will disconnect before destruction. *///------------------------------------- virtual ~IbeoEcu(); public: //======================================== /*!\brief Establish the connection to the hardware. * * Reimplements IbeoDevice::getConnected. In * addition it will send a setFilter command * to the ECU to make all messages passes its * output filter. *///------------------------------------- virtual void getConnected(); public: //======================================== /*!\brief Send a command which expects no reply. * \param[in] cmd Command to be sent. * \return The result of the operation. *///------------------------------------- virtual statuscodes::Codes sendCommand(const EcuCommandBase& cmd); //======================================== /*!\brief Send a command and wait for a reply. * * The command will be sent. The calling thread * will sleep until a reply has been received * but not longer than the number of milliseconds * given in \a timeOut. * * \param[in] cmd Command to be sent. * \param[in, out] reply The reply container for * the reply to be stored into. * \param[in] timeOut Number of milliseconds to * wait for a reply. * \return The result of the operation. *///------------------------------------- virtual statuscodes::Codes sendCommand(const EcuCommandBase& cmd, EcuCommandReplyBase& reply, const boost::posix_time::time_duration timeOut = boost::posix_time::milliseconds(500)); }; // IbeoEcu //====================================================================== } // namespace ibeosdk //====================================================================== #endif // IBEOSDK_IBEOECU_HPP_SEEN //======================================================================
33.604167
127
0.450713
tomcamp0228
2089db00baaca9f27215e50d86bf88ee8f2080b6
346
cpp
C++
Software/swirli/WashingInstructions/AddSoapInstruction.cpp
martijnvandijk/th06
873c63fbd232c3465f700f5ecee945b2f2ecd8f2
[ "MIT" ]
null
null
null
Software/swirli/WashingInstructions/AddSoapInstruction.cpp
martijnvandijk/th06
873c63fbd232c3465f700f5ecee945b2f2ecd8f2
[ "MIT" ]
null
null
null
Software/swirli/WashingInstructions/AddSoapInstruction.cpp
martijnvandijk/th06
873c63fbd232c3465f700f5ecee945b2f2ecd8f2
[ "MIT" ]
null
null
null
// // Created by chiel on 18/01/16. // #include "AddSoapInstruction.h" AddSoapInstruction::AddSoapInstruction(WashingMachine::SoapDispenser &dispenser) : dispenser(dispenser) { } void AddSoapInstruction::execute(WashingProgramRunner &runner, LogController &logController, bool doWait) { dispenser.set(WashingMachine::SOAP_OPEN, &runner); }
26.615385
107
0.780347
martijnvandijk
208e31af872d140780be8836b8f8eb79ca09ca06
393
hpp
C++
inc/rook/ast/call.hpp
Vandise/Gambit-Archive
6db1921d99d76cd10f8f1bd25c46776d435d85a7
[ "MIT" ]
1
2019-02-20T19:19:23.000Z
2019-02-20T19:19:23.000Z
inc/rook/ast/call.hpp
Vandise/Gambit-Archive
6db1921d99d76cd10f8f1bd25c46776d435d85a7
[ "MIT" ]
null
null
null
inc/rook/ast/call.hpp
Vandise/Gambit-Archive
6db1921d99d76cd10f8f1bd25c46776d435d85a7
[ "MIT" ]
null
null
null
#ifndef __ROOK_CALLNODE #define __ROOK_CALLNODE 1 #include "rook/ast/node.hpp" #include <vector> namespace RookAST { class CallNode : public RookAST::Node { protected: std::string methodSignature; int parameters; public: CallNode(std::string methodSignature, int parameters); ~CallNode(); void compile(RookVM::PawnExecutor* e); }; } #endif
14.035714
60
0.669211
Vandise
209208747f4e473eef2c105d730a3f9331fceb88
19,876
hpp
C++
llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/util/common_type/assoc/common_type.hpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/util/common_type/assoc/common_type.hpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/util/common_type/assoc/common_type.hpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
// -*- C++ -*- // Copyright (C) 2005, 2006 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) any later // version. // This library 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 library; see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA. // As a special exception, you may use this file as part of a free // software library without restriction. Specifically, if other files // instantiate templates or use macros or inline functions from this // file, or you compile this file and link it with other files to // produce an executable, this file does not by itself cause the // resulting executable to be covered by the GNU General Public // License. This exception does not however invalidate any other // reasons why the executable file might be covered by the GNU General // Public License. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file common_type.hpp * Contains common types. */ #ifndef PB_DS_COMMON_TYPES_HPP #define PB_DS_COMMON_TYPES_HPP #include <ext/pb_ds/detail/type_utils.hpp> #include <common_type/assoc/template_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> namespace pb_ds { namespace test { template<typename Key, typename Data, class Hash_Fn = typename pb_ds::detail::default_hash_fn<Key>::type, class Eq_Fn = std::equal_to<Key>, class Allocator = std::allocator<std::pair<const Key, Data> > > struct hash_common_types { private: typedef typename Allocator::size_type size_type; typedef pb_ds::test::hash_load_check_resize_trigger_t_< Allocator, 1, 8, 1, 2, false> no_access_half_load_check_resize_trigger_policy; typedef pb_ds::test::hash_load_check_resize_trigger_t_< Allocator, 1, 8, 1, 2, true> access_half_load_check_resize_trigger_policy; typedef pb_ds::test::hash_load_check_resize_trigger_t_< Allocator, 1, 8, 1, 1, false> no_access_one_load_check_resize_trigger_policy; typedef pb_ds::test::cc_hash_max_collision_check_resize_trigger_t_< Allocator, 1, 2, false> no_access_half_max_col_check_check_resize_trigger_policy; typedef pb_ds::test::cc_hash_max_collision_check_resize_trigger_t_< Allocator, 1, 2, true> access_half_max_col_check_check_resize_trigger_policy; typedef pb_ds::test::linear_probe_fn_t_<Key, Allocator> lin_p_t; typedef pb_ds::test::quadratic_probe_fn_t_<Key, Allocator> quad_p_t; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::false_type, pb_ds::test::direct_mask_range_hashing_t_< Allocator>, no_access_half_load_check_resize_trigger_policy, pb_ds::test::hash_exponential_size_policy_t_< Allocator> >::type performance_cc_policy0; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::false_type, pb_ds::test::direct_mod_range_hashing_t_< Allocator>, no_access_half_load_check_resize_trigger_policy, pb_ds::test::hash_prime_size_policy_t_>::type performance_cc_policy1; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::false_type, pb_ds::test::direct_mask_range_hashing_t_< Allocator>, no_access_one_load_check_resize_trigger_policy, pb_ds::test::hash_exponential_size_policy_t_< Allocator> >::type performance_cc_policy2; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::false_type, pb_ds::test::direct_mod_range_hashing_t_< Allocator>, no_access_one_load_check_resize_trigger_policy, pb_ds::test::hash_prime_size_policy_t_ >::type performance_cc_policy3; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::true_type, pb_ds::test::direct_mask_range_hashing_t_< Allocator>, no_access_half_load_check_resize_trigger_policy, pb_ds::test::hash_exponential_size_policy_t_< Allocator> >::type performance_cc_policy4; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::false_type, pb_ds::test::direct_mask_range_hashing_t_< Allocator>, no_access_half_max_col_check_check_resize_trigger_policy, pb_ds::test::hash_exponential_size_policy_t_< Allocator> >::type performance_cc_policy5; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::false_type, pb_ds::test::direct_mask_range_hashing_t_< Allocator>, access_half_max_col_check_check_resize_trigger_policy, pb_ds::test::hash_exponential_size_policy_t_< Allocator> >::type regression_cc_policy0; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::false_type, pb_ds::test::direct_mask_range_hashing_t_< Allocator>, access_half_load_check_resize_trigger_policy, pb_ds::test::hash_exponential_size_policy_t_< Allocator> >::type regression_cc_policy1; typedef typename __gnu_cxx::typelist::create4< pb_ds::detail::true_type, pb_ds::test::direct_mod_range_hashing_t_< Allocator>, no_access_half_load_check_resize_trigger_policy, pb_ds::test::hash_prime_size_policy_t_ >::type regression_cc_policy2; typedef typename __gnu_cxx::typelist::create5< pb_ds::detail::false_type, lin_p_t, pb_ds::test::direct_mask_range_hashing_t_< Allocator>, no_access_half_load_check_resize_trigger_policy, pb_ds::test::hash_exponential_size_policy_t_< Allocator> >::type performance_gp_policy0; typedef typename __gnu_cxx::typelist::create5< pb_ds::detail::false_type, quad_p_t, pb_ds::test::direct_mod_range_hashing_t_< Allocator>, no_access_half_load_check_resize_trigger_policy, pb_ds::test::hash_prime_size_policy_t_ >::type performance_gp_policy1; typedef typename __gnu_cxx::typelist::create5< pb_ds::detail::false_type, quad_p_t, pb_ds::test::direct_mod_range_hashing_t_< Allocator>, access_half_load_check_resize_trigger_policy, pb_ds::test::hash_prime_size_policy_t_>::type regression_gp_policy0; typedef typename __gnu_cxx::typelist::create5< pb_ds::detail::true_type, lin_p_t, pb_ds::test::direct_mask_range_hashing_t_< Allocator>, access_half_load_check_resize_trigger_policy, pb_ds::test::hash_exponential_size_policy_t_< Allocator> >::type regression_gp_policy1; typedef typename __gnu_cxx::typelist::create6< performance_cc_policy0, performance_cc_policy1, performance_cc_policy2, performance_cc_policy3, performance_cc_policy4, performance_cc_policy5>::type performance_cc_range_hashing_policies; typedef typename __gnu_cxx::typelist::create3< regression_cc_policy0, regression_cc_policy1, regression_cc_policy2>::type regression_cc_range_hashing_policies; typedef typename __gnu_cxx::typelist::create2< performance_gp_policy0, performance_gp_policy1>::type performance_gp_range_hashing_policies; typedef typename __gnu_cxx::typelist::create2< regression_gp_policy0, regression_gp_policy1>::type regression_gp_range_hashing_policies; template<typename Policy_Tl> struct no_access_generic_cc_hash_table_t { private: typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 0>::type store_hash_indicator; enum { store_hash = store_hash_indicator::value }; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 1>::type comb_hash_fn; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 2>::type trigger_policy; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 3>::type size_policy; public: typedef pb_ds::cc_hash_table< Key, Data, Hash_Fn, Eq_Fn, comb_hash_fn, pb_ds::hash_standard_resize_policy< size_policy, trigger_policy, false>, store_hash, Allocator> type; }; template<typename Policy_Tl> struct access_generic_cc_hash_table_t { private: typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 0>::type store_hash_indicator; enum { store_hash = store_hash_indicator::value }; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 1>::type comb_hash_fn; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 2>::type trigger_policy; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 3>::type size_policy; public: typedef pb_ds::cc_hash_table< Key, Data, Hash_Fn, Eq_Fn, comb_hash_fn, pb_ds::hash_standard_resize_policy< size_policy, trigger_policy, true>, store_hash, Allocator> type; }; template<typename Policy_Tl> struct no_access_generic_gp_hash_table_t { private: typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 0>::type store_hash_indicator; enum { store_hash = store_hash_indicator::value }; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 1>::type probe_fn; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 2>::type comb_probe_fn; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 3>::type trigger_policy; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 4>::type size_policy; public: typedef pb_ds::gp_hash_table< Key, Data, Hash_Fn, Eq_Fn, comb_probe_fn, probe_fn, pb_ds::hash_standard_resize_policy< size_policy, trigger_policy, false>, store_hash, Allocator> type; }; template<typename Policy_Tl> struct access_generic_gp_hash_table_t { private: typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 0>::type store_hash_indicator; enum { store_hash = store_hash_indicator::value }; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 1>::type probe_fn; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 2>::type comb_probe_fn; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 3>::type trigger_policy; typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 4>::type size_policy; public: typedef pb_ds::gp_hash_table< Key, Data, Hash_Fn, Eq_Fn, comb_probe_fn, probe_fn, pb_ds::hash_standard_resize_policy< size_policy, trigger_policy, true>, store_hash, Allocator> type; }; typedef typename __gnu_cxx::typelist::transform< performance_cc_range_hashing_policies, no_access_generic_cc_hash_table_t>::type performance_cc_types; typedef typename __gnu_cxx::typelist::transform< regression_cc_range_hashing_policies, access_generic_cc_hash_table_t>::type regression_cc_types; typedef typename __gnu_cxx::typelist::at_index< performance_cc_types, 0>::type performance_min_cc_type; typedef typename __gnu_cxx::typelist::transform< performance_gp_range_hashing_policies, no_access_generic_gp_hash_table_t>::type performance_gp_types; typedef typename __gnu_cxx::typelist::transform< regression_gp_range_hashing_policies, access_generic_gp_hash_table_t>::type regression_gp_types; typedef typename __gnu_cxx::typelist::at_index< performance_gp_types, 0>::type performance_min_gp_type; public: typedef typename __gnu_cxx::typelist::append< performance_cc_types, performance_gp_types>::type performance_tl; typedef typename __gnu_cxx::typelist::append< regression_gp_types, regression_cc_types>::type regression_tl; typedef typename __gnu_cxx::typelist::create1< performance_min_cc_type>::type performance_min_tl; }; template<typename Key, typename Data, class Comb_Hash_Fn_TL, class Comb_Probe_Fn_TL, class Eq_Fn = std::equal_to<Key>, class Allocator = std::allocator< std::pair< const Key, Data> > > struct ranged_hash_common_types { private: typedef typename Allocator::size_type size_type; typedef pb_ds::test::hash_load_check_resize_trigger_t_< Allocator, 1, 8, 1, 2, false> no_access_half_load_check_resize_trigger_policy; typedef pb_ds::test::hash_load_check_resize_trigger_t_< Allocator, 1, 8, 1, 1, false> no_access_one_load_check_resize_trigger_policy; typedef pb_ds::hash_standard_resize_policy< pb_ds::test::hash_exponential_size_policy_t_< Allocator>, no_access_half_load_check_resize_trigger_policy> mask_half_resize_policy_t; typedef pb_ds::hash_standard_resize_policy< pb_ds::test::hash_exponential_size_policy_t_< Allocator>, no_access_one_load_check_resize_trigger_policy> mask_one_resize_policy_t; typedef pb_ds::hash_standard_resize_policy< pb_ds::test::hash_prime_size_policy_t_, no_access_half_load_check_resize_trigger_policy> mod_half_resize_policy_t; typedef pb_ds::hash_standard_resize_policy< pb_ds::test::hash_prime_size_policy_t_, no_access_one_load_check_resize_trigger_policy> mod_one_resize_policy_t; template<typename Comb_Hash_Fn_> struct half_resize_policy_selector; template<typename Allocator_> struct half_resize_policy_selector< pb_ds::test::direct_mask_range_hashing_t_< Allocator_> > { typedef mask_half_resize_policy_t type; }; template<typename Allocator_> struct half_resize_policy_selector< pb_ds::test::direct_mod_range_hashing_t_< Allocator_> > { typedef mod_half_resize_policy_t type; }; template<typename Comb_Hash_Fn_> struct one_resize_policy_selector; template<typename Allocator_> struct one_resize_policy_selector< pb_ds::test::direct_mask_range_hashing_t_< Allocator_> > { typedef mask_one_resize_policy_t type; }; template<typename Allocator_> struct one_resize_policy_selector< pb_ds::test::direct_mod_range_hashing_t_< Allocator_> > { typedef mod_one_resize_policy_t type; }; template<typename Comb_Hash_Fn> struct generic_cc_hash_table_t { typedef pb_ds::cc_hash_table< Key, Data, pb_ds::null_hash_fn, Eq_Fn, Comb_Hash_Fn, typename one_resize_policy_selector< typename Comb_Hash_Fn::comb_fn>::type, false, Allocator> type; }; typedef typename __gnu_cxx::typelist::transform< Comb_Hash_Fn_TL, generic_cc_hash_table_t>::type performance_cc_types; template<typename Comb_Probe_Fn> struct no_access_generic_gp_hash_table_t { typedef pb_ds::gp_hash_table< Key, Data, pb_ds::null_hash_fn, Eq_Fn, Comb_Probe_Fn, pb_ds::null_probe_fn, typename half_resize_policy_selector< typename Comb_Probe_Fn::comb_fn>::type, false, Allocator> type; }; typedef typename __gnu_cxx::typelist::transform< Comb_Probe_Fn_TL, no_access_generic_gp_hash_table_t>::type performance_gp_types; public: typedef typename __gnu_cxx::typelist::append< performance_cc_types, performance_gp_types>::type performance_tl; }; template<typename Key, typename Data, class Eq_Fn = std::equal_to<Key>, class Allocator = std::allocator<char> > class lu_common_types { private: typedef typename Allocator::size_type size_type; typedef pb_ds::test::move_to_front_lu_policy_t_ mtf_u; typedef pb_ds::test::counter_lu_policy_t_<Allocator, 5> cnt_5_u; typedef typename __gnu_cxx::typelist::create1<mtf_u>::type lu_policy0; typedef typename __gnu_cxx::typelist::create1<cnt_5_u>::type lu_policy1; typedef typename __gnu_cxx::typelist::create2< lu_policy0, lu_policy1>::type lu_policies; template<typename Policy_Tl> struct generic_list_update_t { private: typedef typename __gnu_cxx::typelist::at_index< Policy_Tl, 0>::type update_policy_t; public: typedef pb_ds::list_update< Key, Data, Eq_Fn, update_policy_t, Allocator> type; }; typedef typename __gnu_cxx::typelist::transform< lu_policies, generic_list_update_t>::type lu_types; typedef typename __gnu_cxx::typelist::at_index< lu_types, 0>::type min_lu_type; public: typedef lu_types performance_tl; typedef lu_types regression_tl; typedef typename __gnu_cxx::typelist::create1<min_lu_type>::type performance_min_tl; }; template<typename Key, typename Data, class Cmp_Fn = std::less<Key>, template<typename Const_Node_Iterator, class Node_Iterator, class Cmp_Fn_, class Allocator_> class Node_Update = pb_ds::null_tree_node_update, class Allocator = std::allocator<std::pair<const Key, Data> > > struct tree_common_types { private: typedef pb_ds::tree< Key, Data, Cmp_Fn, pb_ds::ov_tree_tag, Node_Update, Allocator> ov_tree_assoc_container_t; typedef pb_ds::tree< Key, Data, Cmp_Fn, pb_ds::rb_tree_tag, Node_Update, Allocator> rb_tree_assoc_container_t; typedef pb_ds::tree< Key, Data, Cmp_Fn, pb_ds::splay_tree_tag, Node_Update, Allocator> splay_tree_assoc_container_t; public: typedef typename __gnu_cxx::typelist::create3< splay_tree_assoc_container_t, rb_tree_assoc_container_t, ov_tree_assoc_container_t>::type performance_tl; typedef typename __gnu_cxx::typelist::create3< ov_tree_assoc_container_t, splay_tree_assoc_container_t, rb_tree_assoc_container_t>::type regression_tl; typedef typename __gnu_cxx::typelist::create1< rb_tree_assoc_container_t>::type performance_min_tl; }; template<typename Key, typename Data, class E_Access_Traits = typename pb_ds::detail::default_trie_e_access_traits<Key>::type, class Tag = pb_ds::pat_trie_tag, template<typename Const_Node_Iterator, typename Node_Iterator, class E_Access_Traits_, typename Allocator_> class Node_Update = pb_ds::null_trie_node_update, class Allocator = std::allocator<char> > class trie_common_types { private: typedef pb_ds::trie<Key, Data, E_Access_Traits, Tag, Node_Update, Allocator> type; public: typedef typename __gnu_cxx::typelist::create1<type>::type performance_tl; typedef typename __gnu_cxx::typelist::create1<type>::type regression_tl; typedef typename __gnu_cxx::typelist::create1<type>::type performance_min_tl; }; } // namespace test } // namespace pb_ds #endif // #ifndef PB_DS_COMMON_TYPES_HPP
24.26862
90
0.721674
vidkidz
20945912f354bbfef46106af158a534e81a59ff1
25,618
cc
C++
ceee/ie/plugin/bho/frame_event_handler_unittest.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
ceee/ie/plugin/bho/frame_event_handler_unittest.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
ceee/ie/plugin/bho/frame_event_handler_unittest.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 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. // // @file // Frame event handler unittests. #include "ceee/ie/plugin/bho/frame_event_handler.h" #include <atlctl.h> #include <map> #include "base/file_util.h" #include "ceee/common/com_utils.h" #include "ceee/ie/testing/mock_frame_event_handler_host.h" #include "ceee/testing/utils/instance_count_mixin.h" #include "ceee/testing/utils/mock_com.h" #include "ceee/testing/utils/mshtml_mocks.h" #include "ceee/testing/utils/test_utils.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using testing::IOleObjecMockImpl; using testing::IWebBrowser2MockImpl; using testing::InstanceCountMixinBase; using testing::InstanceCountMixin; using testing::_; using testing::CopyInterfaceToArgument; using testing::DoAll; using testing::Return; using testing::StrEq; using testing::StrictMock; using testing::SetArgumentPointee; ScriptHost::DebugApplication debug_app(L"FrameEventHandlerUnittest"); // We need to implement this interface separately, because // there are name conflicts with methods in IConnectionPointImpl, // and we don't want to override those methods. class TestIOleObjectImpl: public StrictMock<IOleObjecMockImpl> { public: // Implement the advise functions. STDMETHOD(Advise)(IAdviseSink* sink, DWORD* advise_cookie) { return advise_holder_->Advise(sink, advise_cookie); } STDMETHOD(Unadvise)(DWORD advise_cookie) { return advise_holder_->Unadvise(advise_cookie); } STDMETHOD(EnumAdvise)(IEnumSTATDATA **enum_advise) { return advise_holder_->EnumAdvise(enum_advise); } HRESULT Initialize() { return ::CreateOleAdviseHolder(&advise_holder_); } public: CComPtr<IOleAdviseHolder> advise_holder_; }; class IPersistMockImpl: public IPersist { public: MOCK_METHOD1_WITH_CALLTYPE(__stdcall, GetClassID, HRESULT(CLSID *clsid)); }; class MockDocument : public CComObjectRootEx<CComSingleThreadModel>, public InitializingCoClass<MockDocument>, public InstanceCountMixin<MockDocument>, public StrictMock<IHTMLDocument2MockImpl>, public StrictMock<IPersistMockImpl>, public TestIOleObjectImpl, public IConnectionPointContainerImpl<MockDocument>, public IConnectionPointImpl<MockDocument, &IID_IPropertyNotifySink> { public: BEGIN_COM_MAP(MockDocument) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IHTMLDocument) COM_INTERFACE_ENTRY(IHTMLDocument2) COM_INTERFACE_ENTRY(IOleObject) COM_INTERFACE_ENTRY(IPersist) COM_INTERFACE_ENTRY(IConnectionPointContainer) END_COM_MAP() BEGIN_CONNECTION_POINT_MAP(MockDocument) CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink) END_CONNECTION_POINT_MAP() MockDocument() : ready_state_(READYSTATE_UNINITIALIZED) { } void FireOnClose() { EXPECT_HRESULT_SUCCEEDED(advise_holder_->SendOnClose()); } // Override to handle DISPID_READYSTATE. STDMETHOD(Invoke)(DISPID member, REFIID iid, LCID locale, WORD flags, DISPPARAMS* params, VARIANT *result, EXCEPINFO* ex_info, unsigned int* arg_error) { if (member == DISPID_READYSTATE && flags == DISPATCH_PROPERTYGET) { result->vt = VT_I4; result->lVal = ready_state_; return S_OK; } return StrictMock<IHTMLDocument2MockImpl>::Invoke(member, iid, locale, flags, params, result, ex_info, arg_error); } STDMETHOD(get_URL)(BSTR* url) { return url_.CopyTo(url); } HRESULT Initialize(MockDocument** self) { *self = this; return TestIOleObjectImpl::Initialize(); } READYSTATE ready_state() const { return ready_state_; } void set_ready_state(READYSTATE ready_state) { ready_state_ = ready_state; } void FireReadyStateChange() { CFirePropNotifyEvent::FireOnChanged(GetUnknown(), DISPID_READYSTATE); } // Sets our ready state and fires the change event. void SetReadyState(READYSTATE new_ready_state) { if (ready_state_ == new_ready_state) return; ready_state_ = new_ready_state; FireReadyStateChange(); } const wchar_t *url() const { return com::ToString(url_); } void set_url(const wchar_t* url) { url_ = url; } protected: CComBSTR url_; READYSTATE ready_state_; }; class MockBrowser : public CComObjectRootEx<CComSingleThreadModel>, public InitializingCoClass<MockBrowser>, public InstanceCountMixin<MockBrowser>, public StrictMock<IWebBrowser2MockImpl> { public: BEGIN_COM_MAP(MockBrowser) COM_INTERFACE_ENTRY(IWebBrowser2) COM_INTERFACE_ENTRY(IWebBrowserApp) COM_INTERFACE_ENTRY(IWebBrowser) END_COM_MAP() HRESULT Initialize(MockBrowser** self) { *self = this; return S_OK; } STDMETHOD(get_Parent)(IDispatch** parent) { this->GetUnknown()->AddRef(); *parent = this; return S_OK; } }; class IFrameEventHandlerHostMockImpl : public IFrameEventHandlerHost { public: MOCK_METHOD1(GetReadyState, HRESULT(READYSTATE* readystate)); MOCK_METHOD3(GetMatchingUserScriptsCssContent, HRESULT(const GURL& url, bool require_all_frames, std::string* css_content)); MOCK_METHOD4(GetMatchingUserScriptsJsContent, HRESULT(const GURL& url, UserScript::RunLocation location, bool require_all_frames, UserScriptsLibrarian::JsFileList* js_file_list)); MOCK_METHOD1(GetExtensionId, HRESULT(std::wstring* extension_id)); MOCK_METHOD1(GetExtensionPath, HRESULT(std::wstring* extension_path)); MOCK_METHOD1(GetExtensionPortMessagingProvider, HRESULT(IExtensionPortMessagingProvider** messaging_provider)); MOCK_METHOD4(InsertCode, HRESULT(BSTR, BSTR, BOOL, CeeeTabCodeType)); }; class TestFrameEventHandlerHost : public testing::MockFrameEventHandlerHostBase<TestFrameEventHandlerHost> { public: HRESULT Initialize(TestFrameEventHandlerHost** self) { *self = this; return S_OK; } virtual HRESULT AttachBrowser(IWebBrowser2* browser, IWebBrowser2* parent_browser, IFrameEventHandler* handler) { // Get the identity unknown. CComPtr<IUnknown> browser_identity_unknown; EXPECT_HRESULT_SUCCEEDED( browser->QueryInterface(&browser_identity_unknown)); std::pair<HandlerMap::iterator, bool> result = handlers_.insert(std::make_pair(browser_identity_unknown, handler)); EXPECT_TRUE(result.second); return S_OK; } virtual HRESULT DetachBrowser(IWebBrowser2* browser, IWebBrowser2* parent_browser, IFrameEventHandler* handler) { // Get the identity unknown. CComPtr<IUnknown> browser_identity_unknown; EXPECT_HRESULT_SUCCEEDED( browser->QueryInterface(&browser_identity_unknown)); EXPECT_EQ(1, handlers_.erase(browser_identity_unknown)); return S_OK; } virtual HRESULT OnReadyStateChanged(READYSTATE ready_state) { return S_OK; } bool has_browser(IUnknown* browser) { CComPtr<IUnknown> browser_identity(browser); return handlers_.find(browser_identity) != handlers_.end(); } FrameEventHandler* GetHandler(IUnknown* browser) { CComPtr<IUnknown> browser_identity(browser); HandlerMap::iterator it(handlers_.find(browser_identity)); if (it != handlers_.end()) return NULL; return static_cast<FrameEventHandler*>(it->second); } private: typedef std::map<IUnknown*, IFrameEventHandler*> HandlerMap; HandlerMap handlers_; }; class MockContentScriptManager : public ContentScriptManager { public: MOCK_METHOD3(ExecuteScript, HRESULT(const wchar_t* code, const wchar_t* file_path, IHTMLDocument2* document)); MOCK_METHOD2(InsertCss, HRESULT(const wchar_t* code, IHTMLDocument2* document)); }; // This testing class is used to test the higher-level event handling // behavior of FrameEventHandler by mocking out the implementation // functions invoked on readystate transitions. class TestingFrameEventHandler : public FrameEventHandler, public InitializingCoClass<TestingFrameEventHandler>, public InstanceCountMixin<TestingFrameEventHandler> { public: TestingFrameEventHandler() {} ~TestingFrameEventHandler() {} HRESULT Initialize(TestingFrameEventHandler **self, IWebBrowser2* browser, IWebBrowser2* parent_browser, IFrameEventHandlerHost* host) { *self = this; return FrameEventHandler::Initialize(browser, parent_browser, host); } virtual void InitializeContentScriptManager() { content_script_manager_.reset(new MockContentScriptManager); } MockContentScriptManager* GetContentScriptManager() { return reinterpret_cast<MockContentScriptManager*>( content_script_manager_.get()); } // Mock out or publicize our internal helper methods. MOCK_METHOD2(GetExtensionResourceContents, HRESULT(const FilePath& file, std::string* contents)); MOCK_METHOD3(GetCodeOrFileContents, HRESULT(BSTR code, BSTR file, std::wstring* contents)); HRESULT CallGetCodeOrFileContents(BSTR code, BSTR file, std::wstring* contents) { return FrameEventHandler::GetCodeOrFileContents(code, file, contents); } const std::list<DeferredInjection>& deferred_injections() { return deferred_injections_; } void SetupForRedoDoneInjectionsTest(BSTR url) { browser_url_ = url; loaded_css_ = true; loaded_start_scripts_ = true; loaded_end_scripts_ = true; } // Disambiguate. using InitializingCoClass<TestingFrameEventHandler>:: CreateInitialized; // Mock out the state transition implementation functions. MOCK_METHOD1(LoadCss, void(const GURL& match_url)); MOCK_METHOD1(LoadStartScripts, void(const GURL& match_url)); MOCK_METHOD1(LoadEndScripts, void(const GURL& match_url)); }; class FrameEventHandlerTestBase: public testing::Test { public: virtual void SetUp() { ASSERT_HRESULT_SUCCEEDED( MockBrowser::CreateInitialized(&browser_, &browser_keeper_)); ASSERT_HRESULT_SUCCEEDED( MockDocument::CreateInitialized(&document_, &document_keeper_)); ASSERT_HRESULT_SUCCEEDED( TestFrameEventHandlerHost::CreateInitializedIID( &host_, IID_IUnknown, &host_keeper_)); ExpectGetDocument(); } virtual void TearDown() { // Fire a close event just in case. if (document_) document_->FireOnClose(); browser_ = NULL; browser_keeper_.Release(); document_ = NULL; document_keeper_.Release(); host_ = NULL; host_keeper_.Release(); handler_keeper_.Release(); ASSERT_EQ(0, InstanceCountMixinBase::all_instance_count()); } void ExpectGetDocument() { EXPECT_CALL(*browser_, get_Document(_)) .WillRepeatedly(DoAll( CopyInterfaceToArgument<0>(static_cast<IDispatch*>(document_)), Return(S_OK))); } protected: MockBrowser* browser_; CComPtr<IWebBrowser2> browser_keeper_; MockDocument* document_; CComPtr<IHTMLDocument2> document_keeper_; TestFrameEventHandlerHost* host_; CComPtr<IFrameEventHandlerHost> host_keeper_; CComPtr<IUnknown> handler_keeper_; }; class FrameEventHandlerTest: public FrameEventHandlerTestBase { public: typedef FrameEventHandlerTestBase Base; static void SetUpTestCase() { // Never torn down as other threads in the test may need it after // teardown. ScriptHost::set_default_debug_application(&debug_app); } void TearDown() { handler_ = NULL; Base::TearDown(); } void CreateHandler() { EXPECT_CALL(*document_, GetClassID(_)).WillOnce( DoAll(SetArgumentPointee<0>(CLSID_HTMLDocument), Return(S_OK))); IWebBrowser2* parent_browser = NULL; ASSERT_HRESULT_SUCCEEDED( TestingFrameEventHandler::CreateInitialized( &handler_, browser_, parent_browser, host_, &handler_keeper_)); } protected: TestingFrameEventHandler* handler_; }; TEST_F(FrameEventHandlerTest, WillNotAttachToNonHTMLDocument) { EXPECT_CALL(*document_, GetClassID(_)).WillOnce( DoAll(SetArgumentPointee<0>(GUID_NULL), Return(S_OK))); // If the document is not MSHTML, we should not attach, and // we should return E_DOCUMENT_NOT_MSHTML to our caller to signal this. IWebBrowser2* parent_browser = NULL; HRESULT hr = TestingFrameEventHandler::CreateInitialized( &handler_, browser_, parent_browser, host_, &handler_keeper_); EXPECT_EQ(E_DOCUMENT_NOT_MSHTML, hr); EXPECT_FALSE(host_->has_browser(browser_)); } TEST_F(FrameEventHandlerTest, CreateAndDetachDoesNotCrash) { ASSERT_EQ(0, TestingFrameEventHandler::instance_count()); CreateHandler(); ASSERT_EQ(1, TestingFrameEventHandler::instance_count()); // Assert that it registered. ASSERT_TRUE(host_->has_browser(browser_)); // Release the handler early to ensure its last reference will // be released while handling FireOnClose. handler_keeper_.Release(); handler_ = NULL; EXPECT_EQ(1, TestingFrameEventHandler::instance_count()); // Should tear down and destroy itself on this event. document_->FireOnClose(); ASSERT_EQ(0, TestingFrameEventHandler::instance_count()); } const wchar_t kGoogleUrl[] = L"http://www.google.com/search?q=Google+Buys+Iceland"; const wchar_t kSlashdotUrl[] = L"http://hardware.slashdot.org/"; TEST_F(FrameEventHandlerTest, InjectsCSSAndStartScriptsOnLoadedReadystate) { CreateHandler(); document_->set_url(kGoogleUrl); document_->set_ready_state(READYSTATE_LOADING); // Transitioning to loading should not cause any loads. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); // Notify the handler of the URL. handler_->SetUrl(CComBSTR(kGoogleUrl)); document_->FireReadyStateChange(); const GURL google_url(kGoogleUrl); // Transitioning to LOADED should load Css and start scripts. EXPECT_CALL(*handler_, LoadCss(google_url)).Times(1); EXPECT_CALL(*handler_, LoadStartScripts(google_url)).Times(1); // But not end scripts. EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_LOADED); // Now make like a re-navigation. document_->SetReadyState(READYSTATE_LOADING); // Transitioning back to LOADED should load Css and start scripts again. EXPECT_CALL(*handler_, LoadCss(google_url)).Times(1); EXPECT_CALL(*handler_, LoadStartScripts(google_url)).Times(1); // But not end scripts. EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_LOADED); // Now navigate to a different URL. document_->set_url(kSlashdotUrl); document_->set_ready_state(READYSTATE_LOADING); // Transitioning to loading should not cause any loads. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); handler_->SetUrl(CComBSTR(kSlashdotUrl)); document_->FireReadyStateChange(); const GURL slashdot_url(kSlashdotUrl); // Transitioning back to LOADED on the new URL should load // Css and start scripts again. EXPECT_CALL(*handler_, LoadCss(slashdot_url)).Times(1); EXPECT_CALL(*handler_, LoadStartScripts(slashdot_url)).Times(1); // But not end scripts. EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_LOADED); } TEST_F(FrameEventHandlerTest, InjectsEndScriptsOnCompleteReadystate) { CreateHandler(); document_->set_url(kGoogleUrl); document_->set_ready_state(READYSTATE_LOADING); EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); // Transitioning to loading should not cause any loads. EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); // Notify the handler of the URL. handler_->SetUrl(CComBSTR(kGoogleUrl)); document_->FireReadyStateChange(); const GURL google_url(kGoogleUrl); // Transitioning to LOADED should load Css and start scripts. EXPECT_CALL(*handler_, LoadCss(google_url)).Times(1); EXPECT_CALL(*handler_, LoadStartScripts(google_url)).Times(1); // But not end scripts. EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_LOADED); // Transitioning to INTERACTIVE should be a no-op. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_INTERACTIVE); // Transitioning to COMPLETE should load end scripts. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(google_url)).Times(1); document_->SetReadyState(READYSTATE_COMPLETE); // Now make like a re-navigation. document_->SetReadyState(READYSTATE_LOADING); // Transitioning back to LOADED should load Css and start scripts again. EXPECT_CALL(*handler_, LoadCss(google_url)).Times(1); EXPECT_CALL(*handler_, LoadStartScripts(google_url)).Times(1); // But not end scripts. EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_LOADED); // Transitioning back to INTERACTIVE should be a no-op. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_INTERACTIVE); // Transitioning back to COMPLETE should load end scripts. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(google_url)).Times(1); document_->SetReadyState(READYSTATE_COMPLETE); // Now navigate to a different URL. document_->set_url(kSlashdotUrl); document_->set_ready_state(READYSTATE_LOADING); // Transitioning to loading should not cause any loads. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); handler_->SetUrl(CComBSTR(kSlashdotUrl)); document_->FireReadyStateChange(); const GURL slashdot_url(kSlashdotUrl); // Transitioning back to LOADED on the new URL should load // Css and start scripts again. EXPECT_CALL(*handler_, LoadCss(slashdot_url)).Times(1); EXPECT_CALL(*handler_, LoadStartScripts(slashdot_url)).Times(1); // But not end scripts. EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_LOADED); // Back to INTERACTIVE is still a noop. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(_)).Times(0); document_->SetReadyState(READYSTATE_INTERACTIVE); // And COMPLETE loads end scripts again. EXPECT_CALL(*handler_, LoadCss(_)).Times(0); EXPECT_CALL(*handler_, LoadStartScripts(_)).Times(0); EXPECT_CALL(*handler_, LoadEndScripts(slashdot_url)).Times(1); document_->SetReadyState(READYSTATE_COMPLETE); } TEST_F(FrameEventHandlerTest, InsertCodeCss) { CreateHandler(); MockContentScriptManager* content_script_manager = handler_->GetContentScriptManager(); // Css code type EXPECT_CALL(*handler_, GetCodeOrFileContents(_, _, _)).WillOnce(Return(S_OK)); // Must respond with non-empty extension path or call will get deferred. EXPECT_CALL(*host_, GetExtensionId(_)).WillOnce( DoAll(SetArgumentPointee<0>(std::wstring(L"hello")), Return(S_OK))); EXPECT_CALL(*content_script_manager, InsertCss(_, _)).WillOnce(Return(S_OK)); ASSERT_HRESULT_SUCCEEDED( handler_->InsertCode(NULL, NULL, kCeeeTabCodeTypeCss)); // Js code type with no file EXPECT_CALL(*handler_, GetCodeOrFileContents(_, _, _)).WillOnce(Return(S_OK)); wchar_t* default_file = L"ExecuteScript.code"; EXPECT_CALL(*content_script_manager, ExecuteScript(_, StrEq(default_file), _)) .WillOnce(Return(S_OK)); EXPECT_CALL(*host_, GetExtensionId(_)).WillOnce( DoAll(SetArgumentPointee<0>(std::wstring(L"hello")), Return(S_OK))); ASSERT_HRESULT_SUCCEEDED( handler_->InsertCode(NULL, NULL, kCeeeTabCodeTypeJs)); // Js code type with a file EXPECT_CALL(*handler_, GetCodeOrFileContents(_, _, _)).WillOnce(Return(S_OK)); wchar_t* test_file = L"test_file.js"; EXPECT_CALL(*content_script_manager, ExecuteScript(_, StrEq(test_file), _)) .WillOnce(Return(S_OK)); EXPECT_CALL(*host_, GetExtensionId(_)).WillOnce( DoAll(SetArgumentPointee<0>(std::wstring(L"hello")), Return(S_OK))); CComBSTR test_file_bstr(test_file); ASSERT_HRESULT_SUCCEEDED( handler_->InsertCode(NULL, test_file_bstr, kCeeeTabCodeTypeJs)); } TEST_F(FrameEventHandlerTest, DeferInsertCodeCss) { CreateHandler(); // Does not set extension path, so it stays empty. EXPECT_CALL(*host_, GetExtensionId(_)).WillRepeatedly(Return(S_OK)); ASSERT_HRESULT_SUCCEEDED( handler_->InsertCode(L"boo", NULL, kCeeeTabCodeTypeCss)); ASSERT_HRESULT_SUCCEEDED( handler_->InsertCode(NULL, L"moo", kCeeeTabCodeTypeJs)); ASSERT_EQ(2, handler_->deferred_injections().size()); ASSERT_EQ(L"boo", handler_->deferred_injections().begin()->code); ASSERT_EQ(L"", handler_->deferred_injections().begin()->file); ASSERT_EQ(kCeeeTabCodeTypeCss, handler_->deferred_injections().begin()->type); // The ++ syntax is ugly but it's either this or make DeferredInjection // a public struct. ASSERT_EQ(L"", (++handler_->deferred_injections().begin())->code); ASSERT_EQ(L"moo", (++handler_->deferred_injections().begin())->file); ASSERT_EQ(kCeeeTabCodeTypeJs, (++handler_->deferred_injections().begin())->type); } TEST_F(FrameEventHandlerTest, RedoDoneInjections) { CreateHandler(); MockContentScriptManager* content_script_manager = handler_->GetContentScriptManager(); // Expects no calls since nothing to redo. handler_->RedoDoneInjections(); CComBSTR url(L"http://www.google.com/"); handler_->SetupForRedoDoneInjectionsTest(url); GURL match_url(com::ToString(url)); // Does not set extension path, so it stays empty. EXPECT_CALL(*host_, GetExtensionId(_)).WillOnce(Return(S_OK)); // Will get deferred. ASSERT_HRESULT_SUCCEEDED(handler_->InsertCode(L"boo", NULL, kCeeeTabCodeTypeCss)); EXPECT_CALL(*handler_, LoadCss(match_url)).Times(1); EXPECT_CALL(*handler_, LoadStartScripts(match_url)).Times(1); EXPECT_CALL(*handler_, LoadEndScripts(match_url)).Times(1); // Expect to get this once, as we deferred it before. EXPECT_CALL(*handler_, GetCodeOrFileContents(_, _, _)).WillOnce(Return(S_OK)); EXPECT_CALL(*host_, GetExtensionId(_)).WillOnce( DoAll(SetArgumentPointee<0>(std::wstring(L"hello")), Return(S_OK))); EXPECT_CALL(*content_script_manager, InsertCss(_, _)).WillOnce(Return(S_OK)); ASSERT_HRESULT_SUCCEEDED( handler_->InsertCode(L"boo", NULL, kCeeeTabCodeTypeCss)); EXPECT_CALL(*handler_, GetCodeOrFileContents(_, _, _)).WillOnce(Return(S_OK)); EXPECT_CALL(*host_, GetExtensionId(_)).WillOnce( DoAll(SetArgumentPointee<0>(std::wstring(L"hello")), Return(S_OK))); EXPECT_CALL(*content_script_manager, InsertCss(_, _)).WillOnce(Return(S_OK)); handler_->RedoDoneInjections(); } TEST_F(FrameEventHandlerTest, GetCodeOrFileContents) { CreateHandler(); CComBSTR code(L"test"); CComBSTR file(L"test.js"); CComBSTR empty; std::wstring contents; // Failure cases. EXPECT_CALL(*handler_, GetExtensionResourceContents(_, _)).Times(0); ASSERT_HRESULT_FAILED(handler_->CallGetCodeOrFileContents(NULL, NULL, &contents)); ASSERT_HRESULT_FAILED(handler_->CallGetCodeOrFileContents(code, file, &contents)); ASSERT_HRESULT_FAILED(handler_->CallGetCodeOrFileContents(empty, NULL, &contents)); ASSERT_HRESULT_FAILED(handler_->CallGetCodeOrFileContents(NULL, empty, &contents)); ASSERT_HRESULT_FAILED(handler_->CallGetCodeOrFileContents(empty, empty, &contents)); EXPECT_CALL(*handler_, GetExtensionResourceContents(_, _)) .WillOnce(Return(E_FAIL)); ASSERT_HRESULT_FAILED(handler_->CallGetCodeOrFileContents(NULL, file, &contents)); // Success cases. EXPECT_CALL(*handler_, GetExtensionResourceContents(_, _)).Times(0); ASSERT_HRESULT_SUCCEEDED(handler_->CallGetCodeOrFileContents(code, NULL, &contents)); ASSERT_HRESULT_SUCCEEDED(handler_->CallGetCodeOrFileContents(code, empty, &contents)); EXPECT_CALL(*handler_, GetExtensionResourceContents(_, _)).Times(2) .WillRepeatedly(Return(S_OK)); ASSERT_HRESULT_SUCCEEDED(handler_->CallGetCodeOrFileContents(NULL, file, &contents)); ASSERT_HRESULT_SUCCEEDED(handler_->CallGetCodeOrFileContents(empty, file, &contents)); } } // namespace
34.5722
80
0.720587
Gitman1989
209c4d620b6ba3e6717ab1b61a5efd30e62a2e99
1,036
cpp
C++
client/core/layers.cpp
syby119/icloth-web-application
241d894b5f4805964ab7991b5ccb62e44a6aa7cb
[ "MIT" ]
2
2021-11-12T05:53:48.000Z
2021-11-12T05:53:59.000Z
client/core/layers.cpp
syby119/icloth-web-application
241d894b5f4805964ab7991b5ccb62e44a6aa7cb
[ "MIT" ]
null
null
null
client/core/layers.cpp
syby119/icloth-web-application
241d894b5f4805964ab7991b5ccb62e44a6aa7cb
[ "MIT" ]
null
null
null
#include <iostream> #include "layers.h" void Layers::set(int channel) noexcept { _mask = 1 << channel; } void Layers::enable(int channel) noexcept { _mask |= 1 << channel; } void Layers::enableAll() noexcept { _mask = 0xFFFFFFFF; } void Layers::toggle(int channel) noexcept { _mask ^= 1 << channel; } void Layers::disable(int channel) noexcept { _mask &= ~(1 << channel); } void Layers::disableAll() noexcept { _mask = 0; } bool Layers::isEnabled(int channel) const noexcept { return _mask & (1 << channel); } bool Layers::test(Layers layers) const noexcept { return _mask & layers._mask; } void Layers::printEnabledChannels() const { bool first = true; std::cout << "["; for (int channel = 0; channel < getMaxChannels(); ++channel) { if (isEnabled(channel)) { if (first) { std::cout << channel; first = false; } else { std::cout << ", " << channel; } } } std::cout << "]"; }
20.72
66
0.563707
syby119
209cfe14153b98e74ba62878d208d95657a39e11
7,524
cc
C++
naos/src/kernel/arch/cpu.cc
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
14
2020-02-12T11:07:58.000Z
2022-02-02T00:05:08.000Z
naos/src/kernel/arch/cpu.cc
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
null
null
null
naos/src/kernel/arch/cpu.cc
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
4
2020-02-27T09:53:53.000Z
2021-11-07T17:43:44.000Z
#include "kernel/arch/cpu.hpp" #include "kernel/arch/klib.hpp" #include "kernel/arch/task.hpp" #include "kernel/arch/tss.hpp" #include "kernel/arch/paging.hpp" #include "kernel/mm/vm.hpp" #include "kernel/mm/memory.hpp" #include "kernel/mm/mm.hpp" #include "kernel/task.hpp" #include "kernel/trace.hpp" #include "kernel/ucontext.hpp" namespace arch::cpu { cpu_t per_cpu_data[max_cpu_support]; std::atomic_int last_cpuid = 0; void *get_rsp() { void *stack; __asm__ __volatile__("movq %%rsp,%0 \n\t" : "=r"(stack) : :); return stack; } // switch task void cpu_t::set_context(void *stack) { kernel_rsp = static_cast<byte *>(stack); tss::set_rsp(cpu::current().get_id(), 0, stack); } bool cpu_t::is_in_exception_context() { return is_in_exception_context(get_rsp()); } bool cpu_t::is_in_kernel_context() { return is_in_kernel_context(get_rsp()); } bool cpu_t::is_in_interrupt_context() { return is_in_interrupt_context(get_rsp()); } bool cpu_t::is_in_exception_context(void *rsp) { byte *t_rsp = get_exception_rsp(); byte *b_rsp = t_rsp - memory::exception_stack_size; byte *s_rsp = static_cast<byte *>(rsp); return s_rsp <= t_rsp && s_rsp >= b_rsp; } bool cpu_t::is_in_interrupt_context(void *rsp) { byte *t_rsp = get_interrupt_rsp(); byte *b_rsp = t_rsp - memory::interrupt_stack_size; byte *s_rsp = static_cast<byte *>(rsp); return s_rsp <= t_rsp && s_rsp >= b_rsp; } bool cpu_t::is_in_kernel_context(void *rsp) { byte *t_rsp = get_kernel_rsp(); byte *b_rsp = t_rsp - memory::kernel_stack_size; byte *s_rsp = static_cast<byte *>(rsp); return s_rsp <= t_rsp && s_rsp >= b_rsp; } cpuid_t init() { u64 cpuid = last_cpuid++; auto &cur_data = per_cpu_data[cpuid]; cur_data.id = cpuid; /// gs kernel base _wrmsr(0xC0000102, (u64)&per_cpu_data[cpuid]); kassert(_rdmsr(0xC0000102) == ((u64)&per_cpu_data[cpuid]), "Unable to write kernel gs_base"); /// gs user base _wrmsr(0xC0000101, 0); /// fs base _wrmsr(0xC0000100, 0); __asm__("swapgs \n\t" ::: "memory"); kassert(_rdmsr(0xC0000101) == ((u64)&per_cpu_data[cpuid]), "Unable to swap kernel gs register"); return cpuid; } bool has_init() { return last_cpuid >= 1; } void init_data(cpuid_t cpuid) { _wrmsr(0xC0000101, (u64)&per_cpu_data[cpuid]); auto &data = cpu::current(); data.interrupt_rsp = get_interrupt_stack_bottom(cpuid) + memory::interrupt_stack_size; data.exception_rsp = get_exception_stack_bottom(cpuid) + memory::exception_stack_size; data.exception_nmi_rsp = get_exception_nmi_stack_bottom(cpuid) + memory::exception_nmi_stack_size; data.kernel_rsp = get_kernel_stack_bottom(cpuid) + memory::kernel_stack_size; tss::set_rsp(cpuid, 0, data.kernel_rsp); tss::set_ist(cpuid, 1, data.interrupt_rsp); tss::set_ist(cpuid, 3, data.exception_rsp); tss::set_ist(cpuid, 4, data.exception_nmi_rsp); } bool cpu_t::is_bsp() { return id == 0; } cpu_t &get(cpuid_t cpuid) { return per_cpu_data[cpuid]; } cpu_t &current() { u64 cpuid; #ifdef _DEBUG kassert(_rdmsr(0xC0000101) != 0, "Unreadable gs base"); kassert(_rdmsr(0xC0000102) == 0, "Unreadable kernel gs base"); #endif __asm__("movq %%gs:0x0, %0\n\t" : "=r"(cpuid) : :); return per_cpu_data[cpuid]; } void *current_user_data() { u64 u; __asm__("movq %%gs:0x10, %0\n\t" : "=r"(u) : :); return (void *)u; } u64 count() { return last_cpuid; } cpuid_t id() { return current().get_id(); } void map(u64 &base, u64 pg, bool is_bsp = false) { u64 size = pg * memory::page_size; auto c = (arch::paging::base_paging_t *) memory::kernel_vm_info->mmu_paging.get_base_page(); base += memory::page_size; phy_addr_t ks; if (is_bsp) { ks = phy_addr_t::from(0x90000 - size); } else { ks = memory::va2pa(memory::KernelBuddyAllocatorV->allocate(size, 0)); } paging::map(c, reinterpret_cast<void*>(base), ks, paging::frame_size::size_4kb, pg, paging::flags::writable); base += size; } void allocate_stack(int logic_num) { u64 base = memory::kernel_cpu_stack_bottom_address; for (int i = 0; i < logic_num; i++) { if (i != 0) { map(base, memory::kernel_stack_page_count); } else { map(base, memory::kernel_stack_page_count, true); } map(base, memory::exception_stack_page_count); map(base, memory::interrupt_stack_page_count); map(base, memory::exception_nmi_stack_page_count); } } phy_addr_t get_kernel_stack_bottom_phy(cpuid_t id) { void *vir = get_kernel_stack_bottom(id); phy_addr_t phy = nullptr; bool ret = paging::get_map_address(paging::current(), vir, &phy); kassert(ret, ""); return phy; } phy_addr_t get_exception_stack_bottom_phy(cpuid_t id) { void *vir = get_exception_stack_bottom(id); phy_addr_t phy = nullptr; bool ret = paging::get_map_address(paging::current(), vir, &phy); kassert(ret, ""); return phy; } phy_addr_t get_interrupt_stack_bottom_phy(cpuid_t id) { void *vir = get_interrupt_stack_bottom(id); phy_addr_t phy = nullptr; bool ret = paging::get_map_address(paging::current(), vir, &phy); kassert(ret, ""); return phy; } phy_addr_t get_exception_nmi_stack_bottom_phy(cpuid_t id) { void *vir = get_exception_nmi_stack_bottom(id); phy_addr_t phy = nullptr; bool ret = paging::get_map_address(paging::current(), vir, &phy); kassert(ret, ""); return phy; } byte *get_kernel_stack_bottom(cpuid_t id) { u64 base = memory::kernel_cpu_stack_bottom_address; u64 each_of_cpu_size = memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size + memory::exception_nmi_stack_size; each_of_cpu_size += memory::page_size * 4; // guard pages return reinterpret_cast<byte *>(base + each_of_cpu_size * id + memory::page_size); } byte *get_exception_stack_bottom(cpuid_t id) { u64 base = memory::kernel_cpu_stack_bottom_address; u64 each_of_cpu_size = memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size + memory::exception_nmi_stack_size; each_of_cpu_size += memory::page_size * 4; // guard pages return reinterpret_cast<byte *>(base + each_of_cpu_size * id + memory::page_size * 2 + memory::kernel_stack_size); } byte *get_interrupt_stack_bottom(cpuid_t id) { u64 base = memory::kernel_cpu_stack_bottom_address; u64 each_of_cpu_size = memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size + memory::exception_nmi_stack_size; each_of_cpu_size += memory::page_size * 4; // guard pages return reinterpret_cast<byte *>(base + each_of_cpu_size * id + memory::page_size * 3 + memory::kernel_stack_size + memory::exception_stack_size); } byte *get_exception_nmi_stack_bottom(cpuid_t id) { u64 base = memory::kernel_cpu_stack_bottom_address; u64 each_of_cpu_size = memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size + memory::exception_nmi_stack_size; each_of_cpu_size += memory::page_size * 4; // guard pages return reinterpret_cast<byte *>(base + each_of_cpu_size * id + memory::page_size * 4 + memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size); } } // namespace arch::cpu
31.881356
118
0.68009
kadds
20a1ad7f67b2c8aa3198b8f6932f40ee3d39e1fb
5,976
cxx
C++
src/Plugins/Plugin_PnPframegrabber/Widget_PnPframegrabber.cxx
gomezalberto/pretus
63b05419f70ecf8b28ccbb6191eab79637c051ac
[ "MIT" ]
18
2021-11-05T13:04:00.000Z
2022-01-31T14:14:08.000Z
src/Plugins/Plugin_PnPframegrabber/Widget_PnPframegrabber.cxx
gomezalberto/pretus
63b05419f70ecf8b28ccbb6191eab79637c051ac
[ "MIT" ]
27
2021-09-14T14:04:28.000Z
2022-02-15T09:58:30.000Z
src/Plugins/Plugin_PnPframegrabber/Widget_PnPframegrabber.cxx
gomezalberto/pretus
63b05419f70ecf8b28ccbb6191eab79637c051ac
[ "MIT" ]
1
2021-12-16T12:51:32.000Z
2021-12-16T12:51:32.000Z
#include "Widget_PnPframegrabber.h" #include <QLabel> #include <QVBoxLayout> #include <QPushButton> #include <QComboBox> #include <QSpacerItem> Widget_PnPframegrabber::Widget_PnPframegrabber( QWidget *parent, Qt::WindowFlags f) : QtPluginWidgetBase(parent, f) { this->mWidgetLocation = WidgetLocation::top_left; mStreamTypes = ifind::InitialiseStreamTypeSetFromString("Input"); mLabel = new QLabel("Text not set", this); mLabel->setStyleSheet(QtPluginWidgetBase::sQLabelStyle); auto labelFont = mLabel->font(); labelFont.setPixelSize(15); labelFont.setBold(true); mLabel->setFont(labelFont); auto vLayout = new QVBoxLayout(this); vLayout->setContentsMargins(0, 0, 0, 0); vLayout->setSpacing(0); this->setLayout(vLayout); vLayout->addWidget(mLabel); { // create a miniwidget for the play/pause/slider mPausePlayButton = new QPushButton("⏸︎"); mPausePlayButton->setStyleSheet(QtPluginWidgetBase::sQPushButtonStyle); mPausePlayButton->setCheckable(true); QWidget *placeholder = new QWidget(); QHBoxLayout *ph_layout = new QHBoxLayout(); ph_layout->addWidget(mPausePlayButton); // create a miniwidget for selecting framerates mFrameRateList = new QComboBox(this); mFrameRateList->setStyleSheet(QtPluginWidgetBase::sQComboBoxStyle); ph_layout->addWidget(mFrameRateList); mResolutionList = new QComboBox(this); mResolutionList->setStyleSheet(QtPluginWidgetBase::sQComboBoxStyle); ph_layout->addWidget(mResolutionList); mEncodingList = new QComboBox(this); mEncodingList->setStyleSheet(QtPluginWidgetBase::sQComboBoxStyle); ph_layout->addWidget(mEncodingList); ph_layout->addStretch(); placeholder->setLayout(ph_layout); vLayout->addWidget(placeholder); } QObject::connect(this->mFrameRateList, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Widget_PnPframegrabber::slot_updateFrameRate); QObject::connect(this->mResolutionList, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Widget_PnPframegrabber::slot_updateResolution); QObject::connect(this->mEncodingList, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Widget_PnPframegrabber::slot_updateEncoding); this->AddImageViewCheckboxToLayout(vLayout); } void Widget_PnPframegrabber::setFrameRates(std::vector<int> &framerates){ for (int i=0; i<framerates.size(); i++){ mFrameRateList->addItem(QString::number(framerates[i]) + " fps"); } } void Widget_PnPframegrabber::setResolutions(std::vector<std::string> &resolutions){ for (int i=0; i<resolutions.size(); i++){ mResolutionList->addItem(QString::fromStdString(resolutions[i])); } } void Widget_PnPframegrabber::setEncodings(std::vector<std::string> &encs){ for (int i=0; i<encs.size(); i++){ mEncodingList->addItem(QString::fromStdString(encs[i])); } } void Widget_PnPframegrabber::slot_togglePlayPause(bool v){ if (v == true){ this->mPausePlayButton->setText("▶"); } else { this->mPausePlayButton->setText("⏸︎"); } } void Widget_PnPframegrabber::slot_updateFrameRate(int idx){ QString newframerate = mFrameRateList->itemText(idx); Q_EMIT signal_newFrameRate(newframerate); } void Widget_PnPframegrabber::slot_updateResolution(int idx){ QString newres = mResolutionList->itemText(idx); Q_EMIT signal_newResolution(newres); } void Widget_PnPframegrabber::slot_updateEncoding(int idx){ QString newenc = mEncodingList->itemText(idx); Q_EMIT signal_newEncoding(newenc); } void Widget_PnPframegrabber::setSelectedFramerate(double r_fr){ int idx = -1; for (int i=0; i<mFrameRateList->count(); i++){ QString item_name = mFrameRateList->itemText(i); QStringList pieces0 = item_name.split( " " ); double item_fr= pieces0.value(0).toDouble(); if (r_fr == item_fr){ idx = i; break; } } mFrameRateList->setCurrentIndex(idx); } void Widget_PnPframegrabber::setSelectedResolution(QString res){ QStringList pieces = res.split( "." ); int r_w = pieces.value(0).toInt(); int r_h = pieces.value(1).toInt(); int idx = -1; for (int i=0; i<mResolutionList->count(); i++){ QString item_name = mResolutionList->itemText(i); QStringList pieces0 = item_name.split( " " ); QStringList pieces = pieces0.value(0).split( "x" ); int item_w = pieces.value(0).toInt(); int item_h = pieces.value(1).toInt(); if (r_w == item_w && r_h == item_h){ idx = i; break; } } mResolutionList->setCurrentIndex(idx); } void Widget_PnPframegrabber::setSelectedEncoding(QString enc){ int idx = -1; for (int i=0; i<mEncodingList->count(); i++){ QString item_name = mEncodingList->itemText(i); if (enc.toLower()==item_name.toLower()){ idx = i; break; } } mEncodingList->setCurrentIndex(idx); } void Widget_PnPframegrabber::SendImageToWidgetImpl(ifind::Image::Pointer image){ std::stringstream stream; stream << "==" << this->mPluginName.toStdString() << "=="<< std::endl; stream << "Sending " << ifind::StreamTypeSetToString(this->mStreamTypes) << std::endl; if (image->HasKey("StreamTime")){ stream << "Stream time: "<<image->GetMetaData<std::string>("StreamTime") << std::endl; } if (image->HasKey("MeasuredFrameRate")){ stream << "Video: "<< std::fixed << std::setprecision(1) << atof(image->GetMetaData<std::string>("MeasuredFrameRate").c_str()) << " Hz ("<< image->GetMetaData<std::string>("Width") <<"x"<<image->GetMetaData<std::string>("Height") <<")"<< std::endl; } mLabel->setText(stream.str().c_str()); }
30.030151
135
0.659806
gomezalberto
20a2ae88676f1ed59012289a780288c9fb47879c
7,181
hpp
C++
QtDemoApp/auth/smbios.hpp
F474M0R64N4/license-system
982f1297948353b58d736009a08c697c3e15a41b
[ "MIT" ]
4
2020-10-13T19:57:16.000Z
2021-09-08T11:57:12.000Z
client/client/src/auth/smbios.hpp
F474M0R64N4/license-system
982f1297948353b58d736009a08c697c3e15a41b
[ "MIT" ]
null
null
null
client/client/src/auth/smbios.hpp
F474M0R64N4/license-system
982f1297948353b58d736009a08c697c3e15a41b
[ "MIT" ]
null
null
null
#ifndef SMBIOS_H #define SMBIOS_H #pragma once #include <cstdint> #include <vector> namespace smbios { namespace types { enum { bios_info = 0, // Required system_info = 1, // Required baseboard_info = 2, module_info = 2, system_enclosure = 3, // Required system_chassis = 3, // Required processor_info = 4, // Required memory_controller_info = 5, // Obsolete memory_module_info = 6, // Obsolete cache_info = 7, // Required port_connector_info = 8, system_slots = 9, // Required onboard_device_info = 10, // Obsolete oem_strings = 11, system_config_options = 12, language_info = 13, group_associations = 14, system_event_log = 15, memory_array = 16, // Required memory_device = 17, // Required memory_error_info_32_bit = 18, memory_array_mapped_addr = 19, // Required memory_device_mapped_addr = 20, builtin_pointing_device = 21, portable_battery = 22, system_reset = 23, hardware_security = 24, system_power_controls = 25, voltage_probe = 26, cooling_device = 27, temperature_probe = 28, electrical_current_probe = 29, out_of_band_remote_access = 30, bis_entry_point = 31, // Required system_boot_info = 32, // Required memory_error_info_64_bit = 33, management_device = 34, management_device_component = 35, management_device_threshold = 36, memory_channel = 37, ipmi_device_info = 38, system_power_supply = 39, additional_info = 40, onboard_device_extinfo = 41, management_controller_host = 42, inactive = 126, end_of_table = 127, // Always last structure }; } typedef uint8_t byte_t; typedef uint16_t word_t; typedef uint32_t dword_t; #ifdef _MSC_VER typedef __int64 qword_t; #else #ifdef INT64_C typedef uint64_t qword_t; #else typedef (unsigned long long int) qwordt_t; #endif #endif typedef byte_t str_id; typedef byte_t enum_t; typedef std::vector<char*> string_array_t; struct header; #pragma pack(push, 1) struct raw_smbios_data { BYTE used20_calling_method; BYTE smbios_major_version; BYTE smbios_minor_version; BYTE dmi_revision; DWORD length; BYTE smbios_table_data[1]; }; struct header { byte_t type; byte_t length; word_t handle; }; struct string_list : header { byte_t count; }; struct baseboard_info : header { byte_t manufacturer_name; byte_t product_name; byte_t version; byte_t serial_number; byte_t product; byte_t version1; byte_t serial_number1; }; struct bios_info : header { // 2.0 str_id vendor; str_id version; word_t starting_segment; str_id release_date; byte_t rom_size; qword_t characteristics; // 2.4 byte_t ext_char1; byte_t ext_char2; byte_t sb_major; byte_t sb_minor; byte_t ec_major; byte_t ec_minor; }; struct system_info : header { // 2.0 str_id manufacturer; str_id product_name; str_id version; str_id serial_number; // 2.1 struct { dword_t time_low; word_t time_mid; word_t time_hi_and_version; byte_t clock_seq_hi_and_reserved; byte_t clock_seq_low; byte_t node[6]; } uuid; enum_t wakeup_type; // 2.4 str_id sku; str_id family; }; struct system_chassis : header { // 2.0 str_id manufacturer; byte_t type; str_id version; str_id serial_number; str_id assert_tag; // 2.1 enum_t bootup_state; enum_t power_supply_state; enum_t thermal_state; enum_t security_status; // 2.3 dword_t oem; byte_t height; byte_t cords; }; struct proc_info : header { // 2.0 str_id socket_designation; enum_t type; enum_t family; str_id manufacturer; qword_t id; str_id version; byte_t voltage; word_t clock; word_t speed_max; word_t speed_cur; byte_t status; enum_t upgrade; // 2.1 word_t l1; word_t l2; word_t l3; // 2.3 str_id serial_number; str_id assert_tag; str_id part_number; // 2.5 byte_t cores; byte_t cores_enabled; byte_t threads; word_t characteristics; enum_t family2; }; struct cache_info : header { // 2.0 str_id socket_designation; word_t config; word_t size_max; word_t size_cur; word_t sram_supported; word_t sram_cur; // 2.1 byte_t speed; enum_t error_correction_type; enum_t system_cache_type; enum_t associativity; }; struct slot : header { // 2.0 str_id slot_designation; enum_t type; enum_t data_bus_width; enum_t current_usage; enum_t length; word_t id; byte_t characteristics; // 2.1 byte_t characteristics2; // 2.6 word_t segment_group; byte_t bus; byte_t device; }; typedef string_list oem_strings; typedef string_list system_config_options; struct lang_info : header { byte_t installed_langs; byte_t flags; byte_t reserved[15]; str_id current_lang; }; struct mem_arr : header { // 2.1 enum_t location; enum_t use; enum_t error_correction; dword_t capacity; word_t error_info_handle; word_t devices_number; // 2.7 qword_t capacity_ext; }; struct mem_device : header { // 2.1 word_t mem_arr_handle; word_t mem_arr_error_info_handle; word_t total_width; word_t data_width; word_t size; enum_t form_factor; byte_t device_set; str_id device_locator; str_id bank_locator; enum_t type; word_t type_detail; // 2.3 word_t speed; str_id manufacturer; str_id serial_number; str_id assert_tag; str_id part_number; // 2.6 byte_t attributes; // 2.7 dword_t size_ext; word_t clock_speed; // 2.8 word_t voltage_min; word_t voltage_max; word_t voltage; }; #pragma pack(pop) class parser final { public: parser() = default; parser(const parser& x) { feed(x.raw_data_, x.raw_size_); } ~parser() { clear(); } std::vector<header*> headers; static byte_t* skip(byte_t*); static header* extract_strings(header*, string_array_t&); void feed(const void* raw_smbios, size_t size); void clear(); protected: byte_t* raw_data_{}; size_t raw_size_{}; }; inline byte_t* parser::skip(byte_t* x) { auto* ptr = x + reinterpret_cast<header*>(x)->length; size_t len; if (*ptr == 0) ptr += 2; else do { len = strlen(reinterpret_cast<const char*>(ptr)); ptr += len + 1; } while (len > 0); return ptr; } inline header* parser::extract_strings(header* x, string_array_t& a) { auto* ptr = reinterpret_cast<byte_t*>(x) + x->length; a.clear(); a.push_back(nullptr); if (*ptr == 0) ptr += 2; else for (;;) { auto* str = reinterpret_cast<char*>(ptr); const auto len = strlen(str); ptr += len + 1; if (len == 0) break; a.push_back(str); } return reinterpret_cast<header*>(ptr); } inline void parser::feed(const void* raw_smbios, const size_t size) { clear(); raw_size_ = size; raw_data_ = new byte_t[raw_size_]; memcpy(raw_data_, raw_smbios, size); auto* x = raw_data_; while (static_cast<size_t>(x - raw_data_) < raw_size_) { headers.push_back(reinterpret_cast<header*>(x)); x = skip(x); } } inline void parser::clear() { headers.clear(); delete[] raw_data_; raw_size_ = 0; } } // namespace smbios #endif
17.179426
69
0.682495
F474M0R64N4
20a2f90ab42e03dbeb32ad19813ec1e871972049
290,474
cxx
C++
panda/src/pgraph/nodePath.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/pgraph/nodePath.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/pgraph/nodePath.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: nodePath.cxx // Created by: drose (25Feb02) // Updated by: fperazzi, PandaSE (06Apr10) (added more overloads // for set_shader_input) // Updated by: weifengh, PandaSE(30Apr10) (added set_shader_auto) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "nodePath.h" #include "nodePathCollection.h" #include "findApproxPath.h" #include "findApproxLevelEntry.h" #include "internalNameCollection.h" #include "config_pgraph.h" #include "colorAttrib.h" #include "colorScaleAttrib.h" #include "cullBinAttrib.h" #include "textureAttrib.h" #include "texMatrixAttrib.h" #include "texGenAttrib.h" #include "materialAttrib.h" #include "materialCollection.h" #include "lightAttrib.h" #include "clipPlaneAttrib.h" #include "occluderEffect.h" #include "polylightEffect.h" #include "fogAttrib.h" #include "renderModeAttrib.h" #include "cullFaceAttrib.h" #include "alphaTestAttrib.h" #include "depthTestAttrib.h" #include "depthWriteAttrib.h" #include "depthOffsetAttrib.h" #include "shaderAttrib.h" #include "billboardEffect.h" #include "compassEffect.h" #include "showBoundsEffect.h" #include "transparencyAttrib.h" #include "antialiasAttrib.h" #include "audioVolumeAttrib.h" #include "texProjectorEffect.h" #include "scissorEffect.h" #include "texturePool.h" #include "planeNode.h" #include "occluderNode.h" #include "lensNode.h" #include "materialPool.h" #include "look_at.h" #include "plist.h" #include "boundingSphere.h" #include "geomNode.h" #include "sceneGraphReducer.h" #include "textureCollection.h" #include "textureStageCollection.h" #include "globPattern.h" #include "shader.h" #include "shaderInput.h" #include "config_gobj.h" #include "bamFile.h" #include "preparedGraphicsObjects.h" #include "dcast.h" #include "pStatCollector.h" #include "pStatTimer.h" #include "modelNode.h" #include "py_panda.h" #include "bam.h" #include "bamWriter.h" // stack seems to overflow on Intel C++ at 7000. If we need more than // 7000, need to increase stack size. int NodePath::_max_search_depth = 7000; TypeHandle NodePath::_type_handle; PStatCollector NodePath::_get_transform_pcollector("*:NodePath:get_transform"); PStatCollector NodePath::_verify_complete_pcollector("*:NodePath:verify_complete"); #ifdef HAVE_PYTHON #include "py_panda.h" #ifndef CPPPARSER extern EXPCL_PANDA_PUTIL Dtool_PyTypedObject Dtool_BamWriter; extern EXPCL_PANDA_PUTIL Dtool_PyTypedObject Dtool_BamReader; #endif // CPPPARSER #endif // HAVE_PYTHON // ***Begin temporary transition code for operator bool enum EmptyNodePathType { ENP_future, ENP_transition, ENP_deprecated, ENP_notify, }; ostream &operator << (ostream &out, EmptyNodePathType enp) { switch (enp) { case ENP_future: return out << "future"; case ENP_transition: return out << "transition"; case ENP_deprecated: return out << "deprecated"; case ENP_notify: return out << "notify"; } return out << "**invalid EmptyNodePathType value (" << (int)enp << ")**"; } istream &operator >> (istream &in, EmptyNodePathType &enp) { string word; in >> word; if (word == "future") { enp = ENP_future; } else if (word == "transition") { enp = ENP_transition; } else if (word == "deprecated") { enp = ENP_deprecated; } else if (word == "notify") { enp = ENP_notify; } else { pgraph_cat.warning() << "Invalid EmptyNodePathType value (\"" << word << "\")\n"; enp = ENP_transition; } return in; } static ConfigVariableEnum<EmptyNodePathType> empty_node_path ("empty-node-path", ENP_future, PRC_DESC("This is a temporary transition variable to control the behavior " "of a NodePath when it is used as a boolean false. Set this to " "'deprecated' to preserve the original behavior: every NodePath " "evaluates true, even an empty NodePath. Set it to 'future' to " "support the new behavior: non-empty NodePaths evaluate true, " "and empty NodePaths evaluate false. Set it to 'transition' to " "raise an exception if an empty NodePath is used as a boolean.")); // ***End temporary transition code for operator bool //////////////////////////////////////////////////////////////////// // Function: NodePath::Constructor // Access: Published // Description: Constructs a NodePath with the indicated parent // NodePath and child node; the child node must be a // stashed or unstashed child of the parent. //////////////////////////////////////////////////////////////////// NodePath:: NodePath(const NodePath &parent, PandaNode *child_node, Thread *current_thread) : _error_type(ET_fail) { nassertv(child_node != (PandaNode *)NULL); int pipeline_stage = current_thread->get_pipeline_stage(); if (parent.is_empty()) { // Special case: constructing a NodePath at the root. _head = PandaNode::get_top_component(child_node, true, pipeline_stage, current_thread); } else { _head = PandaNode::get_component(parent._head, child_node, pipeline_stage, current_thread); } nassertv(_head != (NodePathComponent *)NULL); if (_head != (NodePathComponent *)NULL) { _error_type = ET_ok; } _backup_key = 0; } //////////////////////////////////////////////////////////////////// // Function: NodePath::operator bool // Access: Published // Description: Returns true if the NodePath is valid (not empty), // or false if it contains no nodes. //////////////////////////////////////////////////////////////////// NodePath:: operator bool () const { switch (empty_node_path) { case ENP_future: return !is_empty(); case ENP_deprecated: return true; case ENP_notify: { const char *msg = "NodePath being used as a Boolean (talk to Zac)"; #ifdef HAVE_PYTHON PyErr_Warn(PyExc_FutureWarning, (char *)msg); #endif return !is_empty(); } case ENP_transition: if (!is_empty()) { return true; } { const char *message = "Using an empty NodePath as a boolean value. Because the meaning of this operation is changing, you should avoid doing this to avoid ambiguity, or set the config variable empty-node-path to 'future' or 'deprecated' to specify the desired behavior."; pgraph_cat.warning() << message << "\n"; #ifdef HAVE_PYTHON PyErr_Warn(PyExc_FutureWarning, (char *)message); #endif } return true; } nassertr(false, true); return true; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_num_nodes // Access: Published // Description: Returns the number of nodes in the path. //////////////////////////////////////////////////////////////////// int NodePath:: get_num_nodes(Thread *current_thread) const { if (is_empty()) { return 0; } int pipeline_stage = current_thread->get_pipeline_stage(); return _head->get_length(pipeline_stage, current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_node // Access: Published // Description: Returns the nth node of the path, where 0 is the // referenced (bottom) node and get_num_nodes() - 1 is // the top node. This requires iterating through the // path. // // Also see node(), which is a convenience function to // return the same thing as get_node(0) (since the // bottom node is the most important node in the // NodePath, and is the one most frequently referenced). // // Note that this function returns the same thing as // get_ancestor(index).node(). //////////////////////////////////////////////////////////////////// PandaNode *NodePath:: get_node(int index, Thread *current_thread) const { nassertr(index >= 0 && index < get_num_nodes(), NULL); int pipeline_stage = current_thread->get_pipeline_stage(); NodePathComponent *comp = _head; while (index > 0) { // If this assertion fails, the index was out of range; the // component's length must have been invalid. nassertr(comp != (NodePathComponent *)NULL, NULL); comp = comp->get_next(pipeline_stage, current_thread); index--; } // If this assertion fails, the index was out of range; the // component's length must have been invalid. nassertr(comp != (NodePathComponent *)NULL, NULL); return comp->get_node(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_ancestor // Access: Published // Description: Returns the nth ancestor of the path, where 0 is the // NodePath itself and get_num_nodes() - 1 is get_top(). // This requires iterating through the path. // // Also see get_node(), which returns the same thing as // a PandaNode pointer, not a NodePath. //////////////////////////////////////////////////////////////////// NodePath NodePath:: get_ancestor(int index, Thread *current_thread) const { nassertr(index >= 0 && index < get_num_nodes(), NodePath::fail()); int pipeline_stage = current_thread->get_pipeline_stage(); NodePathComponent *comp = _head; while (index > 0) { // If this assertion fails, the index was out of range; the // component's length must have been invalid. nassertr(comp != (NodePathComponent *)NULL, NodePath::fail()); comp = comp->get_next(pipeline_stage, current_thread); index--; } // If this assertion fails, the index was out of range; the // component's length must have been invalid. nassertr(comp != (NodePathComponent *)NULL, NodePath::fail()); NodePath result; result._head = comp; return result; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_top // Access: Published // Description: Returns a singleton NodePath that represents the top // of the path, or empty NodePath if this path is empty. //////////////////////////////////////////////////////////////////// NodePath NodePath:: get_top(Thread *current_thread) const { if (is_empty()) { return *this; } int pipeline_stage = current_thread->get_pipeline_stage(); NodePathComponent *comp = _head; while (!comp->is_top_node(pipeline_stage, current_thread)) { comp = comp->get_next(pipeline_stage, current_thread); nassertr(comp != (NodePathComponent *)NULL, NodePath::fail()); } NodePath top; top._head = comp; return top; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_children // Access: Published // Description: Returns the set of all child nodes of the referenced // node. //////////////////////////////////////////////////////////////////// NodePathCollection NodePath:: get_children(Thread *current_thread) const { NodePathCollection result; nassertr_always(!is_empty(), result); PandaNode *bottom_node = node(); int pipeline_stage = current_thread->get_pipeline_stage(); PandaNode::Children cr = bottom_node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { NodePath child; child._head = PandaNode::get_component(_head, cr.get_child(i), pipeline_stage, current_thread); result.add_path(child); } return result; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_stashed_children // Access: Published // Description: Returns the set of all child nodes of the referenced // node that have been stashed. These children are not // normally visible on the node, and do not appear in // the list returned by get_children(). //////////////////////////////////////////////////////////////////// NodePathCollection NodePath:: get_stashed_children(Thread *current_thread) const { NodePathCollection result; nassertr_always(!is_empty(), result); PandaNode *bottom_node = node(); int pipeline_stage = current_thread->get_pipeline_stage(); int num_stashed = bottom_node->get_num_stashed(); for (int i = 0; i < num_stashed; i++) { NodePath stashed; stashed._head = PandaNode::get_component(_head, bottom_node->get_stashed(i), pipeline_stage, current_thread); result.add_path(stashed); } return result; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_sort // Access: Published // Description: Returns the sort value of the referenced node within // its parent; that is, the sort number passed on the // last reparenting operation for this node. This will // control the position of the node within its parent's // list of children. //////////////////////////////////////////////////////////////////// int NodePath:: get_sort(Thread *current_thread) const { if (!has_parent()) { return 0; } int pipeline_stage = current_thread->get_pipeline_stage(); PandaNode *parent = _head->get_next(pipeline_stage, current_thread)->get_node(); PandaNode *child = node(); nassertr(parent != (PandaNode *)NULL && child != (PandaNode *)NULL, 0); int child_index = parent->find_child(child); if (child_index != -1) { return parent->get_child_sort(child_index); } child_index = parent->find_stashed(child); if (child_index != -1) { return parent->get_stashed_sort(child_index); } nassertr(false, 0); return 0; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find // Access: Published // Description: Searches for a node below the referenced node that // matches the indicated string. Returns the shortest // match found, if any, or an empty NodePath if no match // can be found. //////////////////////////////////////////////////////////////////// NodePath NodePath:: find(const string &path) const { nassertr_always(!is_empty(), fail()); NodePathCollection col; find_matches(col, path, 1); if (col.is_empty()) { return NodePath::not_found(); } return col.get_path(0); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_path_to // Access: Published // Description: Searches for the indicated node below this node and // returns the shortest NodePath that connects them. //////////////////////////////////////////////////////////////////// NodePath NodePath:: find_path_to(PandaNode *node) const { nassertr_always(!is_empty(), fail()); nassertr(node != (PandaNode *)NULL, fail()); NodePathCollection col; FindApproxPath approx_path; approx_path.add_match_many(0); approx_path.add_match_pointer(node, 0); find_matches(col, approx_path, 1); if (col.is_empty()) { return NodePath::not_found(); } return col.get_path(0); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_matches // Access: Published // Description: Returns the complete set of all NodePaths that begin // with this NodePath and can be extended by // path. The shortest paths will be listed // first. //////////////////////////////////////////////////////////////////// NodePathCollection NodePath:: find_all_matches(const string &path) const { NodePathCollection col; nassertr_always(!is_empty(), col); nassertr(verify_complete(), col); find_matches(col, path, -1); return col; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_paths_to // Access: Published // Description: Returns the set of all NodePaths that extend from // this NodePath down to the indicated node. The // shortest paths will be listed first. //////////////////////////////////////////////////////////////////// NodePathCollection NodePath:: find_all_paths_to(PandaNode *node) const { NodePathCollection col; nassertr_always(!is_empty(), col); nassertr(verify_complete(), col); nassertr(node != (PandaNode *)NULL, col); FindApproxPath approx_path; approx_path.add_match_many(0); approx_path.add_match_pointer(node, 0); find_matches(col, approx_path, -1); return col; } //////////////////////////////////////////////////////////////////// // Function: NodePath::reparent_to // Access: Published // Description: Removes the referenced node of the NodePath from its // current parent and attaches it to the referenced node // of the indicated NodePath. // // If the destination NodePath is empty, this is the // same thing as detach_node(). // // If the referenced node is already a child of the // indicated NodePath (via some other instance), this // operation fails and leaves the NodePath detached. //////////////////////////////////////////////////////////////////// void NodePath:: reparent_to(const NodePath &other, int sort, Thread *current_thread) { nassertv(verify_complete()); nassertv(other.verify_complete()); nassertv_always(!is_empty()); nassertv(other._error_type == ET_ok); // Reparenting implicitly resets the delta vector. node()->reset_prev_transform(); int pipeline_stage = current_thread->get_pipeline_stage(); bool reparented = PandaNode::reparent(other._head, _head, sort, false, pipeline_stage, current_thread); nassertv(reparented); } //////////////////////////////////////////////////////////////////// // Function: NodePath::stash_to // Access: Published // Description: Similar to reparent_to(), but the node is added to // its new parent's stashed list, so that the result is // equivalent to calling reparent_to() immediately // followed by stash(). //////////////////////////////////////////////////////////////////// void NodePath:: stash_to(const NodePath &other, int sort, Thread *current_thread) { nassertv(verify_complete()); nassertv(other.verify_complete()); nassertv_always(!is_empty()); nassertv(other._error_type == ET_ok); // Reparenting implicitly resets the delta vector. node()->reset_prev_transform(); int pipeline_stage = current_thread->get_pipeline_stage(); bool reparented = PandaNode::reparent(other._head, _head, sort, true, pipeline_stage, current_thread); nassertv(reparented); } //////////////////////////////////////////////////////////////////// // Function: NodePath::wrt_reparent_to // Access: Published // Description: This functions identically to reparent_to(), except // the transform on this node is also adjusted so that // the node remains in the same place in world // coordinates, even if it is reparented into a // different coordinate system. //////////////////////////////////////////////////////////////////// void NodePath:: wrt_reparent_to(const NodePath &other, int sort, Thread *current_thread) { nassertv(verify_complete(current_thread)); nassertv(other.verify_complete(current_thread)); nassertv_always(!is_empty()); nassertv(other._error_type == ET_ok); if (get_transform(current_thread) == get_prev_transform(current_thread)) { set_transform(get_transform(other, current_thread), current_thread); node()->reset_prev_transform(current_thread); } else { set_transform(get_transform(other, current_thread), current_thread); set_prev_transform(get_prev_transform(other, current_thread), current_thread); } reparent_to(other, sort, current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::instance_to // Access: Published // Description: Adds the referenced node of the NodePath as a child // of the referenced node of the indicated other // NodePath. Any other parent-child relations of the // node are unchanged; in particular, the node is not // removed from its existing parent, if any. // // If the node already had an existing parent, this // method will create a new instance of the node within // the scene graph. // // This does not change the NodePath itself, but does // return a new NodePath that reflects the new instance // node. // // If the destination NodePath is empty, this creates a // new instance which is not yet parented to any node. // A new instance of this sort cannot easily be // differentiated from other similar instances, but it // is nevertheless a different instance and it will // return a different get_id() value. // // If the referenced node is already a child of the // indicated NodePath, returns that already-existing // instance, unstashing it first if necessary. //////////////////////////////////////////////////////////////////// NodePath NodePath:: instance_to(const NodePath &other, int sort, Thread *current_thread) const { nassertr(verify_complete(), NodePath::fail()); nassertr(other.verify_complete(), NodePath::fail()); nassertr_always(!is_empty(), NodePath::fail()); nassertr(other._error_type == ET_ok, NodePath::fail()); NodePath new_instance; // First, we'll attach to NULL, to guarantee we get a brand new // instance. int pipeline_stage = current_thread->get_pipeline_stage(); new_instance._head = PandaNode::attach(NULL, node(), sort, pipeline_stage, current_thread); // Now, we'll reparent the new instance to the target node. bool reparented = PandaNode::reparent(other._head, new_instance._head, sort, false, pipeline_stage, current_thread); if (!reparented) { // Hmm, couldn't reparent. Either making this instance would // create a cycle, or it was already a child of that node. If it // was already a child, return that existing NodePath instead. NodePath orig(other, node(), current_thread); if (!orig.is_empty()) { if (orig.is_stashed()) { orig.unstash(); } return orig; } // Nope, it must be a cycle. nassertr(reparented, new_instance); } // instance_to() doesn't reset the velocity delta, unlike most of // the other reparenting operations. The reasoning is that // instance_to() is not necessarily a reparenting operation, since // it doesn't change the original instance. return new_instance; } //////////////////////////////////////////////////////////////////// // Function: NodePath::instance_under_node // Access: Published // Description: Behaves like instance_to(), but implicitly creates a // new node to instance the geometry under, and returns a // NodePath to that new node. This allows the // programmer to set a unique state and/or transform on // this instance. //////////////////////////////////////////////////////////////////// NodePath NodePath:: instance_under_node(const NodePath &other, const string &name, int sort, Thread *current_thread) const { NodePath new_node = other.attach_new_node(name, sort, current_thread); NodePath instance = instance_to(new_node, 0, current_thread); if (instance.is_empty()) { new_node.remove_node(current_thread); return instance; } return new_node; } //////////////////////////////////////////////////////////////////// // Function: NodePath::copy_to // Access: Published // Description: Functions like instance_to(), except a deep // copy is made of the referenced node and all of its // descendents, which is then parented to the indicated // node. A NodePath to the newly created copy is // returned. //////////////////////////////////////////////////////////////////// NodePath NodePath:: copy_to(const NodePath &other, int sort, Thread *current_thread) const { nassertr(verify_complete(current_thread), fail()); nassertr(other.verify_complete(current_thread), fail()); nassertr_always(!is_empty(), fail()); nassertr(other._error_type == ET_ok, fail()); PandaNode *source_node = node(); PT(PandaNode) copy_node = source_node->copy_subgraph(current_thread); nassertr(copy_node != (PandaNode *)NULL, fail()); copy_node->reset_prev_transform(current_thread); return other.attach_new_node(copy_node, sort, current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::attach_new_node // Access: Published // Description: Attaches a new node, with or without existing // parents, to the scene graph below the referenced node // of this NodePath. This is the preferred way to add // nodes to the graph. // // If the node was already a child of the parent, this // returns a NodePath to the existing child. // // This does *not* automatically extend the current // NodePath to reflect the attachment; however, a // NodePath that does reflect this extension is // returned. //////////////////////////////////////////////////////////////////// NodePath NodePath:: attach_new_node(PandaNode *node, int sort, Thread *current_thread) const { nassertr(verify_complete(current_thread), NodePath::fail()); nassertr(_error_type == ET_ok, NodePath::fail()); nassertr(node != (PandaNode *)NULL, NodePath::fail()); NodePath new_path(*this); int pipeline_stage = current_thread->get_pipeline_stage(); new_path._head = PandaNode::attach(_head, node, sort, pipeline_stage, current_thread); return new_path; } //////////////////////////////////////////////////////////////////// // Function: NodePath::remove_node // Access: Published // Description: Disconnects the referenced node from the scene graph. // This will also delete the node if there are no other // pointers to it. // // Normally, this should be called only when you are // really done with the node. If you want to remove a // node from the scene graph but keep it around for // later, you should probably use detach_node() instead. // // In practice, the only difference between // remove_node() and detach_node() is that remove_node() // also resets the NodePath to empty, which will cause // the node to be deleted immediately if there are no // other references. On the other hand, detach_node() // leaves the NodePath referencing the node, which will // keep at least one reference to the node for as long // as the NodePath exists. //////////////////////////////////////////////////////////////////// void NodePath:: remove_node(Thread *current_thread) { nassertv(_error_type != ET_not_found); // If we have no parents, remove_node() is just a do-nothing // operation; if we have no nodes, maybe we were already removed. // In either case, quietly do nothing except to ensure the // NodePath is clear. if (!is_empty() && !is_singleton(current_thread)) { node()->reset_prev_transform(current_thread); int pipeline_stage = current_thread->get_pipeline_stage(); PandaNode::detach(_head, pipeline_stage, current_thread); } if (is_empty() || _head->has_key()) { // Preserve the key we had on the node before we removed it. int key = get_key(); (*this) = NodePath::removed(); _backup_key = key; } else { // We didn't have a key; just clear the NodePath. (*this) = NodePath::removed(); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::detach_node // Access: Published // Description: Disconnects the referenced node from its parent, but // does not immediately delete it. The NodePath retains // a pointer to the node, and becomes a singleton // NodePath. // // This should be called to detach a node from the scene // graph, with the option of reattaching it later to the // same parent or to a different parent. // // In practice, the only difference between // remove_node() and detach_node() is that remove_node() // also resets the NodePath to empty, which will cause // the node to be deleted immediately if there are no // other references. On the other hand, detach_node() // leaves the NodePath referencing the node, which will // keep at least one reference to the node for as long // as the NodePath exists. //////////////////////////////////////////////////////////////////// void NodePath:: detach_node(Thread *current_thread) { nassertv(_error_type != ET_not_found); if (!is_empty() && !is_singleton()) { node()->reset_prev_transform(); int pipeline_stage = current_thread->get_pipeline_stage(); PandaNode::detach(_head, pipeline_stage, current_thread); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::output // Access: Published // Description: Writes a sensible description of the NodePath to the // indicated output stream. //////////////////////////////////////////////////////////////////// void NodePath:: output(ostream &out) const { switch (_error_type) { case ET_not_found: out << "**not found**"; return; case ET_removed: out << "**removed**"; return; case ET_fail: out << "**error**"; return; default: break; } if (_head == (NodePathComponent *)NULL) { out << "(empty)"; } else { _head->output(out); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_state // Access: Published // Description: Returns the complete state object set on this node. //////////////////////////////////////////////////////////////////// const RenderState *NodePath:: get_state(Thread *current_thread) const { // This method is declared non-inline to avoid a compiler bug in // gcc-3.4 and gcc-4.0. nassertr_always(!is_empty(), RenderState::make_empty()); return node()->get_state(current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_state // Access: Published // Description: Returns the state changes that must be made to // transition to the render state of this node from the // render state of the other node. //////////////////////////////////////////////////////////////////// CPT(RenderState) NodePath:: get_state(const NodePath &other, Thread *current_thread) const { nassertr(_error_type == ET_ok && other._error_type == ET_ok, RenderState::make_empty()); if (other.is_empty()) { return get_net_state(current_thread); } if (is_empty()) { return other.get_net_state(current_thread)->invert_compose(RenderState::make_empty()); } nassertr(verify_complete(current_thread), RenderState::make_empty()); nassertr(other.verify_complete(current_thread), RenderState::make_empty()); int a_count, b_count; if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == (NodePathComponent *)NULL) { if (allow_unrelated_wrt) { pgraph_cat.debug() << *this << " is not related to " << other << "\n"; } else { pgraph_cat.error() << *this << " is not related to " << other << "\n"; nassertr(false, RenderState::make_empty()); } } CPT(RenderState) a_state = r_get_partial_state(_head, a_count, current_thread); CPT(RenderState) b_state = r_get_partial_state(other._head, b_count, current_thread); return b_state->invert_compose(a_state); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_state // Access: Published // Description: Sets the state object on this node, relative to // the other node. This computes a new state object // that will have the indicated value when seen from the // other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_state(const NodePath &other, const RenderState *state, Thread *current_thread) { nassertv(_error_type == ET_ok && other._error_type == ET_ok); nassertv_always(!is_empty()); // First, we perform a wrt to the parent, to get the conversion. CPT(RenderState) rel_state; if (has_parent()) { rel_state = other.get_state(get_parent(current_thread), current_thread); } else { rel_state = other.get_state(NodePath(), current_thread); } CPT(RenderState) new_state = rel_state->compose(state); set_state(new_state, current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_transform // Access: Published // Description: Returns the complete transform object set on this node. //////////////////////////////////////////////////////////////////// const TransformState *NodePath:: get_transform(Thread *current_thread) const { // This method is declared non-inline to avoid a compiler bug in // gcc-3.4 and gcc-4.0. nassertr_always(!is_empty(), TransformState::make_identity()); return node()->get_transform(current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_transform // Access: Published // Description: Returns the relative transform to this node from the // other node; i.e. the transformation of this node // as seen from the other node. //////////////////////////////////////////////////////////////////// CPT(TransformState) NodePath:: get_transform(const NodePath &other, Thread *current_thread) const { nassertr(_error_type == ET_ok && other._error_type == ET_ok, TransformState::make_identity()); PStatTimer timer(_get_transform_pcollector); if (other.is_empty()) { return get_net_transform(current_thread); } if (is_empty()) { return other.get_net_transform(current_thread)->invert_compose(TransformState::make_identity()); } nassertr(verify_complete(current_thread), TransformState::make_identity()); nassertr(other.verify_complete(current_thread), TransformState::make_identity()); int a_count, b_count; if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == (NodePathComponent *)NULL) { if (allow_unrelated_wrt) { if (pgraph_cat.is_debug()) { pgraph_cat.debug() << *this << " is not related to " << other << "\n"; } } else { pgraph_cat.error() << *this << " is not related to " << other << "\n"; nassertr(false, TransformState::make_identity()); } } CPT(TransformState) a_transform, b_transform; a_transform = r_get_partial_transform(_head, a_count, current_thread); if (a_transform != (TransformState *)NULL) { b_transform = r_get_partial_transform(other._head, b_count, current_thread); } if (b_transform == (TransformState *)NULL) { // If either path involved a node with a net_transform // RenderEffect applied, we have to go all the way up to the root // to get the right answer. a_transform = r_get_net_transform(_head, current_thread); b_transform = r_get_net_transform(other._head, current_thread); } return b_transform->invert_compose(a_transform); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_transform // Access: Published // Description: Sets the transform object on this node, relative to // the other node. This computes a new transform object // that will have the indicated value when seen from the // other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_transform(const NodePath &other, const TransformState *transform, Thread *current_thread) { nassertv(_error_type == ET_ok && other._error_type == ET_ok); nassertv_always(!is_empty()); // First, we perform a wrt to the parent, to get the conversion. CPT(TransformState) rel_trans; if (has_parent()) { rel_trans = other.get_transform(get_parent(current_thread), current_thread); } else { rel_trans = other.get_transform(NodePath(), current_thread); } CPT(TransformState) new_trans = rel_trans->compose(transform); set_transform(new_trans, current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_prev_transform // Access: Published // Description: Returns the transform that has been set as this // node's "previous" position. See // set_prev_transform(). //////////////////////////////////////////////////////////////////// const TransformState *NodePath:: get_prev_transform(Thread *current_thread) const { // This method is declared non-inline to avoid a compiler bug in // gcc-3.4 and gcc-4.0. nassertr_always(!is_empty(), TransformState::make_identity()); return node()->get_prev_transform(current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_prev_transform // Access: Published // Description: Returns the relative "previous" transform to this // node from the other node; i.e. the position of this // node in the previous frame, as seen by the other node // in the previous frame. //////////////////////////////////////////////////////////////////// CPT(TransformState) NodePath:: get_prev_transform(const NodePath &other, Thread *current_thread) const { nassertr(_error_type == ET_ok && other._error_type == ET_ok, TransformState::make_identity()); if (other.is_empty()) { return get_net_prev_transform(current_thread); } if (is_empty()) { return other.get_net_prev_transform(current_thread)->invert_compose(TransformState::make_identity()); } nassertr(verify_complete(current_thread), TransformState::make_identity()); nassertr(other.verify_complete(current_thread), TransformState::make_identity()); int a_count, b_count; if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == (NodePathComponent *)NULL) { if (allow_unrelated_wrt) { pgraph_cat.debug() << *this << " is not related to " << other << "\n"; } else { pgraph_cat.error() << *this << " is not related to " << other << "\n"; nassertr(false, TransformState::make_identity()); } } CPT(TransformState) a_prev_transform = r_get_partial_prev_transform(_head, a_count, current_thread); CPT(TransformState) b_prev_transform = r_get_partial_prev_transform(other._head, b_count, current_thread); return b_prev_transform->invert_compose(a_prev_transform); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_prev_transform // Access: Published // Description: Sets the "previous" transform object on this node, // relative to the other node. This computes a new // transform object that will have the indicated value // when seen from the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_prev_transform(const NodePath &other, const TransformState *transform, Thread *current_thread) { nassertv(_error_type == ET_ok && other._error_type == ET_ok); nassertv_always(!is_empty()); // First, we perform a wrt to the parent, to get the conversion. CPT(TransformState) rel_trans; if (has_parent(current_thread)) { rel_trans = other.get_prev_transform(get_parent(current_thread), current_thread); } else { rel_trans = other.get_prev_transform(NodePath(), current_thread); } CPT(TransformState) new_trans = rel_trans->compose(transform); set_prev_transform(new_trans, current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos // Access: Published // Description: Sets the translation component of the transform, // leaving rotation and scale untouched. This also // resets the node's "previous" position, so that the // collision system will see the node as having suddenly // appeared in the new position, without passing any // points in between. // See Also: NodePath::set_fluid_pos //////////////////////////////////////////////////////////////////// void NodePath:: set_pos(const LVecBase3 &pos) { nassertv_always(!is_empty()); set_transform(get_transform()->set_pos(pos)); node()->reset_prev_transform(); } void NodePath:: set_x(PN_stdfloat x) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(); pos[0] = x; set_pos(pos); } void NodePath:: set_y(PN_stdfloat y) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(); pos[1] = y; set_pos(pos); } void NodePath:: set_z(PN_stdfloat z) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(); pos[2] = z; set_pos(pos); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_fluid_pos // Access: Published // Description: Sets the translation component, without changing the // "previous" position, so that the collision system // will see the node as moving fluidly from its previous // position to its new position. // See Also: NodePath::set_pos //////////////////////////////////////////////////////////////////// void NodePath:: set_fluid_pos(const LVecBase3 &pos) { nassertv_always(!is_empty()); set_transform(get_transform()->set_pos(pos)); } void NodePath:: set_fluid_x(PN_stdfloat x) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(); pos[0] = x; set_fluid_pos(pos); } void NodePath:: set_fluid_y(PN_stdfloat y) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(); pos[1] = y; set_fluid_pos(pos); } void NodePath:: set_fluid_z(PN_stdfloat z) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(); pos[2] = z; set_fluid_pos(pos); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_pos // Access: Published // Description: Retrieves the translation component of the transform. //////////////////////////////////////////////////////////////////// LPoint3 NodePath:: get_pos() const { nassertr_always(!is_empty(), LPoint3(0.0f, 0.0f, 0.0f)); return get_transform()->get_pos(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_pos_delta // Access: Published // Description: Returns the delta vector from this node's position in // the previous frame (according to // set_prev_transform(), typically set via the use of // set_fluid_pos()) and its position in the current // frame. This is the vector used to determine // collisions. Generally, if the node was last // repositioned via set_pos(), the delta will be zero; // if it was adjusted via set_fluid_pos(), the delta // will represent the change from the previous frame's // position. //////////////////////////////////////////////////////////////////// LVector3 NodePath:: get_pos_delta() const { nassertr_always(!is_empty(), LPoint3(0.0f, 0.0f, 0.0f)); return get_transform()->get_pos() - get_prev_transform()->get_pos(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_hpr // Access: Published // Description: Sets the rotation component of the transform, // leaving translation and scale untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_hpr(const LVecBase3 &hpr) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); nassertv(transform->has_hpr()); set_transform(transform->set_hpr(hpr)); } void NodePath:: set_h(PN_stdfloat h) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); nassertv(transform->has_hpr()); LVecBase3 hpr = transform->get_hpr(); hpr[0] = h; set_transform(transform->set_hpr(hpr)); } void NodePath:: set_p(PN_stdfloat p) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); nassertv(transform->has_hpr()); LVecBase3 hpr = transform->get_hpr(); hpr[1] = p; set_transform(transform->set_hpr(hpr)); } void NodePath:: set_r(PN_stdfloat r) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); nassertv(transform->has_hpr()); LVecBase3 hpr = transform->get_hpr(); hpr[2] = r; set_transform(transform->set_hpr(hpr)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_hpr // Access: Published // Description: Retrieves the rotation component of the transform. //////////////////////////////////////////////////////////////////// LVecBase3 NodePath:: get_hpr() const { nassertr_always(!is_empty(), LVecBase3(0.0f, 0.0f, 0.0f)); CPT(TransformState) transform = get_transform(); nassertr(transform->has_hpr(), LVecBase3(0.0f, 0.0f, 0.0f)); return transform->get_hpr(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_quat // Access: Published // Description: Sets the rotation component of the transform, // leaving translation and scale untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_quat(const LQuaternion &quat) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); set_transform(transform->set_quat(quat)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_quat // Access: Published // Description: Retrieves the rotation component of the transform. //////////////////////////////////////////////////////////////////// LQuaternion NodePath:: get_quat() const { nassertr_always(!is_empty(), LQuaternion::ident_quat()); CPT(TransformState) transform = get_transform(); return transform->get_quat(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_scale // Access: Published // Description: Sets the scale component of the transform, // leaving translation and rotation untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_scale(const LVecBase3 &scale) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); set_transform(transform->set_scale(scale)); } void NodePath:: set_sx(PN_stdfloat sx) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); LVecBase3 scale = transform->get_scale(); scale[0] = sx; set_transform(transform->set_scale(scale)); } void NodePath:: set_sy(PN_stdfloat sy) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); LVecBase3 scale = transform->get_scale(); scale[1] = sy; set_transform(transform->set_scale(scale)); } void NodePath:: set_sz(PN_stdfloat sz) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); LVecBase3 scale = transform->get_scale(); scale[2] = sz; set_transform(transform->set_scale(scale)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_scale // Access: Published // Description: Retrieves the scale component of the transform. //////////////////////////////////////////////////////////////////// LVecBase3 NodePath:: get_scale() const { nassertr_always(!is_empty(), LVecBase3(0.0f, 0.0f, 0.0f)); CPT(TransformState) transform = get_transform(); return transform->get_scale(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_shear // Access: Published // Description: Sets the shear component of the transform, // leaving translation and rotation untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_shear(const LVecBase3 &shear) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); set_transform(transform->set_shear(shear)); } void NodePath:: set_shxy(PN_stdfloat shxy) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); LVecBase3 shear = transform->get_shear(); shear[0] = shxy; set_transform(transform->set_shear(shear)); } void NodePath:: set_shxz(PN_stdfloat shxz) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); LVecBase3 shear = transform->get_shear(); shear[1] = shxz; set_transform(transform->set_shear(shear)); } void NodePath:: set_shyz(PN_stdfloat shyz) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); LVecBase3 shear = transform->get_shear(); shear[2] = shyz; set_transform(transform->set_shear(shear)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_shear // Access: Published // Description: Retrieves the shear component of the transform. //////////////////////////////////////////////////////////////////// LVecBase3 NodePath:: get_shear() const { nassertr_always(!is_empty(), LVecBase3(0.0f, 0.0f, 0.0f)); CPT(TransformState) transform = get_transform(); return transform->get_shear(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_hpr // Access: Published // Description: Sets the translation and rotation component of the // transform, leaving scale untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_hpr(const LVecBase3 &pos, const LVecBase3 &hpr) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); transform = TransformState::make_pos_hpr_scale_shear (pos, hpr, transform->get_scale(), transform->get_shear()); set_transform(transform); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_quat // Access: Published // Description: Sets the translation and rotation component of the // transform, leaving scale untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_quat(const LVecBase3 &pos, const LQuaternion &quat) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); transform = TransformState::make_pos_quat_scale_shear (pos, quat, transform->get_scale(), transform->get_shear()); set_transform(transform); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_hpr_scale // Access: Published // Description: Sets the rotation and scale components of the // transform, leaving translation untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_hpr_scale(const LVecBase3 &hpr, const LVecBase3 &scale) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); transform = TransformState::make_pos_hpr_scale_shear (transform->get_pos(), hpr, scale, transform->get_shear()); set_transform(transform); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_quat_scale // Access: Published // Description: Sets the rotation and scale components of the // transform, leaving translation untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_quat_scale(const LQuaternion &quat, const LVecBase3 &scale) { nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(); transform = TransformState::make_pos_quat_scale_shear (transform->get_pos(), quat, scale, transform->get_shear()); set_transform(transform); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_hpr_scale // Access: Published // Description: Replaces the translation, rotation, and scale // components, implicitly setting shear to 0. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_hpr_scale(const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale) { nassertv_always(!is_empty()); set_transform(TransformState::make_pos_hpr_scale (pos, hpr, scale)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_quat_scale // Access: Published // Description: Replaces the translation, rotation, and scale // components, implicitly setting shear to 0. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_quat_scale(const LVecBase3 &pos, const LQuaternion &quat, const LVecBase3 &scale) { nassertv_always(!is_empty()); set_transform(TransformState::make_pos_quat_scale (pos, quat, scale)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_hpr_scale_shear // Access: Published // Description: Completely replaces the transform with new // translation, rotation, scale, and shear components. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_hpr_scale_shear(const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale, const LVecBase3 &shear) { nassertv_always(!is_empty()); set_transform(TransformState::make_pos_hpr_scale_shear (pos, hpr, scale, shear)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_quat_scale_shear // Access: Published // Description: Completely replaces the transform with new // translation, rotation, scale, and shear components. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_quat_scale_shear(const LVecBase3 &pos, const LQuaternion &quat, const LVecBase3 &scale, const LVecBase3 &shear) { nassertv_always(!is_empty()); set_transform(TransformState::make_pos_quat_scale_shear (pos, quat, scale, shear)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_mat // Access: Published // Description: Directly sets an arbitrary 4x4 transform matrix. //////////////////////////////////////////////////////////////////// void NodePath:: set_mat(const LMatrix4 &mat) { nassertv_always(!is_empty()); set_transform(TransformState::make_mat(mat)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::look_at // Access: Published // Description: Sets the hpr on this NodePath so that it // rotates to face the indicated point in space. //////////////////////////////////////////////////////////////////// void NodePath:: look_at(const LPoint3 &point, const LVector3 &up) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(); LQuaternion quat; ::look_at(quat, point - pos, up); set_quat(quat); } //////////////////////////////////////////////////////////////////// // Function: NodePath::heads_up // Access: Published // Description: Behaves like look_at(), but with a strong preference // to keeping the up vector oriented in the indicated // "up" direction. //////////////////////////////////////////////////////////////////// void NodePath:: heads_up(const LPoint3 &point, const LVector3 &up) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(); LQuaternion quat; ::heads_up(quat, point - pos, up); set_quat(quat); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos // Access: Published // Description: Sets the translation component of the transform, // relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos(const NodePath &other, const LVecBase3 &pos) { nassertv_always(!is_empty()); CPT(TransformState) rel_transform = get_transform(other); CPT(TransformState) orig_transform = get_transform(); if (orig_transform->has_components()) { // If we had a componentwise transform before we started, we // should be careful to preserve the other three components. We // wouldn't need to do this, except for the possibility of // numerical error or decompose ambiguity. const LVecBase3 &orig_hpr = orig_transform->get_hpr(); const LVecBase3 &orig_scale = orig_transform->get_scale(); const LVecBase3 &orig_shear = orig_transform->get_shear(); set_transform(other, rel_transform->set_pos(pos)); set_pos_hpr_scale_shear(get_transform()->get_pos(), orig_hpr, orig_scale, orig_shear); } else { // If we didn't have a componentwise transform already, never // mind. set_transform(other, rel_transform->set_pos(pos)); } node()->reset_prev_transform(); } void NodePath:: set_x(const NodePath &other, PN_stdfloat x) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(other); pos[0] = x; set_pos(other, pos); } void NodePath:: set_y(const NodePath &other, PN_stdfloat y) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(other); pos[1] = y; set_pos(other, pos); } void NodePath:: set_z(const NodePath &other, PN_stdfloat z) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(other); pos[2] = z; set_pos(other, pos); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_fluid_pos // Access: Published // Description: Sets the translation component of the transform, // relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_fluid_pos(const NodePath &other, const LVecBase3 &pos) { nassertv_always(!is_empty()); CPT(TransformState) rel_transform = get_transform(other); CPT(TransformState) orig_transform = get_transform(); if (orig_transform->has_components()) { // If we had a componentwise transform before we started, we // should be careful to preserve the other three components. We // wouldn't need to do this, except for the possibility of // numerical error or decompose ambiguity. const LVecBase3 &orig_hpr = orig_transform->get_hpr(); const LVecBase3 &orig_scale = orig_transform->get_scale(); const LVecBase3 &orig_shear = orig_transform->get_shear(); // Use the relative set_transform() to compute the relative pos, and // then reset all of the other components back to the way they were. set_transform(other, rel_transform->set_pos(pos)); set_transform(TransformState::make_pos_hpr_scale_shear (get_transform()->get_pos(), orig_hpr, orig_scale, orig_shear)); } else { // If we didn't have a componentwise transform already, never // mind. set_transform(other, rel_transform->set_pos(pos)); } } void NodePath:: set_fluid_x(const NodePath &other, PN_stdfloat x) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(other); pos[0] = x; set_fluid_pos(other, pos); } void NodePath:: set_fluid_y(const NodePath &other, PN_stdfloat y) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(other); pos[1] = y; set_fluid_pos(other, pos); } void NodePath:: set_fluid_z(const NodePath &other, PN_stdfloat z) { nassertv_always(!is_empty()); LPoint3 pos = get_pos(other); pos[2] = z; set_fluid_pos(other, pos); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_pos // Access: Published // Description: Returns the relative position of the referenced node // as seen from the other node. //////////////////////////////////////////////////////////////////// LPoint3 NodePath:: get_pos(const NodePath &other) const { nassertr_always(!is_empty(), LPoint3(0.0f, 0.0f, 0.0f)); return get_transform(other)->get_pos(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_pos_delta // Access: Published // Description: Returns the delta vector from this node's position in // the previous frame (according to // set_prev_transform(), typically set via the use of // set_fluid_pos()) and its position in the current // frame, as seen in the indicated node's coordinate // space. This is the vector used to determine // collisions. Generally, if the node was last // repositioned via set_pos(), the delta will be zero; // if it was adjusted via set_fluid_pos(), the delta // will represent the change from the previous frame's // position. //////////////////////////////////////////////////////////////////// LVector3 NodePath:: get_pos_delta(const NodePath &other) const { nassertr_always(!is_empty(), LPoint3(0.0f, 0.0f, 0.0f)); return get_transform(other)->get_pos() - get_prev_transform(other)->get_pos(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_hpr // Access: Published // Description: Sets the rotation component of the transform, // relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_hpr(const NodePath &other, const LVecBase3 &hpr) { nassertv_always(!is_empty()); CPT(TransformState) rel_transform = get_transform(other); nassertv(rel_transform->has_hpr()); CPT(TransformState) transform = get_transform(); if (transform->has_components()) { // If we had a componentwise transform before we started, we // should be careful to preserve the other three components. We // wouldn't need to do this, except for the possibility of // numerical error or decompose ambiguity. const LVecBase3 &orig_pos = transform->get_pos(); const LVecBase3 &orig_scale = transform->get_scale(); const LVecBase3 &orig_shear = transform->get_shear(); set_transform(other, rel_transform->set_hpr(hpr)); transform = get_transform(); if (transform->has_components()) { set_transform(TransformState::make_pos_hpr_scale_shear (orig_pos, transform->get_hpr(), orig_scale, orig_shear)); } } else { // If we didn't have a componentwise transform already, never // mind. set_transform(other, rel_transform->set_hpr(hpr)); } } void NodePath:: set_h(const NodePath &other, PN_stdfloat h) { nassertv_always(!is_empty()); LVecBase3 hpr = get_hpr(other); hpr[0] = h; set_hpr(other, hpr); } void NodePath:: set_p(const NodePath &other, PN_stdfloat p) { nassertv_always(!is_empty()); LVecBase3 hpr = get_hpr(other); hpr[1] = p; set_hpr(other, hpr); } void NodePath:: set_r(const NodePath &other, PN_stdfloat r) { nassertv_always(!is_empty()); LVecBase3 hpr = get_hpr(other); hpr[2] = r; set_hpr(other, hpr); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_hpr // Access: Published // Description: Returns the relative orientation of the bottom node // as seen from the other node. //////////////////////////////////////////////////////////////////// LVecBase3 NodePath:: get_hpr(const NodePath &other) const { nassertr_always(!is_empty(), LVecBase3(0.0f, 0.0f, 0.0f)); CPT(TransformState) transform = get_transform(other); nassertr(transform->has_hpr(), LVecBase3(0.0f, 0.0f, 0.0f)); return transform->get_hpr(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_quat // Access: Published // Description: Sets the rotation component of the transform, // relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_quat(const NodePath &other, const LQuaternion &quat) { nassertv_always(!is_empty()); CPT(TransformState) rel_transform = get_transform(other); CPT(TransformState) transform = get_transform(); if (transform->has_components()) { // If we had a componentwise transform before we started, we // should be careful to preserve the other three components. We // wouldn't need to do this, except for the possibility of // numerical error or decompose ambiguity. const LVecBase3 &orig_pos = transform->get_pos(); const LVecBase3 &orig_scale = transform->get_scale(); const LVecBase3 &orig_shear = transform->get_shear(); set_transform(other, rel_transform->set_quat(quat)); transform = get_transform(); if (transform->has_components()) { set_transform(TransformState::make_pos_quat_scale_shear (orig_pos, transform->get_quat(), orig_scale, orig_shear)); } } else { // If we didn't have a componentwise transform already, never // mind. set_transform(other, rel_transform->set_quat(quat)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_quat // Access: Published // Description: Returns the relative orientation of the bottom node // as seen from the other node. //////////////////////////////////////////////////////////////////// LQuaternion NodePath:: get_quat(const NodePath &other) const { nassertr_always(!is_empty(), LQuaternion::ident_quat()); CPT(TransformState) transform = get_transform(other); return transform->get_quat(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_scale // Access: Published // Description: Sets the scale component of the transform, // relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_scale(const NodePath &other, const LVecBase3 &scale) { nassertv_always(!is_empty()); CPT(TransformState) rel_transform = get_transform(other); CPT(TransformState) transform = get_transform(); if (transform->has_components()) { // If we had a componentwise transform before we started, we // should be careful to preserve the other three components. We // wouldn't need to do this, except for the possibility of // numerical error or decompose ambiguity. const LVecBase3 &orig_pos = transform->get_pos(); const LVecBase3 &orig_hpr = transform->get_hpr(); const LVecBase3 &orig_shear = transform->get_shear(); set_transform(other, rel_transform->set_scale(scale)); transform = get_transform(); if (transform->has_components()) { set_transform(TransformState::make_pos_hpr_scale_shear (orig_pos, orig_hpr, transform->get_scale(), orig_shear)); } } else { // If we didn't have a componentwise transform already, never // mind. set_transform(other, rel_transform->set_scale(scale)); } } void NodePath:: set_sx(const NodePath &other, PN_stdfloat sx) { nassertv_always(!is_empty()); LVecBase3 scale = get_scale(other); scale[0] = sx; set_scale(other, scale); } void NodePath:: set_sy(const NodePath &other, PN_stdfloat sy) { nassertv_always(!is_empty()); LVecBase3 scale = get_scale(other); scale[1] = sy; set_scale(other, scale); } void NodePath:: set_sz(const NodePath &other, PN_stdfloat sz) { nassertv_always(!is_empty()); LVecBase3 scale = get_scale(other); scale[2] = sz; set_scale(other, scale); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_scale // Access: Published // Description: Returns the relative scale of the bottom node // as seen from the other node. //////////////////////////////////////////////////////////////////// LVecBase3 NodePath:: get_scale(const NodePath &other) const { nassertr_always(!is_empty(), LVecBase3(0.0f, 0.0f, 0.0f)); CPT(TransformState) transform = get_transform(other); return transform->get_scale(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_shear // Access: Published // Description: Sets the shear component of the transform, // relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_shear(const NodePath &other, const LVecBase3 &shear) { nassertv_always(!is_empty()); CPT(TransformState) rel_transform = get_transform(other); CPT(TransformState) transform = get_transform(); if (transform->has_components()) { // If we had a componentwise transform before we started, we // should be careful to preserve the other three components. We // wouldn't need to do this, except for the possibility of // numerical error or decompose ambiguity. const LVecBase3 &orig_pos = transform->get_pos(); const LVecBase3 &orig_hpr = transform->get_hpr(); const LVecBase3 &orig_scale = transform->get_scale(); set_transform(other, rel_transform->set_shear(shear)); transform = get_transform(); if (transform->has_components()) { set_transform(TransformState::make_pos_hpr_scale_shear (orig_pos, orig_hpr, orig_scale, transform->get_shear())); } } else { // If we didn't have a componentwise transform already, never // mind. set_transform(other, rel_transform->set_shear(shear)); } } void NodePath:: set_shxy(const NodePath &other, PN_stdfloat shxy) { nassertv_always(!is_empty()); LVecBase3 shear = get_shear(other); shear[0] = shxy; set_shear(other, shear); } void NodePath:: set_shxz(const NodePath &other, PN_stdfloat shxz) { nassertv_always(!is_empty()); LVecBase3 shear = get_shear(other); shear[1] = shxz; set_shear(other, shear); } void NodePath:: set_shyz(const NodePath &other, PN_stdfloat shyz) { nassertv_always(!is_empty()); LVecBase3 shear = get_shear(other); shear[2] = shyz; set_shear(other, shear); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_shear // Access: Published // Description: Returns the relative shear of the bottom node // as seen from the other node. //////////////////////////////////////////////////////////////////// LVecBase3 NodePath:: get_shear(const NodePath &other) const { nassertr_always(!is_empty(), LVecBase3(0.0f, 0.0f, 0.0f)); CPT(TransformState) transform = get_transform(other); return transform->get_shear(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_hpr // Access: Published // Description: Sets the translation and rotation component of the // transform, relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_hpr(const NodePath &other, const LVecBase3 &pos, const LVecBase3 &hpr) { nassertv_always(!is_empty()); CPT(TransformState) rel_transform = get_transform(other); CPT(TransformState) transform = get_transform(); if (transform->has_components()) { // If we had a componentwise transform before we started, we // should be careful to preserve the other two components. We // wouldn't need to do this, except for the possibility of // numerical error or decompose ambiguity. const LVecBase3 &orig_scale = transform->get_scale(); const LVecBase3 &orig_shear = transform->get_shear(); set_transform(other, TransformState::make_pos_hpr_scale_shear (pos, hpr, rel_transform->get_scale(), rel_transform->get_shear())); transform = get_transform(); if (transform->has_components()) { set_pos_hpr_scale_shear(transform->get_pos(), transform->get_hpr(), orig_scale, orig_shear); } } else { // If we didn't have a componentwise transform already, never // mind. set_transform(other, TransformState::make_pos_hpr_scale_shear (pos, hpr, rel_transform->get_scale(), rel_transform->get_shear())); node()->reset_prev_transform(); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_quat // Access: Published // Description: Sets the translation and rotation component of the // transform, relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_quat(const NodePath &other, const LVecBase3 &pos, const LQuaternion &quat) { nassertv_always(!is_empty()); CPT(TransformState) rel_transform = get_transform(other); CPT(TransformState) transform = get_transform(); if (transform->has_components()) { // If we had a componentwise transform before we started, we // should be careful to preserve the other two components. We // wouldn't need to do this, except for the possibility of // numerical error or decompose ambiguity. const LVecBase3 &orig_scale = transform->get_scale(); const LVecBase3 &orig_shear = transform->get_shear(); set_transform(other, TransformState::make_pos_quat_scale_shear (pos, quat, rel_transform->get_scale(), rel_transform->get_shear())); transform = get_transform(); if (transform->has_components()) { set_pos_quat_scale_shear(transform->get_pos(), transform->get_quat(), orig_scale, orig_shear); } } else { // If we didn't have a componentwise transform already, never // mind. set_transform(other, TransformState::make_pos_quat_scale_shear (pos, quat, rel_transform->get_scale(), rel_transform->get_shear())); node()->reset_prev_transform(); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_hpr_scale // Access: Published // Description: Sets the rotation and scale components of the // transform, leaving translation untouched. This, or // set_pos_hpr_scale, is the preferred way to update a // transform when both hpr and scale are to be changed. //////////////////////////////////////////////////////////////////// void NodePath:: set_hpr_scale(const NodePath &other, const LVecBase3 &hpr, const LVecBase3 &scale) { // We don't bother trying very hard to preserve pos across this // operation, unlike the work we do above to preserve hpr or scale, // since it generally doesn't matter that much if pos is off by a // few thousandths. nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(other); transform = TransformState::make_pos_hpr_scale_shear (transform->get_pos(), hpr, scale, transform->get_shear()); set_transform(other, transform); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_quat_scale // Access: Published // Description: Sets the rotation and scale components of the // transform, leaving translation untouched. This, or // set_pos_quat_scale, is the preferred way to update a // transform when both quat and scale are to be changed. //////////////////////////////////////////////////////////////////// void NodePath:: set_quat_scale(const NodePath &other, const LQuaternion &quat, const LVecBase3 &scale) { // We don't bother trying very hard to preserve pos across this // operation, unlike the work we do above to preserve quat or scale, // since it generally doesn't matter that much if pos is off by a // few thousandths. nassertv_always(!is_empty()); CPT(TransformState) transform = get_transform(other); transform = TransformState::make_pos_quat_scale_shear (transform->get_pos(), quat, scale, transform->get_shear()); set_transform(other, transform); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_hpr_scale // Access: Published // Description: Completely replaces the transform with new // translation, rotation, and scale components, relative // to the other node, implicitly setting shear to 0. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_hpr_scale(const NodePath &other, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale) { nassertv_always(!is_empty()); set_transform(other, TransformState::make_pos_hpr_scale (pos, hpr, scale)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_quat_scale // Access: Published // Description: Completely replaces the transform with new // translation, rotation, and scale components, relative // to the other node, implicitly setting shear to 0. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_quat_scale(const NodePath &other, const LVecBase3 &pos, const LQuaternion &quat, const LVecBase3 &scale) { nassertv_always(!is_empty()); set_transform(other, TransformState::make_pos_quat_scale (pos, quat, scale)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_hpr_scale_shear // Access: Published // Description: Completely replaces the transform with new // translation, rotation, scale, and shear components, // relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_hpr_scale_shear(const NodePath &other, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale, const LVecBase3 &shear) { nassertv_always(!is_empty()); set_transform(other, TransformState::make_pos_hpr_scale_shear (pos, hpr, scale, shear)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_pos_quat_scale_shear // Access: Published // Description: Completely replaces the transform with new // translation, rotation, scale, and shear components, // relative to the other node. //////////////////////////////////////////////////////////////////// void NodePath:: set_pos_quat_scale_shear(const NodePath &other, const LVecBase3 &pos, const LQuaternion &quat, const LVecBase3 &scale, const LVecBase3 &shear) { nassertv_always(!is_empty()); set_transform(other, TransformState::make_pos_quat_scale_shear (pos, quat, scale, shear)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_mat // Access: Published // Description: Returns the matrix that describes the coordinate // space of the bottom node, relative to the other // path's bottom node's coordinate space. //////////////////////////////////////////////////////////////////// LMatrix4 NodePath:: get_mat(const NodePath &other) const { CPT(TransformState) transform = get_transform(other); // We can't safely return a reference to the matrix, because we // can't assume the transform won't go away when the function // returns. If the transform was partially modified by, say, a // CompassEffect, it won't be stored in the cache, and thus we might // have the only reference to it. return transform->get_mat(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_mat // Access: Published // Description: Converts the indicated matrix from the other's // coordinate space to the local coordinate space, and // applies it to the node. //////////////////////////////////////////////////////////////////// void NodePath:: set_mat(const NodePath &other, const LMatrix4 &mat) { nassertv_always(!is_empty()); set_transform(other, TransformState::make_mat(mat)); node()->reset_prev_transform(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_relative_point // Access: Published // Description: Given that the indicated point is in the coordinate // system of the other node, returns the same point in // this node's coordinate system. //////////////////////////////////////////////////////////////////// LPoint3 NodePath:: get_relative_point(const NodePath &other, const LVecBase3 &point) const { CPT(TransformState) transform = other.get_transform(*this); LPoint3 rel_point = LPoint3(point) * transform->get_mat(); return rel_point; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_relative_vector // Access: Published // Description: Given that the indicated vector is in the coordinate // system of the other node, returns the same vector in // this node's coordinate system. //////////////////////////////////////////////////////////////////// LVector3 NodePath:: get_relative_vector(const NodePath &other, const LVecBase3 &vec) const { CPT(TransformState) transform = other.get_transform(*this); LVector3 rel_vector = LVector3(vec) * transform->get_mat(); return rel_vector; } //////////////////////////////////////////////////////////////////// // Function: NodePath::look_at // Access: Published // Description: Sets the transform on this NodePath so that it // rotates to face the indicated point in space, which // is relative to the other NodePath. //////////////////////////////////////////////////////////////////// void NodePath:: look_at(const NodePath &other, const LPoint3 &point, const LVector3 &up) { nassertv_always(!is_empty()); CPT(TransformState) transform = other.get_transform(get_parent()); LPoint3 rel_point = point * transform->get_mat(); LPoint3 pos = get_pos(); LQuaternion quat; ::look_at(quat, rel_point - pos, up); set_quat(quat); } //////////////////////////////////////////////////////////////////// // Function: NodePath::heads_up // Access: Published // Description: Behaves like look_at(), but with a strong preference // to keeping the up vector oriented in the indicated // "up" direction. //////////////////////////////////////////////////////////////////// void NodePath:: heads_up(const NodePath &other, const LPoint3 &point, const LVector3 &up) { nassertv_always(!is_empty()); CPT(TransformState) transform = other.get_transform(get_parent()); LPoint3 rel_point = point * transform->get_mat(); LPoint3 pos = get_pos(); LQuaternion quat; ::heads_up(quat, rel_point - pos, up); set_quat(quat); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_color // Access: Published // Description: Applies a scene-graph color to the referenced node. // This color will apply to all geometry at this level // and below (that does not specify a new color or a // set_color_off()). //////////////////////////////////////////////////////////////////// void NodePath:: set_color(PN_stdfloat r, PN_stdfloat g, PN_stdfloat b, PN_stdfloat a, int priority) { set_color(LColor(r, g, b, a), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_color // Access: Published // Description: Applies a scene-graph color to the referenced node. // This color will apply to all geometry at this level // and below (that does not specify a new color or a // set_color_off()). //////////////////////////////////////////////////////////////////// void NodePath:: set_color(const LColor &color, int priority) { nassertv_always(!is_empty()); node()->set_attrib(ColorAttrib::make_flat(color), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_color_off // Access: Published // Description: Sets the geometry at this level and below to render // using the geometry color. This is normally the // default, but it may be useful to use this to // contradict set_color() at a higher node level (or, // with a priority, to override a set_color() at a lower // level). //////////////////////////////////////////////////////////////////// void NodePath:: set_color_off(int priority) { nassertv_always(!is_empty()); node()->set_attrib(ColorAttrib::make_vertex(), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_color // Access: Published // Description: Completely removes any color adjustment from the node. // This allows the natural color of the geometry, or // whatever color transitions might be otherwise // affecting the geometry, to show instead. //////////////////////////////////////////////////////////////////// void NodePath:: clear_color() { nassertv_always(!is_empty()); node()->clear_attrib(ColorAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_color // Access: Published // Description: Returns true if a color has been applied to the given // node, false otherwise. //////////////////////////////////////////////////////////////////// bool NodePath:: has_color() const { nassertr_always(!is_empty(), false); return node()->has_attrib(ColorAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_color // Access: Published // Description: Returns the color that has been assigned to the node, // or black if no color has been assigned. //////////////////////////////////////////////////////////////////// LColor NodePath:: get_color() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(ColorAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ColorAttrib *ca = DCAST(ColorAttrib, attrib); if (ca->get_color_type() == ColorAttrib::T_flat) { return ca->get_color(); } } pgraph_cat.warning() << "get_color() called on " << *this << " which has no color set.\n"; return LColor(1.0f, 1.0f, 1.0f, 1.0f); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_color_scale // Access: Published // Description: Returns true if a color scale has been applied // to the referenced node, false otherwise. It is still // possible that color at this node might have been // scaled by an ancestor node. //////////////////////////////////////////////////////////////////// bool NodePath:: has_color_scale() const { nassertr_always(!is_empty(), false); return node()->has_attrib(ColorScaleAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_color_scale // Access: Published // Description: Completely removes any color scale from the // referenced node. This is preferable to simply // setting the color scale to identity, as it also // removes the overhead associated with having a color // scale at all. //////////////////////////////////////////////////////////////////// void NodePath:: clear_color_scale() { nassertv_always(!is_empty()); node()->clear_attrib(ColorScaleAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::compose_color_scale // Access: Published // Description: multiplies the color scale component of the transform, // with previous color scale leaving translation and // rotation untouched. //////////////////////////////////////////////////////////////////// void NodePath:: compose_color_scale(const LVecBase4 &scale, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ColorScaleAttrib::get_class_slot())); const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); // Modify the existing ColorScaleAttrib by multiplying with the // indicated colorScale. LVecBase4 prev_color_scale = csa->get_scale(); LVecBase4 new_color_scale(prev_color_scale[0]*scale[0], prev_color_scale[1]*scale[1], prev_color_scale[2]*scale[2], prev_color_scale[3]*scale[3]); node()->set_attrib(csa->set_scale(new_color_scale), priority); } else { // Create a new ColorScaleAttrib for this node. node()->set_attrib(ColorScaleAttrib::make(scale), priority); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_color_scale // Access: Published // Description: Sets the color scale component of the transform, // leaving translation and rotation untouched. //////////////////////////////////////////////////////////////////// void NodePath:: set_color_scale(const LVecBase4 &scale, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ColorScaleAttrib::get_class_slot())); const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); // Modify the existing ColorScaleAttrib to add the indicated // colorScale. node()->set_attrib(csa->set_scale(scale), priority); } else { // Create a new ColorScaleAttrib for this node. node()->set_attrib(ColorScaleAttrib::make(scale), priority); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_color_scale_off // Access: Published // Description: Disables any color scale attribute inherited from // above. This is not the same thing as // clear_color_scale(), which undoes any previous // set_color_scale() operation on this node; rather, // this actively disables any set_color_scale() that // might be inherited from a parent node. This also // disables set_alpha_scale() at the same time. // // It is legal to specify a new color scale on the same // node with a subsequent call to set_color_scale() or // set_alpha_scale(); this new scale will apply to lower // geometry. //////////////////////////////////////////////////////////////////// void NodePath:: set_color_scale_off(int priority) { nassertv_always(!is_empty()); node()->set_attrib(ColorScaleAttrib::make_off(), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_alpha_scale // Access: Published // Description: Sets the alpha scale component of the transform // without (much) affecting the color scale. Note that // any priority specified will also apply to the color // scale. //////////////////////////////////////////////////////////////////// void NodePath:: set_alpha_scale(PN_stdfloat scale, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ColorScaleAttrib::get_class_slot())); const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); // Modify the existing ColorScaleAttrib to add the indicated // colorScale. const LVecBase4 &sc = csa->get_scale(); node()->set_attrib(csa->set_scale(LVecBase4(sc[0], sc[1], sc[2], scale)), priority); } else { // Create a new ColorScaleAttrib for this node. node()->set_attrib(ColorScaleAttrib::make(LVecBase4(1.0f, 1.0f, 1.0f, scale)), priority); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_all_color_scale // Access: Published // Description: Scales all the color components of the object by the // same amount, darkening the object, without (much) // affecting alpha. Note that any priority specified // will also apply to the alpha scale. //////////////////////////////////////////////////////////////////// void NodePath:: set_all_color_scale(PN_stdfloat scale, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ColorScaleAttrib::get_class_slot())); const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); // Modify the existing ColorScaleAttrib to add the indicated // colorScale. const LVecBase4 &sc = csa->get_scale(); node()->set_attrib(csa->set_scale(LVecBase4(scale, scale, scale, sc[3])), priority); } else { // Create a new ColorScaleAttrib for this node. node()->set_attrib(ColorScaleAttrib::make(LVecBase4(scale, scale, scale, 1.0f)), priority); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_color_scale // Access: Published // Description: Returns the complete color scale vector that has been // applied to this node via a previous call to // set_color_scale() and/or set_alpha_scale(), or all // 1's (identity) if no scale has been applied to this // particular node. //////////////////////////////////////////////////////////////////// const LVecBase4 &NodePath:: get_color_scale() const { static const LVecBase4 ident_scale(1.0f, 1.0f, 1.0f, 1.0f); nassertr_always(!is_empty(), ident_scale); const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); return csa->get_scale(); } return ident_scale; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_light // Access: Published // Description: Adds the indicated Light or PolylightNode to the list // of lights that illuminate geometry at this node and // below. The light itself should be parented into the // scene graph elsewhere, to represent the light's // position in space; but until set_light() is called it // will illuminate no geometry. //////////////////////////////////////////////////////////////////// void NodePath:: set_light(const NodePath &light, int priority) { nassertv_always(!is_empty()); if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); if (light_obj != (Light *)NULL) { // It's an actual Light object. const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(LightAttrib::get_class_slot())); const LightAttrib *la = DCAST(LightAttrib, attrib); // Modify the existing LightAttrib to add the indicated // light. node()->set_attrib(la->add_on_light(light), priority); } else { // Create a new LightAttrib for this node. CPT(LightAttrib) la = DCAST(LightAttrib, LightAttrib::make()); node()->set_attrib(la->add_on_light(light), priority); } return; } else if (light.node()->is_of_type(PolylightNode::get_class_type())) { // It's a Polylight object. if (priority != 0) { // PolylightEffects can't have a priority, since they're just // an effect to be applied immediately. pgraph_cat.warning() << "Ignoring priority on set_light(" << light << ")\n"; } const RenderEffect *effect = node()->get_effect(PolylightEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { const PolylightEffect *ple = DCAST(PolylightEffect, effect); // Modify the existing PolylightEffect to add the indicated // light. node()->set_effect(ple->add_light(light)); } else { // Create a new PolylightEffect for this node. CPT(PolylightEffect) ple = DCAST(PolylightEffect, PolylightEffect::make()); node()->set_effect(ple->add_light(light)); } return; } } nassert_raise("Not a Light object."); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_light_off // Access: Published // Description: Sets the geometry at this level and below to render // using no lights at all. This is different // from not specifying a light; rather, this // specifically contradicts set_light() at a higher // node level (or, with a priority, overrides a // set_light() at a lower level). // // If no lights are in effect on a particular piece of // geometry, that geometry is rendered with lighting // disabled. //////////////////////////////////////////////////////////////////// void NodePath:: set_light_off(int priority) { nassertv_always(!is_empty()); node()->set_attrib(LightAttrib::make_all_off(), priority); node()->clear_effect(PolylightEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_light_off // Access: Published // Description: Sets the geometry at this level and below to render // without using the indicated Light. This is different // from not specifying the Light; rather, this // specifically contradicts set_light() at a higher node // level (or, with a priority, overrides a set_light() // at a lower level). // // This interface does not support PolylightNodes, which // cannot be turned off at a lower level. //////////////////////////////////////////////////////////////////// void NodePath:: set_light_off(const NodePath &light, int priority) { nassertv_always(!is_empty()); if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); if (light_obj != (Light *)NULL) { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(LightAttrib::get_class_slot())); const LightAttrib *la = DCAST(LightAttrib, attrib); // Modify the existing LightAttrib to add the indicated light // to the "off" list. This also, incidentally, removes it from // the "on" list if it is there. node()->set_attrib(la->add_off_light(light), priority); } else { // Create a new LightAttrib for this node that turns off the // indicated light. CPT(LightAttrib) la = DCAST(LightAttrib, LightAttrib::make()); node()->set_attrib(la->add_off_light(light), priority); } return; } } nassert_raise("Not a Light object."); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_light // Access: Published // Description: Completely removes any lighting operations that may // have been set via set_light() or set_light_off() // from this particular node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_light() { nassertv_always(!is_empty()); node()->clear_attrib(LightAttrib::get_class_slot()); node()->clear_effect(PolylightEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_light // Access: Published // Description: Removes any reference to the indicated Light or // PolylightNode from the NodePath. //////////////////////////////////////////////////////////////////// void NodePath:: clear_light(const NodePath &light) { nassertv_always(!is_empty()); if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); if (light_obj != (Light *)NULL) { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { CPT(LightAttrib) la = DCAST(LightAttrib, attrib); la = DCAST(LightAttrib, la->remove_on_light(light)); la = DCAST(LightAttrib, la->remove_off_light(light)); if (la->is_identity()) { node()->clear_attrib(LightAttrib::get_class_slot()); } else { int priority = node()->get_state()->get_override(LightAttrib::get_class_slot()); node()->set_attrib(la, priority); } } return; } else if (light.node()->is_of_type(PolylightNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(PolylightEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { CPT(PolylightEffect) ple = DCAST(PolylightEffect, effect); ple = DCAST(PolylightEffect, ple->remove_light(light)); node()->set_effect(ple); } return; } } nassert_raise("Not a Light object."); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_light // Access: Published // Description: Returns true if the indicated Light or PolylightNode // has been specifically enabled on this particular // node. This means that someone called set_light() on // this node with the indicated light. //////////////////////////////////////////////////////////////////// bool NodePath:: has_light(const NodePath &light) const { nassertr_always(!is_empty(), false); if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); if (light_obj != (Light *)NULL) { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const LightAttrib *la = DCAST(LightAttrib, attrib); return la->has_on_light(light); } return false; } else if (light.node()->is_of_type(PolylightNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(PolylightEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { const PolylightEffect *ple = DCAST(PolylightEffect, effect); return ple->has_light(light); } return false; } } nassert_raise("Not a Light object."); return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_light_off // Access: Published // Description: Returns true if all Lights have been specifically // disabled on this particular node. This means that // someone called set_light_off() on this node with no // parameters. //////////////////////////////////////////////////////////////////// bool NodePath:: has_light_off() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const LightAttrib *la = DCAST(LightAttrib, attrib); return la->has_all_off(); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_light_off // Access: Published // Description: Returns true if the indicated Light has been // specifically disabled on this particular node. This // means that someone called set_light_off() on this // node with the indicated light. // // This interface does not support PolylightNodes, which // cannot be turned off at a lower level. //////////////////////////////////////////////////////////////////// bool NodePath:: has_light_off(const NodePath &light) const { nassertr_always(!is_empty(), false); if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); if (light_obj != (Light *)NULL) { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const LightAttrib *la = DCAST(LightAttrib, attrib); return la->has_off_light(light); } } } nassert_raise("Not a Light object."); return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_clip_plane // Access: Published // Description: Adds the indicated clipping plane to the list of // planes that apply to geometry at this node and below. // The clipping plane itself, a PlaneNode, should be // parented into the scene graph elsewhere, to represent // the plane's position in space; but until // set_clip_plane() is called it will clip no geometry. //////////////////////////////////////////////////////////////////// void NodePath:: set_clip_plane(const NodePath &clip_plane, int priority) { nassertv_always(!is_empty()); if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ClipPlaneAttrib::get_class_slot())); const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); // Modify the existing ClipPlaneAttrib to add the indicated // clip_plane. node()->set_attrib(la->add_on_plane(clip_plane), priority); } else { // Create a new ClipPlaneAttrib for this node. CPT(ClipPlaneAttrib) la = DCAST(ClipPlaneAttrib, ClipPlaneAttrib::make()); node()->set_attrib(la->add_on_plane(clip_plane), priority); } return; } nassert_raise("Not a PlaneNode object."); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_clip_plane_off // Access: Published // Description: Sets the geometry at this level and below to render // using no clip_planes at all. This is different // from not specifying a clip_plane; rather, this // specifically contradicts set_clip_plane() at a higher // node level (or, with a priority, overrides a // set_clip_plane() at a lower level). // // If no clip_planes are in effect on a particular piece // of geometry, that geometry is rendered without being // clipped (other than by the viewing frustum). //////////////////////////////////////////////////////////////////// void NodePath:: set_clip_plane_off(int priority) { nassertv_always(!is_empty()); node()->set_attrib(ClipPlaneAttrib::make_all_off(), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_clip_plane_off // Access: Published // Description: Sets the geometry at this level and below to render // without being clipped by the indicated PlaneNode. // This is different from not specifying the PlaneNode; // rather, this specifically contradicts // set_clip_plane() at a higher node level (or, with a // priority, overrides a set_clip_plane() at a lower // level). //////////////////////////////////////////////////////////////////// void NodePath:: set_clip_plane_off(const NodePath &clip_plane, int priority) { nassertv_always(!is_empty()); if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ClipPlaneAttrib::get_class_slot())); const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); // Modify the existing ClipPlaneAttrib to add the indicated clip_plane // to the "off" list. This also, incidentally, removes it from // the "on" list if it is there. node()->set_attrib(la->add_off_plane(clip_plane), priority); } else { // Create a new ClipPlaneAttrib for this node that turns off the // indicated clip_plane. CPT(ClipPlaneAttrib) la = DCAST(ClipPlaneAttrib, ClipPlaneAttrib::make()); node()->set_attrib(la->add_off_plane(clip_plane), priority); } return; } nassert_raise("Not a PlaneNode object."); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_clip_plane // Access: Published // Description: Completely removes any clip planes that may have been // set via set_clip_plane() or set_clip_plane_off() from // this particular node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_clip_plane() { nassertv_always(!is_empty()); node()->clear_attrib(ClipPlaneAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_clip_plane // Access: Published // Description: Removes any reference to the indicated clipping plane // from the NodePath. //////////////////////////////////////////////////////////////////// void NodePath:: clear_clip_plane(const NodePath &clip_plane) { nassertv_always(!is_empty()); if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { CPT(ClipPlaneAttrib) la = DCAST(ClipPlaneAttrib, attrib); la = DCAST(ClipPlaneAttrib, la->remove_on_plane(clip_plane)); la = DCAST(ClipPlaneAttrib, la->remove_off_plane(clip_plane)); if (la->is_identity()) { node()->clear_attrib(ClipPlaneAttrib::get_class_slot()); } else { int priority = node()->get_state()->get_override(ClipPlaneAttrib::get_class_slot()); node()->set_attrib(la, priority); } } return; } nassert_raise("Not a PlaneNode object."); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_clip_plane // Access: Published // Description: Returns true if the indicated clipping plane has been // specifically applied to this particular node. This // means that someone called set_clip_plane() on this // node with the indicated clip_plane. //////////////////////////////////////////////////////////////////// bool NodePath:: has_clip_plane(const NodePath &clip_plane) const { nassertr_always(!is_empty(), false); if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); return la->has_on_plane(clip_plane); } return false; } nassert_raise("Not a PlaneNode object."); return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_clip_plane_off // Access: Published // Description: Returns true if all clipping planes have been // specifically disabled on this particular node. This // means that someone called set_clip_plane_off() on // this node with no parameters. //////////////////////////////////////////////////////////////////// bool NodePath:: has_clip_plane_off() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); return la->has_all_off(); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_clip_plane_off // Access: Published // Description: Returns true if the indicated clipping plane has been // specifically disabled on this particular node. This // means that someone called set_clip_plane_off() on // this node with the indicated clip_plane. //////////////////////////////////////////////////////////////////// bool NodePath:: has_clip_plane_off(const NodePath &clip_plane) const { nassertr_always(!is_empty(), false); if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); return la->has_off_plane(clip_plane); } } nassert_raise("Not a PlaneNode object."); return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_occluder // Access: Published // Description: Adds the indicated occluder to the list of // occluders that apply to geometry at this node and below. // The occluder itself, an OccluderNode, should be // parented into the scene graph elsewhere, to represent // the occluder's position in space; but until // set_occluder() is called it will clip no geometry. //////////////////////////////////////////////////////////////////// void NodePath:: set_occluder(const NodePath &occluder) { nassertv_always(!is_empty()); if (!occluder.is_empty() && occluder.node()->is_of_type(OccluderNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(OccluderEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { const OccluderEffect *la = DCAST(OccluderEffect, effect); // Modify the existing OccluderEffect to add the indicated // occluder. node()->set_effect(la->add_on_occluder(occluder)); } else { // Create a new OccluderEffect for this node. CPT(OccluderEffect) la = DCAST(OccluderEffect, OccluderEffect::make()); node()->set_effect(la->add_on_occluder(occluder)); } return; } nassert_raise("Not an OccluderNode object."); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_occluder // Access: Published // Description: Completely removes any occluders that may have been // set via set_occluder() from this particular node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_occluder() { nassertv_always(!is_empty()); node()->clear_effect(OccluderEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_occluder // Access: Published // Description: Removes any reference to the indicated occluder // from the NodePath. //////////////////////////////////////////////////////////////////// void NodePath:: clear_occluder(const NodePath &occluder) { nassertv_always(!is_empty()); if (!occluder.is_empty() && occluder.node()->is_of_type(OccluderNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(OccluderEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { CPT(OccluderEffect) la = DCAST(OccluderEffect, effect); la = DCAST(OccluderEffect, la->remove_on_occluder(occluder)); if (la->is_identity()) { node()->clear_effect(OccluderEffect::get_class_type()); } else { node()->set_effect(la); } } return; } nassert_raise("Not an OccluderNode object."); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_occluder // Access: Published // Description: Returns true if the indicated occluder has been // specifically applied to this particular node. This // means that someone called set_occluder() on this // node with the indicated occluder. //////////////////////////////////////////////////////////////////// bool NodePath:: has_occluder(const NodePath &occluder) const { nassertr_always(!is_empty(), false); if (!occluder.is_empty() && occluder.node()->is_of_type(OccluderNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(OccluderEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { const OccluderEffect *la = DCAST(OccluderEffect, effect); return la->has_on_occluder(occluder); } return false; } nassert_raise("Not an OccluderNode object."); return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_scissor // Access: Published // Description: Sets up a scissor region on the nodes rendered at // this level and below. The four coordinates are // understood to define a rectangle in screen space. // These numbers are relative to the current // DisplayRegion, where (0,0) is the lower-left corner // of the DisplayRegion, and (1,1) is the upper-right // corner. //////////////////////////////////////////////////////////////////// void NodePath:: set_scissor(PN_stdfloat left, PN_stdfloat right, PN_stdfloat bottom, PN_stdfloat top) { set_effect(ScissorEffect::make_screen(LVecBase4(left, right, bottom, top))); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_scissor // Access: Published // Description: Sets up a scissor region on the nodes rendered at // this level and below. The two points are understood // to be relative to this node. When these points are // projected into screen space, they define the // diagonally-opposite points that determine the scissor // region. //////////////////////////////////////////////////////////////////// void NodePath:: set_scissor(const LPoint3 &a, const LPoint3 &b) { set_effect(ScissorEffect::make_node(a, b)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_scissor // Access: Published // Description: Sets up a scissor region on the nodes rendered at // this level and below. The four points are understood // to be relative to this node. When these points are // projected into screen space, they define the // bounding volume of the scissor region (the scissor // region is the smallest onscreen rectangle that // encloses all four points). //////////////////////////////////////////////////////////////////// void NodePath:: set_scissor(const LPoint3 &a, const LPoint3 &b, const LPoint3 &c, const LPoint3 &d) { set_effect(ScissorEffect::make_node(a, b, c, d)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_scissor // Access: Published // Description: Sets up a scissor region on the nodes rendered at // this level and below. The two points are understood // to be relative to the indicated other node. When // these points are projected into screen space, they // define the diagonally-opposite points that determine // the scissor region. //////////////////////////////////////////////////////////////////// void NodePath:: set_scissor(const NodePath &other, const LPoint3 &a, const LPoint3 &b) { set_effect(ScissorEffect::make_node(a, b, other)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_scissor // Access: Published // Description: Sets up a scissor region on the nodes rendered at // this level and below. The four points are understood // to be relative to the indicated other node. When // these points are projected into screen space, they // define the bounding volume of the scissor region (the // scissor region is the smallest onscreen rectangle // that encloses all four points). //////////////////////////////////////////////////////////////////// void NodePath:: set_scissor(const NodePath &other, const LPoint3 &a, const LPoint3 &b, const LPoint3 &c, const LPoint3 &d) { set_effect(ScissorEffect::make_node(a, b, c, d, other)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_scissor // Access: Published // Description: Removes the scissor region that was defined at this // node level by a previous call to set_scissor(). //////////////////////////////////////////////////////////////////// void NodePath:: clear_scissor() { clear_effect(ScissorEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_scissor // Access: Published // Description: Returns true if a scissor region was defined at this // node by a previous call to set_scissor(). This does // not check for scissor regions inherited from a parent // class. It also does not check for the presence of a // low-level ScissorAttrib, which is different from the // ScissorEffect added by set_scissor. //////////////////////////////////////////////////////////////////// bool NodePath:: has_scissor() const { return has_effect(ScissorEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_bin // Access: Published // Description: Assigns the geometry at this level and below to the // named rendering bin. It is the user's responsibility // to ensure that such a bin already exists, either via // the cull-bin Configrc variable, or by explicitly // creating a GeomBin of the appropriate type at // runtime. // // There are two default bins created when Panda is // started: "default" and "fixed". Normally, all // geometry is assigned to "default" unless specified // otherwise. This bin renders opaque geometry in // state-sorted order, followed by transparent geometry // sorted back-to-front. If any geometry is assigned to // "fixed", this will be rendered following all the // geometry in "default", in the order specified by // draw_order for each piece of geometry so assigned. // // The draw_order parameter is meaningful only for // GeomBinFixed type bins, e.g. "fixed". Other kinds of // bins ignore it. //////////////////////////////////////////////////////////////////// void NodePath:: set_bin(const string &bin_name, int draw_order, int priority) { nassertv_always(!is_empty()); node()->set_attrib(CullBinAttrib::make(bin_name, draw_order), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_bin // Access: Published // Description: Completely removes any bin adjustment that may have // been set via set_bin() from this particular node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_bin() { nassertv_always(!is_empty()); node()->clear_attrib(CullBinAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_bin // Access: Published // Description: Returns true if the node has been assigned to the a // particular rendering bin via set_bin(), false // otherwise. //////////////////////////////////////////////////////////////////// bool NodePath:: has_bin() const { nassertr_always(!is_empty(), false); return node()->has_attrib(CullBinAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_bin_name // Access: Published // Description: Returns the name of the bin that this particular node // was assigned to via set_bin(), or the empty string if // no bin was assigned. See set_bin() and has_bin(). //////////////////////////////////////////////////////////////////// string NodePath:: get_bin_name() const { nassertr_always(!is_empty(), string()); const RenderAttrib *attrib = node()->get_attrib(CullBinAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const CullBinAttrib *ba = DCAST(CullBinAttrib, attrib); return ba->get_bin_name(); } return string(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_bin_draw_order // Access: Published // Description: Returns the drawing order associated with the bin // that this particular node was assigned to via // set_bin(), or 0 if no bin was assigned. See // set_bin() and has_bin(). //////////////////////////////////////////////////////////////////// int NodePath:: get_bin_draw_order() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(CullBinAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const CullBinAttrib *ba = DCAST(CullBinAttrib, attrib); return ba->get_draw_order(); } return 0; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_texture // Access: Published // Description: Adds the indicated texture to the list of textures // that will be rendered on the default texture stage. // // This is the convenience single-texture variant of // this method; it is now superceded by set_texture() // that accepts a stage and texture. You may use this // method if you just want to adjust the default stage. //////////////////////////////////////////////////////////////////// void NodePath:: set_texture(Texture *tex, int priority) { nassertv_always(!is_empty()); PT(TextureStage) stage = TextureStage::get_default(); set_texture(stage, tex, priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_texture // Access: Published // Description: Adds the indicated texture to the list of textures // that will be rendered on the indicated multitexture // stage. If there are multiple texture stages // specified (possibly on multiple different nodes at // different levels), they will all be applied to // geometry together, according to the stage // specification set up in the TextureStage object. //////////////////////////////////////////////////////////////////// void NodePath:: set_texture(TextureStage *stage, Texture *tex, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *tsa = DCAST(TextureAttrib, attrib); int sg_priority = node()->get_state()->get_override(TextureAttrib::get_class_slot()); // Modify the existing TextureAttrib to add the indicated // texture. node()->set_attrib(tsa->add_on_stage(stage, tex, priority), sg_priority); } else { // Create a new TextureAttrib for this node. CPT(TextureAttrib) tsa = DCAST(TextureAttrib, TextureAttrib::make()); node()->set_attrib(tsa->add_on_stage(stage, tex, priority)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_texture // Access: Published // Description: Adds the indicated texture to the list of textures // that will be rendered on the default texture stage. // // The given sampler state will override the sampling // settings on the texture itself. Note that this // method makes a copy of the sampler settings that // you give; further changes to this object will not // be reflected. // // This is the convenience single-texture variant of // this method; it is now superceded by set_texture() // that accepts a stage and texture. You may use this // method if you just want to adjust the default stage. //////////////////////////////////////////////////////////////////// void NodePath:: set_texture(Texture *tex, const SamplerState &sampler, int priority) { nassertv_always(!is_empty()); PT(TextureStage) stage = TextureStage::get_default(); set_texture(stage, tex, sampler, priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_texture // Access: Published // Description: Adds the indicated texture to the list of textures // that will be rendered on the indicated multitexture // stage. If there are multiple texture stages // specified (possibly on multiple different nodes at // different levels), they will all be applied to // geometry together, according to the stage // specification set up in the TextureStage object. // // The given sampler state will override the sampling // settings on the texture itself. Note that this // method makes a copy of the sampler settings that // you give; further changes to this object will not // be reflected. //////////////////////////////////////////////////////////////////// void NodePath:: set_texture(TextureStage *stage, Texture *tex, const SamplerState &sampler, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *tsa = DCAST(TextureAttrib, attrib); int sg_priority = node()->get_state()->get_override(TextureAttrib::get_class_slot()); // Modify the existing TextureAttrib to add the indicated // texture. node()->set_attrib(tsa->add_on_stage(stage, tex, sampler, priority), sg_priority); } else { // Create a new TextureAttrib for this node. CPT(TextureAttrib) tsa = DCAST(TextureAttrib, TextureAttrib::make()); node()->set_attrib(tsa->add_on_stage(stage, tex, sampler, priority)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_texture_off // Access: Published // Description: Sets the geometry at this level and below to render // using no texture, on any stage. This is different // from not specifying a texture; rather, this // specifically contradicts set_texture() at a higher // node level (or, with a priority, overrides a // set_texture() at a lower level). //////////////////////////////////////////////////////////////////// void NodePath:: set_texture_off(int priority) { nassertv_always(!is_empty()); node()->set_attrib(TextureAttrib::make_all_off(), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_texture_off // Access: Published // Description: Sets the geometry at this level and below to render // using no texture, on the indicated stage. This is // different from not specifying a texture; rather, this // specifically contradicts set_texture() at a higher // node level (or, with a priority, overrides a // set_texture() at a lower level). //////////////////////////////////////////////////////////////////// void NodePath:: set_texture_off(TextureStage *stage, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *tsa = DCAST(TextureAttrib, attrib); int sg_priority = node()->get_state()->get_override(TextureAttrib::get_class_slot()); // Modify the existing TextureAttrib to add the indicated texture // to the "off" list. This also, incidentally, removes it from // the "on" list if it is there. node()->set_attrib(tsa->add_off_stage(stage, priority), sg_priority); } else { // Create a new TextureAttrib for this node that turns off the // indicated stage. CPT(TextureAttrib) tsa = DCAST(TextureAttrib, TextureAttrib::make()); node()->set_attrib(tsa->add_off_stage(stage, priority)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_texture // Access: Published // Description: Completely removes any texture adjustment that may // have been set via set_texture() or set_texture_off() // from this particular node. This allows whatever // textures might be otherwise affecting the geometry to // show instead. //////////////////////////////////////////////////////////////////// void NodePath:: clear_texture() { nassertv_always(!is_empty()); node()->clear_attrib(TextureAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_texture // Access: Published // Description: Removes any reference to the indicated texture stage // from the NodePath. //////////////////////////////////////////////////////////////////// void NodePath:: clear_texture(TextureStage *stage) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { CPT(TextureAttrib) tsa = DCAST(TextureAttrib, attrib); tsa = DCAST(TextureAttrib, tsa->remove_on_stage(stage)); tsa = DCAST(TextureAttrib, tsa->remove_off_stage(stage)); if (tsa->is_identity()) { node()->clear_attrib(TextureAttrib::get_class_slot()); } else { int priority = node()->get_state()->get_override(TextureAttrib::get_class_slot()); node()->set_attrib(tsa, priority); } } } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_texture // Access: Published // Description: Returns true if a texture has been applied to this // particular node via set_texture(), false otherwise. // This is not the same thing as asking whether the // geometry at this node will be rendered with // texturing, as there may be a texture in effect from a // higher or lower level. //////////////////////////////////////////////////////////////////// bool NodePath:: has_texture() const { return get_texture() != (Texture *)NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_texture // Access: Published // Description: Returns true if texturing has been specifically // enabled on this particular node for the indicated // stage. This means that someone called // set_texture() on this node with the indicated stage // name, or the stage_name is the default stage_name, // and someone called set_texture() on this node. //////////////////////////////////////////////////////////////////// bool NodePath:: has_texture(TextureStage *stage) const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->has_on_stage(stage); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_texture_off // Access: Published // Description: Returns true if texturing has been specifically // disabled on this particular node via // set_texture_off(), false otherwise. This is not the // same thing as asking whether the geometry at this // node will be rendered untextured, as there may be a // texture in effect from a higher or lower level. //////////////////////////////////////////////////////////////////// bool NodePath:: has_texture_off() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->has_all_off(); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_texture_off // Access: Published // Description: Returns true if texturing has been specifically // disabled on this particular node for the indicated // stage. This means that someone called // set_texture_off() on this node with the indicated // stage name, or that someone called set_texture_off() // on this node to remove all stages. //////////////////////////////////////////////////////////////////// bool NodePath:: has_texture_off(TextureStage *stage) const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->has_off_stage(stage); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_texture // Access: Published // Description: Returns the base-level texture that has been set on // this particular node, or NULL if no texture has been // set. This is not necessarily the texture that will // be applied to the geometry at or below this level, as // another texture at a higher or lower level may // override. // // See also find_texture(). //////////////////////////////////////////////////////////////////// Texture *NodePath:: get_texture() const { nassertr_always(!is_empty(), NULL); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->get_texture(); } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_texture // Access: Published // Description: Returns the texture that has been set on the // indicated stage for this particular node, or NULL if // no texture has been set for this stage. //////////////////////////////////////////////////////////////////// Texture *NodePath:: get_texture(TextureStage *stage) const { nassertr_always(!is_empty(), NULL); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->get_on_texture(stage); } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_texture_sampler // Access: Published // Description: Returns the sampler state that has been given for // the base-level texture that has been set on this // particular node. If no sampler state was given, // this returns the texture's default sampler settings. // // It is an error to call this if there is no base-level // texture applied to this particular node. //////////////////////////////////////////////////////////////////// const SamplerState &NodePath:: get_texture_sampler() const { return get_texture_sampler(TextureStage::get_default()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_texture_sampler // Access: Published // Description: Returns the sampler state that has been given for // the indicated texture stage that has been set on this // particular node. If no sampler state was given, // this returns the texture's default sampler settings. // // It is an error to call this if there is no texture // set for this stage on this particular node. //////////////////////////////////////////////////////////////////// const SamplerState &NodePath:: get_texture_sampler(TextureStage *stage) const { nassertr_always(!is_empty(), SamplerState::get_default()); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); nassertr_always(attrib != NULL, SamplerState::get_default()); const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->get_on_sampler(stage); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_shader // Access: Published // Description: //////////////////////////////////////////////////////////////////// void NodePath:: set_shader(const Shader *sha, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ShaderAttrib::get_class_slot())); const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->set_shader(sha, priority)); } else { // Create a new ShaderAttrib for this node. CPT(ShaderAttrib) sa = DCAST(ShaderAttrib, ShaderAttrib::make()); node()->set_attrib(sa->set_shader(sha, priority)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_shader_off // Access: Published // Description: //////////////////////////////////////////////////////////////////// void NodePath:: set_shader_off(int priority) { set_shader(NULL, priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_shader_auto // Access: Published // Description: //////////////////////////////////////////////////////////////////// void NodePath:: set_shader_auto(int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ShaderAttrib::get_class_slot())); const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->set_shader_auto(priority)); } else { // Create a new ShaderAttrib for this node. CPT(ShaderAttrib) sa = DCAST(ShaderAttrib, ShaderAttrib::make()); node()->set_attrib(sa->set_shader_auto(priority)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_shader_auto // Access: Published // Description: overloaded for auto shader customization //////////////////////////////////////////////////////////////////// void NodePath:: set_shader_auto(BitMask32 shader_switch, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(ShaderAttrib::get_class_slot())); const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->set_shader_auto(shader_switch, priority)); } else { // Create a new ShaderAttrib for this node. CPT(ShaderAttrib) sa = DCAST(ShaderAttrib, ShaderAttrib::make()); node()->set_attrib(sa->set_shader_auto(shader_switch, priority)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_shader // Access: Published // Description: //////////////////////////////////////////////////////////////////// void NodePath:: clear_shader() { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->clear_shader()); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_shader // Access: Published // Description: //////////////////////////////////////////////////////////////////// const Shader *NodePath:: get_shader() const { nassertr_always(!is_empty(), NULL); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); return sa->get_shader(); } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_shader_input // Access: Published // Description: //////////////////////////////////////////////////////////////////// void NodePath:: set_shader_input(const ShaderInput *inp) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->set_shader_input(inp)); } else { // Create a new ShaderAttrib for this node. CPT(ShaderAttrib) sa = DCAST(ShaderAttrib, ShaderAttrib::make()); node()->set_attrib(sa->set_shader_input(inp)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_shader_input // Access: Published // Description: //////////////////////////////////////////////////////////////////// const ShaderInput *NodePath:: get_shader_input(CPT_InternalName id) const { nassertr_always(!is_empty(), NULL); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); return sa->get_shader_input(id); } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_instance_count // Access: Published // Description: Returns the geometry instance count, or 0 if // disabled. See set_instance_count. //////////////////////////////////////////////////////////////////// int NodePath:: get_instance_count() const { nassertr_always(!is_empty(), 0); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); return sa->get_instance_count(); } return 0; } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_shader_input // Access: Published // Description: //////////////////////////////////////////////////////////////////// void NodePath:: clear_shader_input(CPT_InternalName id) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->clear_shader_input(id)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_instance_count // Access: Published // Description: Sets the geometry instance count, or 0 if // geometry instancing should be disabled. Do not // confuse with instanceTo which only applies to // animation instancing. //////////////////////////////////////////////////////////////////// void NodePath:: set_instance_count(int instance_count) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->set_instance_count(instance_count)); } else { // Create a new ShaderAttrib for this node. CPT(ShaderAttrib) sa = DCAST(ShaderAttrib, ShaderAttrib::make()); node()->set_attrib(sa->set_instance_count(instance_count)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_tex_transform // Access: Published // Description: Sets the texture matrix on the current node to the // indicated transform for the given stage. //////////////////////////////////////////////////////////////////// void NodePath:: set_tex_transform(TextureStage *stage, const TransformState *transform) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TexMatrixAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); // Modify the existing TexMatrixAttrib to add the indicated // stage. node()->set_attrib(tma->add_stage(stage, transform)); } else { // Create a new TexMatrixAttrib for this node. node()->set_attrib(TexMatrixAttrib::make(stage, transform)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_tex_transform // Access: Published // Description: Removes all texture matrices from the current node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_tex_transform() { nassertv_always(!is_empty()); node()->clear_attrib(TexMatrixAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_tex_transform // Access: Published // Description: Removes the texture matrix on the current node for // the given stage. //////////////////////////////////////////////////////////////////// void NodePath:: clear_tex_transform(TextureStage *stage) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TexMatrixAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { CPT(TexMatrixAttrib) tma = DCAST(TexMatrixAttrib, attrib); tma = DCAST(TexMatrixAttrib, tma->remove_stage(stage)); if (tma->is_empty()) { node()->clear_attrib(TexMatrixAttrib::get_class_slot()); } else { node()->set_attrib(tma); } } } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_tex_transform // Access: Published // Description: Returns true if there is an explicit texture matrix // on the current node for the given stage. //////////////////////////////////////////////////////////////////// bool NodePath:: has_tex_transform(TextureStage *stage) const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(TexMatrixAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); return tma->has_stage(stage); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_tex_transform // Access: Published // Description: Returns the texture matrix on the current node for the // given stage, or identity transform if there is no // explicit transform set for the given stage. //////////////////////////////////////////////////////////////////// CPT(TransformState) NodePath:: get_tex_transform(TextureStage *stage) const { nassertr_always(!is_empty(), NULL); const RenderAttrib *attrib = node()->get_attrib(TexMatrixAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); return tma->get_transform(stage); } return TransformState::make_identity(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_tex_transform // Access: Published // Description: Sets the texture matrix on the current node to the // indicated transform for the given stage. //////////////////////////////////////////////////////////////////// void NodePath:: set_tex_transform(const NodePath &other, TextureStage *stage, const TransformState *transform) { nassertv(_error_type == ET_ok && other._error_type == ET_ok); nassertv_always(!is_empty()); CPT(RenderState) state = get_state(other); const RenderAttrib *attrib = state->get_attrib(TexMatrixAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); // Modify the existing TexMatrixAttrib to add the indicated // stage. state = state->add_attrib(tma->add_stage(stage, transform)); } else { // Create a new TexMatrixAttrib for this node. state = state->add_attrib(TexMatrixAttrib::make(stage, transform)); } // Now compose that with our parent's state. CPT(RenderState) rel_state; if (has_parent()) { rel_state = other.get_state(get_parent()); } else { rel_state = other.get_state(NodePath()); } CPT(RenderState) new_state = rel_state->compose(state); // And apply only the TexMatrixAttrib to the current node, leaving // the others unchanged. node()->set_attrib(new_state->get_attrib(TexMatrixAttrib::get_class_slot())); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_tex_transform // Access: Published // Description: Returns the texture matrix on the current node for the // given stage, relative to the other node. //////////////////////////////////////////////////////////////////// CPT(TransformState) NodePath:: get_tex_transform(const NodePath &other, TextureStage *stage) const { nassertr(_error_type == ET_ok && other._error_type == ET_ok, TransformState::make_identity()); CPT(RenderState) state = get_state(other); const RenderAttrib *attrib = state->get_attrib(TexMatrixAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); return tma->get_transform(stage); } return TransformState::make_identity(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_tex_gen // Access: Published // Description: Enables automatic texture coordinate generation for // the indicated texture stage. //////////////////////////////////////////////////////////////////// void NodePath:: set_tex_gen(TextureStage *stage, RenderAttrib::TexGenMode mode, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TexGenAttrib::get_class_slot()); CPT(TexGenAttrib) tga; if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(TextureAttrib::get_class_slot())); tga = DCAST(TexGenAttrib, attrib); } else { tga = DCAST(TexGenAttrib, TexGenAttrib::make()); } node()->set_attrib(tga->add_stage(stage, mode), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_tex_gen // Access: Published // Description: Enables automatic texture coordinate generation for // the indicated texture stage. This version of this // method is useful when setting M_constant, which // requires a constant texture coordinate value. //////////////////////////////////////////////////////////////////// void NodePath:: set_tex_gen(TextureStage *stage, RenderAttrib::TexGenMode mode, const LTexCoord3 &constant_value, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TexGenAttrib::get_class_slot()); CPT(TexGenAttrib) tga; if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(TextureAttrib::get_class_slot())); tga = DCAST(TexGenAttrib, attrib); } else { tga = DCAST(TexGenAttrib, TexGenAttrib::make()); } node()->set_attrib(tga->add_stage(stage, mode, constant_value), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_tex_gen // Access: Published // Description: Removes the texture coordinate generation mode from // all texture stages on this node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_tex_gen() { nassertv_always(!is_empty()); node()->clear_attrib(TexGenAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_tex_gen // Access: Published // Description: Disables automatic texture coordinate generation for // the indicated texture stage. //////////////////////////////////////////////////////////////////// void NodePath:: clear_tex_gen(TextureStage *stage) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(TexGenAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { CPT(TexGenAttrib) tga = DCAST(TexGenAttrib, attrib); tga = DCAST(TexGenAttrib, tga->remove_stage(stage)); if (tga->is_empty()) { node()->clear_attrib(TexGenAttrib::get_class_slot()); } else { node()->set_attrib(tga); } } } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_tex_gen // Access: Published // Description: Returns true if there is a mode for automatic texture // coordinate generation on the current node for the // given stage. //////////////////////////////////////////////////////////////////// bool NodePath:: has_tex_gen(TextureStage *stage) const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(TexGenAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TexGenAttrib *tga = DCAST(TexGenAttrib, attrib); return tga->has_stage(stage); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_tex_gen // Access: Published // Description: Returns the texture coordinate generation mode for // the given stage, or M_off if there is no explicit // mode set for the given stage. //////////////////////////////////////////////////////////////////// RenderAttrib::TexGenMode NodePath:: get_tex_gen(TextureStage *stage) const { nassertr_always(!is_empty(), TexGenAttrib::M_off); const RenderAttrib *attrib = node()->get_attrib(TexGenAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TexGenAttrib *tga = DCAST(TexGenAttrib, attrib); return tga->get_mode(stage); } return TexGenAttrib::M_off; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_tex_projector // Access: Published // Description: Establishes a TexProjectorEffect on this node, which // can be used to establish projective texturing (but // see also the NodePath::project_texture() convenience // function), or it can be used to bind this node's // texture transform to particular node's position in // space, allowing a LerpInterval (for instance) to // adjust this node's texture coordinates. // // If to is a LensNode, then the fourth parameter, // lens_index, can be provided to select a particular // lens to apply. Otherwise lens_index is not used. //////////////////////////////////////////////////////////////////// void NodePath:: set_tex_projector(TextureStage *stage, const NodePath &from, const NodePath &to, int lens_index) { nassertv_always(!is_empty()); const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); CPT(TexProjectorEffect) tpe; if (effect != (const RenderEffect *)NULL) { tpe = DCAST(TexProjectorEffect, effect); } else { tpe = DCAST(TexProjectorEffect, TexProjectorEffect::make()); } node()->set_effect(tpe->add_stage(stage, from, to, lens_index)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_tex_projector // Access: Published // Description: Removes the TexProjectorEffect for the indicated // stage from this node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_tex_projector(TextureStage *stage) { nassertv_always(!is_empty()); const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { CPT(TexProjectorEffect) tpe = DCAST(TexProjectorEffect, effect); tpe = DCAST(TexProjectorEffect, tpe->remove_stage(stage)); if (tpe->is_empty()) { node()->clear_effect(TexProjectorEffect::get_class_type()); } else { node()->set_effect(tpe); } } } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_tex_projector // Access: Published // Description: Removes the TexProjectorEffect for all stages from // this node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_tex_projector() { nassertv_always(!is_empty()); node()->clear_effect(TexProjectorEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_tex_projector // Access: Published // Description: Returns true if this node has a TexProjectorEffect // for the indicated stage, false otherwise. //////////////////////////////////////////////////////////////////// bool NodePath:: has_tex_projector(TextureStage *stage) const { nassertr_always(!is_empty(), false); const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { const TexProjectorEffect *tpe = DCAST(TexProjectorEffect, effect); return tpe->has_stage(stage); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_tex_projector_from // Access: Published // Description: Returns the "from" node associated with the // TexProjectorEffect on the indicated stage. The // relative transform between the "from" and the "to" // nodes is automatically applied to the texture // transform each frame. //////////////////////////////////////////////////////////////////// NodePath NodePath:: get_tex_projector_from(TextureStage *stage) const { nassertr_always(!is_empty(), NodePath::fail()); const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { const TexProjectorEffect *tpe = DCAST(TexProjectorEffect, effect); return tpe->get_from(stage); } return NodePath::not_found(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_tex_projector_to // Access: Published // Description: Returns the "to" node associated with the // TexProjectorEffect on the indicated stage. The // relative transform between the "from" and the "to" // nodes is automatically applied to the texture // transform each frame. //////////////////////////////////////////////////////////////////// NodePath NodePath:: get_tex_projector_to(TextureStage *stage) const { nassertr_always(!is_empty(), NodePath::fail()); const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); if (effect != (const RenderEffect *)NULL) { const TexProjectorEffect *tpe = DCAST(TexProjectorEffect, effect); return tpe->get_to(stage); } return NodePath::not_found(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::project_texture // Access: Published // Description: A convenience function to enable projective texturing // at this node level and below, using the indicated // NodePath (which should contain a LensNode) as the // projector. //////////////////////////////////////////////////////////////////// void NodePath:: project_texture(TextureStage *stage, Texture *tex, const NodePath &projector) { nassertv(!projector.is_empty() && projector.node()->is_of_type(LensNode::get_class_type())); set_texture(stage, tex); set_tex_gen(stage, TexGenAttrib::M_world_position); set_tex_projector(stage, NodePath(), projector); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_vertex_column // Access: Published // Description: Returns true if there are at least some vertices at // this node and below that contain a reference to the // indicated vertex data column name, false otherwise. // // This is particularly useful for testing whether a // particular model has a given texture coordinate set // (but see has_texcoord()). //////////////////////////////////////////////////////////////////// bool NodePath:: has_vertex_column(const InternalName *name) const { nassertr_always(!is_empty(), false); return r_has_vertex_column(node(), name); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_vertex_columns // Access: Published // Description: Returns a list of all vertex array columns stored on // some geometry found at this node level and below. //////////////////////////////////////////////////////////////////// InternalNameCollection NodePath:: find_all_vertex_columns() const { nassertr_always(!is_empty(), InternalNameCollection()); InternalNames vertex_columns; r_find_all_vertex_columns(node(), vertex_columns); InternalNameCollection tc; InternalNames::iterator ti; for (ti = vertex_columns.begin(); ti != vertex_columns.end(); ++ti) { tc.add_name(*ti); } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_vertex_columns // Access: Published // Description: Returns a list of all vertex array columns stored on // some geometry found at this node level and below that // match the indicated name (which may contain wildcard // characters). //////////////////////////////////////////////////////////////////// InternalNameCollection NodePath:: find_all_vertex_columns(const string &name) const { nassertr_always(!is_empty(), InternalNameCollection()); InternalNames vertex_columns; r_find_all_vertex_columns(node(), vertex_columns); GlobPattern glob(name); InternalNameCollection tc; InternalNames::iterator ti; for (ti = vertex_columns.begin(); ti != vertex_columns.end(); ++ti) { const InternalName *name = (*ti); if (glob.matches(name->get_name())) { tc.add_name(name); } } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_texcoords // Access: Published // Description: Returns a list of all texture coordinate sets used by // any geometry at this node level and below. //////////////////////////////////////////////////////////////////// InternalNameCollection NodePath:: find_all_texcoords() const { nassertr_always(!is_empty(), InternalNameCollection()); InternalNames vertex_columns; r_find_all_vertex_columns(node(), vertex_columns); CPT(InternalName) texcoord_name = InternalName::get_texcoord(); InternalNameCollection tc; InternalNames::iterator ti; for (ti = vertex_columns.begin(); ti != vertex_columns.end(); ++ti) { if ((*ti)->get_top() == texcoord_name) { tc.add_name(*ti); } } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_texcoords // Access: Published // Description: Returns a list of all texture coordinate sets used by // any geometry at this node level and below that match // the indicated name (which may contain wildcard // characters). //////////////////////////////////////////////////////////////////// InternalNameCollection NodePath:: find_all_texcoords(const string &name) const { nassertr_always(!is_empty(), InternalNameCollection()); InternalNames vertex_columns; r_find_all_vertex_columns(node(), vertex_columns); GlobPattern glob(name); CPT_InternalName texcoord_name = InternalName::get_texcoord(); InternalNameCollection tc; InternalNames::iterator ti; for (ti = vertex_columns.begin(); ti != vertex_columns.end(); ++ti) { const InternalName *name = (*ti); if (name->get_top() == texcoord_name) { // This is a texture coordinate name. Figure out the basename // of the texture coordinates. int index = name->find_ancestor("texcoord"); nassertr(index != -1, InternalNameCollection()); string net_basename = name->get_net_basename(index - 1); if (glob.matches(net_basename)) { tc.add_name(name); } } } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_texture // Access: Published // Description: Returns the first texture found applied to geometry // at this node or below that matches the indicated name // (which may contain wildcards). Returns the texture // if it is found, or NULL if it is not. //////////////////////////////////////////////////////////////////// Texture *NodePath:: find_texture(const string &name) const { nassertr_always(!is_empty(), NULL); GlobPattern glob(name); return r_find_texture(node(), get_net_state(), glob); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_texture // Access: Published // Description: Returns the first texture found applied to geometry // at this node or below that is assigned to the // indicated texture stage. Returns the texture if it // is found, or NULL if it is not. //////////////////////////////////////////////////////////////////// Texture *NodePath:: find_texture(TextureStage *stage) const { nassertr_always(!is_empty(), NULL); return r_find_texture(node(), stage); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_textures // Access: Published // Description: Returns a list of a textures applied to geometry at // this node and below. //////////////////////////////////////////////////////////////////// TextureCollection NodePath:: find_all_textures() const { nassertr_always(!is_empty(), TextureCollection()); Textures textures; r_find_all_textures(node(), get_net_state(), textures); TextureCollection tc; Textures::iterator ti; for (ti = textures.begin(); ti != textures.end(); ++ti) { tc.add_texture(*ti); } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_textures // Access: Published // Description: Returns a list of a textures applied to geometry at // this node and below that match the indicated name // (which may contain wildcard characters). //////////////////////////////////////////////////////////////////// TextureCollection NodePath:: find_all_textures(const string &name) const { nassertr_always(!is_empty(), TextureCollection()); Textures textures; r_find_all_textures(node(), get_net_state(), textures); GlobPattern glob(name); TextureCollection tc; Textures::iterator ti; for (ti = textures.begin(); ti != textures.end(); ++ti) { Texture *texture = (*ti); if (glob.matches(texture->get_name())) { tc.add_texture(texture); } } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_textures // Access: Published // Description: Returns a list of a textures on geometry at // this node and below that are assigned to the // indicated texture stage. //////////////////////////////////////////////////////////////////// TextureCollection NodePath:: find_all_textures(TextureStage *stage) const { nassertr_always(!is_empty(), TextureCollection()); Textures textures; r_find_all_textures(node(), stage, textures); TextureCollection tc; Textures::iterator ti; for (ti = textures.begin(); ti != textures.end(); ++ti) { Texture *texture = (*ti); tc.add_texture(texture); } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_texture_stage // Access: Published // Description: Returns the first TextureStage found applied to // geometry at this node or below that matches the // indicated name (which may contain wildcards). // Returns the TextureStage if it is found, or NULL if // it is not. //////////////////////////////////////////////////////////////////// TextureStage *NodePath:: find_texture_stage(const string &name) const { nassertr_always(!is_empty(), NULL); GlobPattern glob(name); return r_find_texture_stage(node(), get_net_state(), glob); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_texture_stages // Access: Published // Description: Returns a list of a TextureStages applied to geometry // at this node and below. //////////////////////////////////////////////////////////////////// TextureStageCollection NodePath:: find_all_texture_stages() const { nassertr_always(!is_empty(), TextureStageCollection()); TextureStages texture_stages; r_find_all_texture_stages(node(), get_net_state(), texture_stages); TextureStageCollection tc; TextureStages::iterator ti; for (ti = texture_stages.begin(); ti != texture_stages.end(); ++ti) { tc.add_texture_stage(*ti); } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::unify_texture_stages // Access: Published // Description: Searches through all TextureStages at this node and // below. Any TextureStages that share the same name as // the indicated TextureStage object are replaced with // this object, thus ensuring that all geometry at this // node and below with a particular TextureStage name is // using the same TextureStage object. //////////////////////////////////////////////////////////////////// void NodePath:: unify_texture_stages(TextureStage *stage) { nassertv_always(!is_empty()); r_unify_texture_stages(node(), stage); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_texture_stages // Access: Published // Description: Returns a list of a TextureStages applied to geometry // at this node and below that match the indicated name // (which may contain wildcard characters). //////////////////////////////////////////////////////////////////// TextureStageCollection NodePath:: find_all_texture_stages(const string &name) const { nassertr_always(!is_empty(), TextureStageCollection()); TextureStages texture_stages; r_find_all_texture_stages(node(), get_net_state(), texture_stages); GlobPattern glob(name); TextureStageCollection tc; TextureStages::iterator ti; for (ti = texture_stages.begin(); ti != texture_stages.end(); ++ti) { TextureStage *texture_stage = (*ti); if (glob.matches(texture_stage->get_name())) { tc.add_texture_stage(texture_stage); } } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_material // Access: Published // Description: Returns the first material found applied to geometry // at this node or below that matches the indicated name // (which may contain wildcards). Returns the material // if it is found, or NULL if it is not. //////////////////////////////////////////////////////////////////// Material *NodePath:: find_material(const string &name) const { nassertr_always(!is_empty(), NULL); GlobPattern glob(name); return r_find_material(node(), get_net_state(), glob); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_materials // Access: Published // Description: Returns a list of a materials applied to geometry at // this node and below. //////////////////////////////////////////////////////////////////// MaterialCollection NodePath:: find_all_materials() const { nassertr_always(!is_empty(), MaterialCollection()); Materials materials; r_find_all_materials(node(), get_net_state(), materials); MaterialCollection tc; Materials::iterator ti; for (ti = materials.begin(); ti != materials.end(); ++ti) { tc.add_material(*ti); } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_all_materials // Access: Published // Description: Returns a list of a materials applied to geometry at // this node and below that match the indicated name // (which may contain wildcard characters). //////////////////////////////////////////////////////////////////// MaterialCollection NodePath:: find_all_materials(const string &name) const { nassertr_always(!is_empty(), MaterialCollection()); Materials materials; r_find_all_materials(node(), get_net_state(), materials); GlobPattern glob(name); MaterialCollection tc; Materials::iterator ti; for (ti = materials.begin(); ti != materials.end(); ++ti) { Material *material = (*ti); if (glob.matches(material->get_name())) { tc.add_material(material); } } return tc; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_material // Access: Published // Description: Sets the geometry at this level and below to render // using the indicated material. // // Previously, this operation made a copy of the // material structure, but nowadays it assigns the // pointer directly. //////////////////////////////////////////////////////////////////// void NodePath:: set_material(Material *mat, int priority) { nassertv_always(!is_empty()); nassertv(mat != NULL); node()->set_attrib(MaterialAttrib::make(mat), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_material_off // Access: Published // Description: Sets the geometry at this level and below to render // using no material. This is normally the default, but // it may be useful to use this to contradict // set_material() at a higher node level (or, with a // priority, to override a set_material() at a lower // level). //////////////////////////////////////////////////////////////////// void NodePath:: set_material_off(int priority) { nassertv_always(!is_empty()); node()->set_attrib(MaterialAttrib::make_off(), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_material // Access: Published // Description: Completely removes any material adjustment that may // have been set via set_material() from this particular // node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_material() { nassertv_always(!is_empty()); node()->clear_attrib(MaterialAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_material // Access: Published // Description: Returns true if a material has been applied to this // particular node via set_material(), false otherwise. //////////////////////////////////////////////////////////////////// bool NodePath:: has_material() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(MaterialAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const MaterialAttrib *ma = DCAST(MaterialAttrib, attrib); return !ma->is_off(); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_material // Access: Published // Description: Returns the material that has been set on this // particular node, or NULL if no material has been set. // This is not necessarily the material that will be // applied to the geometry at or below this level, as // another material at a higher or lower level may // override. // See also find_material(). //////////////////////////////////////////////////////////////////// PT(Material) NodePath:: get_material() const { nassertr_always(!is_empty(), NULL); const RenderAttrib *attrib = node()->get_attrib(MaterialAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const MaterialAttrib *ma = DCAST(MaterialAttrib, attrib); return ma->get_material(); } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_fog // Access: Published // Description: Sets the geometry at this level and below to render // using the indicated fog. //////////////////////////////////////////////////////////////////// void NodePath:: set_fog(Fog *fog, int priority) { nassertv_always(!is_empty()); node()->set_attrib(FogAttrib::make(fog), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_fog_off // Access: Published // Description: Sets the geometry at this level and below to render // using no fog. This is normally the default, but // it may be useful to use this to contradict // set_fog() at a higher node level (or, with a // priority, to override a set_fog() at a lower // level). //////////////////////////////////////////////////////////////////// void NodePath:: set_fog_off(int priority) { nassertv_always(!is_empty()); node()->set_attrib(FogAttrib::make_off(), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_fog // Access: Published // Description: Completely removes any fog adjustment that may // have been set via set_fog() or set_fog_off() // from this particular node. This allows whatever // fogs might be otherwise affecting the geometry to // show instead. //////////////////////////////////////////////////////////////////// void NodePath:: clear_fog() { nassertv_always(!is_empty()); node()->clear_attrib(FogAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_fog // Access: Published // Description: Returns true if a fog has been applied to this // particular node via set_fog(), false otherwise. // This is not the same thing as asking whether the // geometry at this node will be rendered with // fog, as there may be a fog in effect from a higher or // lower level. //////////////////////////////////////////////////////////////////// bool NodePath:: has_fog() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(FogAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const FogAttrib *fa = DCAST(FogAttrib, attrib); return !fa->is_off(); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_fog_off // Access: Published // Description: Returns true if a fog has been specifically // disabled on this particular node via // set_fog_off(), false otherwise. This is not the // same thing as asking whether the geometry at this // node will be rendered unfogged, as there may be a // fog in effect from a higher or lower level. //////////////////////////////////////////////////////////////////// bool NodePath:: has_fog_off() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(FogAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const FogAttrib *fa = DCAST(FogAttrib, attrib); return fa->is_off(); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_fog // Access: Published // Description: Returns the fog that has been set on this // particular node, or NULL if no fog has been set. // This is not necessarily the fog that will be // applied to the geometry at or below this level, as // another fog at a higher or lower level may // override. //////////////////////////////////////////////////////////////////// Fog *NodePath:: get_fog() const { nassertr_always(!is_empty(), NULL); const RenderAttrib *attrib = node()->get_attrib(FogAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const FogAttrib *fa = DCAST(FogAttrib, attrib); return fa->get_fog(); } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_render_mode_wireframe // Access: Published // Description: Sets up the geometry at this level and below (unless // overridden) to render in wireframe mode. //////////////////////////////////////////////////////////////////// void NodePath:: set_render_mode_wireframe(int priority) { nassertv_always(!is_empty()); PN_stdfloat thickness = get_render_mode_thickness(); bool perspective = get_render_mode_perspective(); node()->set_attrib(RenderModeAttrib::make(RenderModeAttrib::M_wireframe, thickness, perspective), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_render_mode_filled // Access: Published // Description: Sets up the geometry at this level and below (unless // overridden) to render in filled (i.e. not wireframe) // mode. //////////////////////////////////////////////////////////////////// void NodePath:: set_render_mode_filled(int priority) { nassertv_always(!is_empty()); PN_stdfloat thickness = get_render_mode_thickness(); bool perspective = get_render_mode_perspective(); node()->set_attrib(RenderModeAttrib::make(RenderModeAttrib::M_filled, thickness, perspective), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_render_mode_filled_wireframe // Access: Published // Description: Sets up the geometry at this level and below (unless // overridden) to render in filled, but overlay the // wireframe on top with a fixed color. This is useful // for debug visualizations. //////////////////////////////////////////////////////////////////// void NodePath:: set_render_mode_filled_wireframe(const LColor &wireframe_color, int priority) { nassertv_always(!is_empty()); PN_stdfloat thickness = get_render_mode_thickness(); bool perspective = get_render_mode_perspective(); node()->set_attrib(RenderModeAttrib::make(RenderModeAttrib::M_filled_wireframe, thickness, perspective, wireframe_color), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_render_mode_perspective // Access: Published // Description: Sets up the point geometry at this level and below to // render as perspective sprites (that is, billboarded // quads). The thickness, as specified with // set_render_mode_thickness(), is the width of each // point in 3-D units, unless it is overridden on a // per-vertex basis. This does not affect geometry // other than points. // // If you want the quads to be individually textured, // you should also set a TexGenAttrib::M_point_sprite on // the node. //////////////////////////////////////////////////////////////////// void NodePath:: set_render_mode_perspective(bool perspective, int priority) { nassertv_always(!is_empty()); RenderModeAttrib::Mode mode = get_render_mode(); PN_stdfloat thickness = get_render_mode_thickness(); node()->set_attrib(RenderModeAttrib::make(mode, thickness, perspective), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_render_mode_thickness // Access: Published // Description: Sets up the point geometry at this level and below to // render as thick points (that is, billboarded // quads). The thickness is in pixels, unless // set_render_mode_perspective is also true, in which // case it is in 3-D units. // // If you want the quads to be individually textured, // you should also set a TexGenAttrib::M_point_sprite on // the node. //////////////////////////////////////////////////////////////////// void NodePath:: set_render_mode_thickness(PN_stdfloat thickness, int priority) { nassertv_always(!is_empty()); RenderModeAttrib::Mode mode = get_render_mode(); bool perspective = get_render_mode_perspective(); node()->set_attrib(RenderModeAttrib::make(mode, thickness, perspective), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_render_mode // Access: Published // Description: Sets up the geometry at this level and below (unless // overridden) to render in the specified mode and with // the indicated line and/or point thickness. //////////////////////////////////////////////////////////////////// void NodePath:: set_render_mode(RenderModeAttrib::Mode mode, PN_stdfloat thickness, int priority) { nassertv_always(!is_empty()); node()->set_attrib(RenderModeAttrib::make(mode, thickness), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_render_mode // Access: Published // Description: Completely removes any render mode adjustment that // may have been set on this node via // set_render_mode_wireframe() or // set_render_mode_filled(). //////////////////////////////////////////////////////////////////// void NodePath:: clear_render_mode() { nassertv_always(!is_empty()); node()->clear_attrib(RenderModeAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_render_mode // Access: Published // Description: Returns true if a render mode has been explicitly set // on this particular node via set_render_mode() (or // set_render_mode_wireframe() or // set_render_mode_filled()), false otherwise. //////////////////////////////////////////////////////////////////// bool NodePath:: has_render_mode() const { nassertr_always(!is_empty(), false); return node()->has_attrib(RenderModeAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_render_mode // Access: Published // Description: Returns the render mode that has been specifically // set on this node via set_render_mode(), or // M_unchanged if nothing has been set. //////////////////////////////////////////////////////////////////// RenderModeAttrib::Mode NodePath:: get_render_mode() const { nassertr_always(!is_empty(), RenderModeAttrib::M_unchanged); const RenderAttrib *attrib = node()->get_attrib(RenderModeAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const RenderModeAttrib *ta = DCAST(RenderModeAttrib, attrib); return ta->get_mode(); } return RenderModeAttrib::M_unchanged; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_render_mode_thickness // Access: Published // Description: Returns the render mode thickness that has been // specifically set on this node via set_render_mode(), // or 1.0 if nothing has been set. //////////////////////////////////////////////////////////////////// PN_stdfloat NodePath:: get_render_mode_thickness() const { nassertr_always(!is_empty(), 0.0f); const RenderAttrib *attrib = node()->get_attrib(RenderModeAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const RenderModeAttrib *ta = DCAST(RenderModeAttrib, attrib); return ta->get_thickness(); } return 1.0f; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_render_mode_perspective // Access: Published // Description: Returns the flag that has been set on this node via // set_render_mode_perspective(), or false if no flag // has been set. //////////////////////////////////////////////////////////////////// bool NodePath:: get_render_mode_perspective() const { nassertr_always(!is_empty(), 0.0f); const RenderAttrib *attrib = node()->get_attrib(RenderModeAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const RenderModeAttrib *ta = DCAST(RenderModeAttrib, attrib); return ta->get_perspective(); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_two_sided // Access: Published // Description: Specifically sets or disables two-sided rendering // mode on this particular node. If no other nodes // override, this will cause backfacing polygons to be // drawn (in two-sided mode, true) or culled (in // one-sided mode, false). //////////////////////////////////////////////////////////////////// void NodePath:: set_two_sided(bool two_sided, int priority) { nassertv_always(!is_empty()); CullFaceAttrib::Mode mode = two_sided ? CullFaceAttrib::M_cull_none : CullFaceAttrib::M_cull_clockwise; node()->set_attrib(CullFaceAttrib::make(mode), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_two_sided // Access: Published // Description: Completely removes any two-sided adjustment that // may have been set on this node via set_two_sided(). // The geometry at this level and below will // subsequently be rendered either two-sided or // one-sided, according to whatever other nodes may have // had set_two_sided() on it, or according to the // initial state otherwise. //////////////////////////////////////////////////////////////////// void NodePath:: clear_two_sided() { nassertv_always(!is_empty()); node()->clear_attrib(CullFaceAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_two_sided // Access: Published // Description: Returns true if a two-sided adjustment has been // explicitly set on this particular node via // set_two_sided(). If this returns true, then // get_two_sided() may be called to determine which has // been set. //////////////////////////////////////////////////////////////////// bool NodePath:: has_two_sided() const { nassertr_always(!is_empty(), false); return node()->has_attrib(CullFaceAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_two_sided // Access: Published // Description: Returns true if two-sided rendering has been // specifically set on this node via set_two_sided(), or // false if one-sided rendering has been specifically // set, or if nothing has been specifically set. See // also has_two_sided(). This does not necessarily // imply that the geometry will or will not be rendered // two-sided, as there may be other nodes that override. //////////////////////////////////////////////////////////////////// bool NodePath:: get_two_sided() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(CullFaceAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const CullFaceAttrib *cfa = DCAST(CullFaceAttrib, attrib); return (cfa->get_actual_mode() == CullFaceAttrib::M_cull_none); } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_depth_test // Access: Published // Description: Specifically sets or disables the testing of the // depth buffer on this particular node. This is // normally on in the 3-d scene graph and off in the 2-d // scene graph; it should be on for rendering most 3-d // objects properly. //////////////////////////////////////////////////////////////////// void NodePath:: set_depth_test(bool depth_test, int priority) { nassertv_always(!is_empty()); DepthTestAttrib::PandaCompareFunc mode = depth_test ? DepthTestAttrib::M_less : DepthTestAttrib::M_none; node()->set_attrib(DepthTestAttrib::make(mode), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_depth_test // Access: Published // Description: Completely removes any depth-test adjustment that // may have been set on this node via set_depth_test(). //////////////////////////////////////////////////////////////////// void NodePath:: clear_depth_test() { nassertv_always(!is_empty()); node()->clear_attrib(DepthTestAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_depth_test // Access: Published // Description: Returns true if a depth-test adjustment has been // explicitly set on this particular node via // set_depth_test(). If this returns true, then // get_depth_test() may be called to determine which has // been set. //////////////////////////////////////////////////////////////////// bool NodePath:: has_depth_test() const { nassertr_always(!is_empty(), false); return node()->has_attrib(DepthTestAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_depth_test // Access: Published // Description: Returns true if depth-test rendering has been // specifically set on this node via set_depth_test(), or // false if depth-test rendering has been specifically // disabled. If nothing has been specifically set, // returns true. See also has_depth_test(). //////////////////////////////////////////////////////////////////// bool NodePath:: get_depth_test() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(DepthTestAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const DepthTestAttrib *dta = DCAST(DepthTestAttrib, attrib); return (dta->get_mode() != DepthTestAttrib::M_none); } return true; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_depth_write // Access: Published // Description: Specifically sets or disables the writing to the // depth buffer on this particular node. This is // normally on in the 3-d scene graph and off in the 2-d // scene graph; it should be on for rendering most 3-d // objects properly. //////////////////////////////////////////////////////////////////// void NodePath:: set_depth_write(bool depth_write, int priority) { nassertv_always(!is_empty()); DepthWriteAttrib::Mode mode = depth_write ? DepthWriteAttrib::M_on : DepthWriteAttrib::M_off; node()->set_attrib(DepthWriteAttrib::make(mode), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_depth_write // Access: Published // Description: Completely removes any depth-write adjustment that // may have been set on this node via set_depth_write(). //////////////////////////////////////////////////////////////////// void NodePath:: clear_depth_write() { nassertv_always(!is_empty()); node()->clear_attrib(DepthWriteAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_depth_write // Access: Published // Description: Returns true if a depth-write adjustment has been // explicitly set on this particular node via // set_depth_write(). If this returns true, then // get_depth_write() may be called to determine which has // been set. //////////////////////////////////////////////////////////////////// bool NodePath:: has_depth_write() const { nassertr_always(!is_empty(), false); return node()->has_attrib(DepthWriteAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_depth_write // Access: Published // Description: Returns true if depth-write rendering has been // specifically set on this node via set_depth_write(), or // false if depth-write rendering has been specifically // disabled. If nothing has been specifically set, // returns true. See also has_depth_write(). //////////////////////////////////////////////////////////////////// bool NodePath:: get_depth_write() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(DepthWriteAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const DepthWriteAttrib *dta = DCAST(DepthWriteAttrib, attrib); return (dta->get_mode() != DepthWriteAttrib::M_off); } return true; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_depth_offset // Access: Published // Description: This instructs the graphics driver to apply an // offset or bias to the generated depth values for // rendered polygons, before they are written to the // depth buffer. This can be used to shift polygons // forward slightly, to resolve depth conflicts, or // self-shadowing artifacts on thin objects. // The bias is always an integer number, and each // integer increment represents the smallest possible // increment in Z that is sufficient to completely // resolve two coplanar polygons. Positive numbers // are closer towards the camera. //////////////////////////////////////////////////////////////////// void NodePath:: set_depth_offset(int bias, int priority) { nassertv_always(!is_empty()); node()->set_attrib(DepthOffsetAttrib::make(bias), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_depth_offset // Access: Published // Description: Completely removes any depth-offset adjustment that // may have been set on this node via set_depth_offset(). //////////////////////////////////////////////////////////////////// void NodePath:: clear_depth_offset() { nassertv_always(!is_empty()); node()->clear_attrib(DepthOffsetAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_depth_offset // Access: Published // Description: Returns true if a depth-offset adjustment has been // explicitly set on this particular node via // set_depth_offset(). If this returns true, then // get_depth_offset() may be called to determine which has // been set. //////////////////////////////////////////////////////////////////// bool NodePath:: has_depth_offset() const { nassertr_always(!is_empty(), false); return node()->has_attrib(DepthOffsetAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_depth_offset // Access: Published // Description: Returns the depth offset value if it has been // specified using set_depth_offset, or 0 if not. //////////////////////////////////////////////////////////////////// int NodePath:: get_depth_offset() const { nassertr_always(!is_empty(), 0); const RenderAttrib *attrib = node()->get_attrib(DepthOffsetAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const DepthOffsetAttrib *doa = DCAST(DepthOffsetAttrib, attrib); return doa->get_offset(); } return 0; } //////////////////////////////////////////////////////////////////// // Function: NodePath::do_billboard_axis // Access: Published // Description: Performs a billboard-type rotate to the indicated // camera node, one time only, and leaves the object // rotated. This is similar in principle to heads_up(). //////////////////////////////////////////////////////////////////// void NodePath:: do_billboard_axis(const NodePath &camera, PN_stdfloat offset) { nassertv_always(!is_empty()); CPT(TransformState) transform = camera.get_transform(get_parent()); const LMatrix4 &rel_mat = transform->get_mat(); LVector3 up = LVector3::up(); LVector3 rel_pos = -rel_mat.get_row3(3); LQuaternion quat; ::heads_up(quat, rel_pos, up); set_quat(quat); // Also slide the geometry towards the camera according to the // offset factor. if (offset != 0.0f) { LVector3 translate = rel_mat.get_row3(3); translate.normalize(); translate *= offset; set_pos(translate); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::do_billboard_point_eye // Access: Published // Description: Performs a billboard-type rotate to the indicated // camera node, one time only, and leaves the object // rotated. This is similar in principle to look_at(), // although the point_eye billboard effect cannot be // achieved using the ordinary look_at() call. //////////////////////////////////////////////////////////////////// void NodePath:: do_billboard_point_eye(const NodePath &camera, PN_stdfloat offset) { nassertv_always(!is_empty()); CPT(TransformState) transform = camera.get_transform(get_parent()); const LMatrix4 &rel_mat = transform->get_mat(); LVector3 up = LVector3::up() * rel_mat; LVector3 rel_pos = LVector3::forward() * rel_mat; LQuaternion quat; ::look_at(quat, rel_pos, up); set_quat(quat); // Also slide the geometry towards the camera according to the // offset factor. if (offset != 0.0f) { LVector3 translate = rel_mat.get_row3(3); translate.normalize(); translate *= offset; set_pos(translate); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::do_billboard_point_world // Access: Published // Description: Performs a billboard-type rotate to the indicated // camera node, one time only, and leaves the object // rotated. This is similar in principle to look_at(). //////////////////////////////////////////////////////////////////// void NodePath:: do_billboard_point_world(const NodePath &camera, PN_stdfloat offset) { nassertv_always(!is_empty()); CPT(TransformState) transform = camera.get_transform(get_parent()); const LMatrix4 &rel_mat = transform->get_mat(); LVector3 up = LVector3::up(); LVector3 rel_pos = -rel_mat.get_row3(3); LQuaternion quat; ::look_at(quat, rel_pos, up); set_quat(quat); // Also slide the geometry towards the camera according to the // offset factor. if (offset != 0.0f) { LVector3 translate = rel_mat.get_row3(3); translate.normalize(); translate *= offset; set_pos(translate); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_billboard_axis // Access: Published // Description: Puts a billboard transition on the node such that it // will rotate in two dimensions around the up axis, // towards a specified "camera" instead of to the // viewing camera. //////////////////////////////////////////////////////////////////// void NodePath:: set_billboard_axis(const NodePath &camera, PN_stdfloat offset) { nassertv_always(!is_empty()); CPT(RenderEffect) billboard = BillboardEffect::make (LVector3::up(), false, true, offset, camera, LPoint3(0.0f, 0.0f, 0.0f)); node()->set_effect(billboard); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_billboard_point_eye // Access: Published // Description: Puts a billboard transition on the node such that it // will rotate in three dimensions about the origin, // keeping its up vector oriented to the top of the // camera, towards a specified "camera" instead of to // the viewing camera. //////////////////////////////////////////////////////////////////// void NodePath:: set_billboard_point_eye(const NodePath &camera, PN_stdfloat offset) { nassertv_always(!is_empty()); CPT(RenderEffect) billboard = BillboardEffect::make (LVector3::up(), true, false, offset, camera, LPoint3(0.0f, 0.0f, 0.0f)); node()->set_effect(billboard); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_billboard_point_world // Access: Published // Description: Puts a billboard transition on the node such that it // will rotate in three dimensions about the origin, // keeping its up vector oriented to the sky, towards a // specified "camera" instead of to the viewing camera. //////////////////////////////////////////////////////////////////// void NodePath:: set_billboard_point_world(const NodePath &camera, PN_stdfloat offset) { nassertv_always(!is_empty()); CPT(RenderEffect) billboard = BillboardEffect::make (LVector3::up(), false, false, offset, camera, LPoint3(0.0f, 0.0f, 0.0f)); node()->set_effect(billboard); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_billboard // Access: Published // Description: Removes any billboard effect from the node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_billboard() { nassertv_always(!is_empty()); node()->clear_effect(BillboardEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_billboard // Access: Published // Description: Returns true if there is any billboard effect on // the node. //////////////////////////////////////////////////////////////////// bool NodePath:: has_billboard() const { nassertr_always(!is_empty(), false); return node()->has_effect(BillboardEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_compass // Access: Published // Description: Puts a compass effect on the node, so that it will // retain a fixed rotation relative to the reference // node (or render if the reference node is empty) // regardless of the transforms above it. //////////////////////////////////////////////////////////////////// void NodePath:: set_compass(const NodePath &reference) { nassertv_always(!is_empty()); node()->set_effect(CompassEffect::make(reference)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_compass // Access: Published // Description: Removes any compass effect from the node. //////////////////////////////////////////////////////////////////// void NodePath:: clear_compass() { nassertv_always(!is_empty()); node()->clear_effect(CompassEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_compass // Access: Published // Description: Returns true if there is any compass effect on // the node. //////////////////////////////////////////////////////////////////// bool NodePath:: has_compass() const { nassertr_always(!is_empty(), false); return node()->has_effect(CompassEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_transparency // Access: Published // Description: Specifically sets or disables transparent rendering // mode on this particular node. If no other nodes // override, this will cause items with a non-1 value // for alpha color to be rendered partially transparent. //////////////////////////////////////////////////////////////////// void NodePath:: set_transparency(TransparencyAttrib::Mode mode, int priority) { nassertv_always(!is_empty()); node()->set_attrib(TransparencyAttrib::make(mode), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_transparency // Access: Published // Description: Completely removes any transparency adjustment that // may have been set on this node via set_transparency(). // The geometry at this level and below will // subsequently be rendered either transparent or not, // to whatever other nodes may have had // set_transparency() on them. //////////////////////////////////////////////////////////////////// void NodePath:: clear_transparency() { nassertv_always(!is_empty()); node()->clear_attrib(TransparencyAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_transparency // Access: Published // Description: Returns true if a transparent-rendering adjustment // has been explicitly set on this particular node via // set_transparency(). If this returns true, then // get_transparency() may be called to determine whether // transparency has been explicitly enabled or // explicitly disabled for this node. //////////////////////////////////////////////////////////////////// bool NodePath:: has_transparency() const { nassertr_always(!is_empty(), false); return node()->has_attrib(TransparencyAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_transparency // Access: Published // Description: Returns the transparent rendering that has been // specifically set on this node via set_transparency(), or // M_none if nontransparent rendering has been specifically // set, or if nothing has been specifically set. See // also has_transparency(). This does not necessarily // imply that the geometry will or will not be rendered // transparent, as there may be other nodes that override. //////////////////////////////////////////////////////////////////// TransparencyAttrib::Mode NodePath:: get_transparency() const { nassertr_always(!is_empty(), TransparencyAttrib::M_none); const RenderAttrib *attrib = node()->get_attrib(TransparencyAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TransparencyAttrib *ta = DCAST(TransparencyAttrib, attrib); return ta->get_mode(); } return TransparencyAttrib::M_none; } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_antialias // Access: Published // Description: Specifies the antialiasing type that should be // applied at this node and below. See AntialiasAttrib. //////////////////////////////////////////////////////////////////// void NodePath:: set_antialias(unsigned short mode, int priority) { nassertv_always(!is_empty()); node()->set_attrib(AntialiasAttrib::make(mode), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_antialias // Access: Published // Description: Completely removes any antialias setting that // may have been set on this node via set_antialias(). //////////////////////////////////////////////////////////////////// void NodePath:: clear_antialias() { nassertv_always(!is_empty()); node()->clear_attrib(AntialiasAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_antialias // Access: Published // Description: Returns true if an antialias setting has been // explicitly mode on this particular node via // set_antialias(). If this returns true, then // get_antialias() may be called to determine what the // setting was. //////////////////////////////////////////////////////////////////// bool NodePath:: has_antialias() const { nassertr_always(!is_empty(), false); return node()->has_attrib(AntialiasAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_antialias // Access: Published // Description: Returns the antialias setting that has been // specifically set on this node via set_antialias(), or // M_none if no setting has been made. //////////////////////////////////////////////////////////////////// unsigned short NodePath:: get_antialias() const { nassertr_always(!is_empty(), AntialiasAttrib::M_none); const RenderAttrib *attrib = node()->get_attrib(AntialiasAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const AntialiasAttrib *ta = DCAST(AntialiasAttrib, attrib); return ta->get_mode(); } return AntialiasAttrib::M_none; } //////////////////////////////////////////////////////////////////// // Function: NodePath::has_audio_volume // Access: Published // Description: Returns true if an audio volume has been applied // to the referenced node, false otherwise. It is still // possible that volume at this node might have been // scaled by an ancestor node. //////////////////////////////////////////////////////////////////// bool NodePath:: has_audio_volume() const { nassertr_always(!is_empty(), false); return node()->has_attrib(AudioVolumeAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::clear_audio_volume // Access: Published // Description: Completely removes any audio volume from the // referenced node. This is preferable to simply // setting the audio volume to identity, as it also // removes the overhead associated with having an audio // volume at all. //////////////////////////////////////////////////////////////////// void NodePath:: clear_audio_volume() { nassertv_always(!is_empty()); node()->clear_attrib(AudioVolumeAttrib::get_class_slot()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_audio_volume // Access: Published // Description: Sets the audio volume component of the transform //////////////////////////////////////////////////////////////////// void NodePath:: set_audio_volume(PN_stdfloat volume, int priority) { nassertv_always(!is_empty()); const RenderAttrib *attrib = node()->get_attrib(AudioVolumeAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { priority = max(priority, node()->get_state()->get_override(AudioVolumeAttrib::get_class_slot())); CPT(AudioVolumeAttrib) ava = DCAST(AudioVolumeAttrib, attrib); // Modify the existing AudioVolumeAttrib to add the indicated // volume. node()->set_attrib(ava->set_volume(volume), priority); } else { // Create a new AudioVolumeAttrib for this node. node()->set_attrib(AudioVolumeAttrib::make(volume), priority); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::set_audio_volume_off // Access: Published // Description: Disables any audio volume attribute inherited from // above. This is not the same thing as // clear_audio_volume(), which undoes any previous // set_audio_volume() operation on this node; rather, // this actively disables any set_audio_volume() that // might be inherited from a parent node. // // It is legal to specify a new volume on the same // node with a subsequent call to set_audio_volume(); // this new scale will apply to lower nodes. //////////////////////////////////////////////////////////////////// void NodePath:: set_audio_volume_off(int priority) { nassertv_always(!is_empty()); node()->set_attrib(AudioVolumeAttrib::make_off(), priority); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_audio_volume // Access: Published // Description: Returns the complete audio volume that has been // applied to this node via a previous call to // set_audio_volume(), or 1. (identity) if no volume has // been applied to this particular node. //////////////////////////////////////////////////////////////////// PN_stdfloat NodePath:: get_audio_volume() const { const RenderAttrib *attrib = node()->get_attrib(AudioVolumeAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const AudioVolumeAttrib *ava = DCAST(AudioVolumeAttrib, attrib); return ava->get_volume(); } return 1.0f; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_net_audio_volume // Access: Published // Description: Returns the complete audio volume for this node // taking highers nodes in the graph into account. //////////////////////////////////////////////////////////////////// PN_stdfloat NodePath:: get_net_audio_volume() const { CPT(RenderState) net_state = get_net_state(); const RenderAttrib *attrib = net_state->get_attrib(AudioVolumeAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const AudioVolumeAttrib *ava = DCAST(AudioVolumeAttrib, attrib); if (ava != (const AudioVolumeAttrib *)NULL) { return ava->get_volume(); } } return 1.0f; } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_hidden_ancestor // Access: Published // Description: Returns the NodePath at or above the referenced node // that is hidden to the indicated camera(s), or an // empty NodePath if no ancestor of the referenced node // is hidden (and the node should be visible). //////////////////////////////////////////////////////////////////// NodePath NodePath:: get_hidden_ancestor(DrawMask camera_mask, Thread *current_thread) const { int pipeline_stage = current_thread->get_pipeline_stage(); NodePathComponent *comp; for (comp = _head; comp != (NodePathComponent *)NULL; comp = comp->get_next(pipeline_stage, current_thread)) { PandaNode *node = comp->get_node(); if (node->is_overall_hidden() || ((node->get_draw_show_mask() | ~node->get_draw_control_mask()) & camera_mask).is_zero()) { NodePath result; result._head = comp; return result; } } return not_found(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::stash // Access: Published // Description: Removes the referenced node (and the entire subgraph // below this node) from the scene graph in any normal // sense. The node will no longer be visible and is not // tested for collisions; furthermore, no normal scene // graph traversal will visit the node. The node's // bounding volume no longer contributes to its parent's // bounding volume. // // A stashed node cannot be located by a normal find() // operation (although a special find string can still // retrieve it). //////////////////////////////////////////////////////////////////// void NodePath:: stash(int sort, Thread *current_thread) { nassertv_always(!is_singleton() && !is_empty()); nassertv(verify_complete()); int pipeline_stage = current_thread->get_pipeline_stage(); bool reparented = PandaNode::reparent(_head->get_next(pipeline_stage, current_thread), _head, sort, true, pipeline_stage, current_thread); nassertv(reparented); } //////////////////////////////////////////////////////////////////// // Function: NodePath::unstash // Access: Published // Description: Undoes the effect of a previous stash() on this // node: makes the referenced node (and the entire // subgraph below this node) once again part of the // scene graph. //////////////////////////////////////////////////////////////////// void NodePath:: unstash(int sort, Thread *current_thread) { nassertv_always(!is_singleton() && !is_empty()); nassertv(verify_complete()); int pipeline_stage = current_thread->get_pipeline_stage(); bool reparented = PandaNode::reparent(_head->get_next(pipeline_stage, current_thread), _head, sort, false, pipeline_stage, current_thread); nassertv(reparented); } //////////////////////////////////////////////////////////////////// // Function: NodePath::unstash_all // Access: Published // Description: Unstashes this node and all stashed child nodes. //////////////////////////////////////////////////////////////////// void NodePath:: unstash_all(Thread *current_thread) { NodePathCollection stashed_descendents = find_all_matches("**/@@*"); stashed_descendents.unstash(); unstash(0, current_thread); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_stashed_ancestor // Access: Published // Description: Returns the NodePath at or above the referenced node // that is stashed, or an empty NodePath if no ancestor // of the referenced node is stashed (and the node should // be visible). //////////////////////////////////////////////////////////////////// NodePath NodePath:: get_stashed_ancestor(Thread *current_thread) const { NodePathComponent *comp = _head; if (comp != (NodePathComponent *)NULL) { int pipeline_stage = current_thread->get_pipeline_stage(); NodePathComponent *next = comp->get_next(pipeline_stage, current_thread); while (next != (NodePathComponent *)NULL) { PandaNode *node = comp->get_node(); PandaNode *parent_node = next->get_node(); if (parent_node->find_stashed(node) >= 0) { NodePath result; result._head = comp; return result; } comp = next; next = next->get_next(pipeline_stage, current_thread); } } return not_found(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::verify_complete // Access: Published // Description: Returns true if all of the nodes described in the // NodePath are connected, or false otherwise. //////////////////////////////////////////////////////////////////// bool NodePath:: verify_complete(Thread *current_thread) const { if (is_empty()) { return true; } #ifdef HAVE_THREADS if (Thread::is_true_threads()) { // In a threaded environment, we can't reliably test this, since a // sub-thread may be mucking with the NodePath's ancestry as we // try to validate it. NodePaths are inherently not thread-safe, // but generally that's not an issue. return true; } #endif // HAVE_THREADS PStatTimer timer(_verify_complete_pcollector); const NodePathComponent *comp = _head; nassertr(comp != (const NodePathComponent *)NULL, false); int pipeline_stage = current_thread->get_pipeline_stage(); PandaNode *node = comp->get_node(); nassertr(node != (const PandaNode *)NULL, false); int length = comp->get_length(pipeline_stage, current_thread); comp = comp->get_next(pipeline_stage, current_thread); length--; while (comp != (const NodePathComponent *)NULL) { PandaNode *next_node = comp->get_node(); nassertr(next_node != (const PandaNode *)NULL, false); if (node->find_parent(next_node) < 0) { pgraph_cat.warning() << *this << " is incomplete; " << *node << " is not a child of " << *next_node << "\n"; return false; } if (comp->get_length(pipeline_stage, current_thread) != length) { pgraph_cat.warning() << *this << " is incomplete; length at " << *next_node << " indicates " << comp->get_length(pipeline_stage, current_thread) << " while length at " << *node << " indicates " << length << "\n"; return false; } node = next_node; comp = comp->get_next(pipeline_stage, current_thread); length--; } return true; } //////////////////////////////////////////////////////////////////// // Function: NodePath::premunge_scene // Access: Published // Description: Walks through the scene graph beginning at the bottom // node, and internally adjusts any GeomVertexFormats // for optimal rendering on the indicated GSG. If this // step is not done prior to rendering, the formats will // be optimized at render time instead, for a small // cost. // // It is not normally necessary to do this on a model // loaded directly from disk, since the loader will do // this by default. //////////////////////////////////////////////////////////////////// void NodePath:: premunge_scene(GraphicsStateGuardianBase *gsg) { nassertv_always(!is_empty()); CPT(RenderState) state = RenderState::make_empty(); if (has_parent()) { state = get_parent().get_net_state(); } SceneGraphReducer gr(gsg); gr.premunge(node(), state); } //////////////////////////////////////////////////////////////////// // Function: NodePath::prepare_scene // Access: Published // Description: Walks through the scene graph beginning at the bottom // node, and does whatever initialization is required to // render the scene properly with the indicated GSG. It // is not strictly necessary to call this, since the GSG // will initialize itself when the scene is rendered, // but this may take some of the overhead away from that // process. // // In particular, this will ensure that textures and // vertex buffers within the scene are loaded into // graphics memory. //////////////////////////////////////////////////////////////////// void NodePath:: prepare_scene(GraphicsStateGuardianBase *gsg) { nassertv_always(!is_empty()); node()->prepare_scene(gsg, get_net_state()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::show_bounds // Access: Published // Description: Causes the bounding volume of the bottom node and all // of its descendants (that is, the bounding volume // associated with the the bottom arc) to be rendered, // if possible. The rendering method is less than // optimal; this is intended primarily for debugging. //////////////////////////////////////////////////////////////////// void NodePath:: show_bounds() { nassertv_always(!is_empty()); node()->set_effect(ShowBoundsEffect::make(false)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::show_tight_bounds // Access: Published // Description: Similar to show_bounds(), this draws a bounding box // representing the "tight" bounds of this node and all // of its descendants. The bounding box is recomputed // every frame by reexamining all of the vertices; this // is far from efficient, but this is intended for // debugging. //////////////////////////////////////////////////////////////////// void NodePath:: show_tight_bounds() { nassertv_always(!is_empty()); node()->set_effect(ShowBoundsEffect::make(true)); } //////////////////////////////////////////////////////////////////// // Function: NodePath::hide_bounds // Access: Published // Description: Stops the rendering of the bounding volume begun with // show_bounds(). //////////////////////////////////////////////////////////////////// void NodePath:: hide_bounds() { nassertv_always(!is_empty()); node()->clear_effect(ShowBoundsEffect::get_class_type()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::get_bounds // Access: Published // Description: Returns a newly-allocated bounding volume containing // the bottom node and all of its descendants. This is // the bounding volume on the bottom arc, converted to // the local coordinate space of the node. //////////////////////////////////////////////////////////////////// PT(BoundingVolume) NodePath:: get_bounds(Thread *current_thread) const { nassertr_always(!is_empty(), new BoundingSphere); return node()->get_bounds(current_thread)->make_copy(); } //////////////////////////////////////////////////////////////////// // Function: NodePath::force_recompute_bounds // Access: Published // Description: Forces the recomputing of all the bounding volumes at // every node in the subgraph beginning at this node and // below. // // This should not normally need to be called, since the // bounding volumes are supposed to be recomputed // automatically when necessary. It may be useful when // debugging, to verify that the bounding volumes have // not become inadvertently stale; it may also be useful // to force animated characters to update their bounding // volumes (which does not presently happen // automatically). //////////////////////////////////////////////////////////////////// void NodePath:: force_recompute_bounds() { nassertv_always(!is_empty()); r_force_recompute_bounds(node()); } //////////////////////////////////////////////////////////////////// // Function: NodePath::write_bounds // Access: Published // Description: Writes a description of the bounding volume // containing the bottom node and all of its descendants // to the indicated output stream. //////////////////////////////////////////////////////////////////// void NodePath:: write_bounds(ostream &out) const { get_bounds()->write(out); } //////////////////////////////////////////////////////////////////// // Function: NodePath::calc_tight_bounds // Access: Published // Description: Calculates the minimum and maximum vertices of all // Geoms at this NodePath's bottom node and below. This // is a tight bounding box; it will generally be tighter // than the bounding volume returned by get_bounds() // (but it is more expensive to compute). // // The bounding box is computed relative to the parent // node's coordinate system by default. You can // optionally specify a different NodePath to compute // the bounds relative to. Note that the box is always // axis-aligned against the given NodePath's coordinate // system, so you might get a differently sized box // depending on which node you pass. // // The return value is true if any points are within the // bounding volume, or false if none are. //////////////////////////////////////////////////////////////////// bool NodePath:: calc_tight_bounds(LPoint3 &min_point, LPoint3 &max_point, const NodePath &other, Thread *current_thread) const { min_point.set(0.0f, 0.0f, 0.0f); max_point.set(0.0f, 0.0f, 0.0f); nassertr_always(!is_empty(), false); CPT(TransformState) transform = TransformState::make_identity(); if (!other.is_empty()) { transform = get_transform(other)->compose(get_transform()->get_inverse()); } bool found_any = false; node()->calc_tight_bounds(min_point, max_point, found_any, MOVE(transform), current_thread); return found_any; } /* NB: Had to remove this function to avoid circular dependency when moving SceneGraphAnalyzer into pgraphnodes, attempting to reduce size of pgraph. This function is now defined as a Python extension function instead. //////////////////////////////////////////////////////////////////// // Function: NodePath::analyze // Access: Published // Description: Analyzes the geometry below this node and reports the // number of vertices, triangles, etc. This is the same // information reported by the bam-info program. //////////////////////////////////////////////////////////////////// void NodePath:: analyze() const { nassertv_always(!is_empty()); SceneGraphAnalyzer sga; sga.add_node(node()); if (sga.get_num_lod_nodes() == 0) { sga.write(nout); } else { nout << "At highest LOD:\n"; SceneGraphAnalyzer sga2; sga2.set_lod_mode(SceneGraphAnalyzer::LM_highest); sga2.add_node(node()); sga2.write(nout); nout << "\nAt lowest LOD:\n"; sga2.clear(); sga2.set_lod_mode(SceneGraphAnalyzer::LM_lowest); sga2.add_node(node()); sga2.write(nout); nout << "\nAll nodes:\n"; sga.write(nout); } } */ //////////////////////////////////////////////////////////////////// // Function: NodePath::flatten_light // Access: Published // Description: Lightly flattens out the hierarchy below this node by // applying transforms, colors, and texture matrices // from the nodes onto the vertices, but does not remove // any nodes. // // This can result in improved rendering performance // because there will be fewer transforms in the // resulting scene graph, but the number of nodes will // remain the same. // // In particular, any NodePaths that reference nodes // within this hierarchy will not be damaged. However, // since this operation will remove transforms from the // scene graph, it may be dangerous to apply to nodes // where you expect to dynamically modify the transform, // or where you expect the geometry to remain in a // particular local coordinate system. // // The return value is always 0, since flatten_light // does not remove any nodes. //////////////////////////////////////////////////////////////////// int NodePath:: flatten_light() { nassertr_always(!is_empty(), 0); SceneGraphReducer gr; gr.apply_attribs(node()); return 0; } //////////////////////////////////////////////////////////////////// // Function: NodePath::flatten_medium // Access: Published // Description: A more thorough flattening than flatten_light(), this // first applies all the transforms, colors, and texture // matrices from the nodes onto the vertices, and then // removes unneeded grouping nodes--nodes that have // exactly one child, for instance, but have no special // properties in themselves. // // This results in improved performance over // flatten_light() because the number of nodes in the // scene graph is reduced. // // The return value is the number of nodes removed. //////////////////////////////////////////////////////////////////// int NodePath:: flatten_medium() { nassertr_always(!is_empty(), 0); SceneGraphReducer gr; gr.apply_attribs(node()); int num_removed = gr.flatten(node(), 0); if (flatten_geoms) { gr.make_compatible_state(node()); gr.collect_vertex_data(node()); gr.unify(node(), true); } return num_removed; } //////////////////////////////////////////////////////////////////// // Function: NodePath::flatten_strong // Access: Published // Description: The strongest possible flattening. This first // applies all of the transforms to the vertices, as in // flatten_medium(), but then it will combine sibling // nodes together when possible, in addition to removing // unnecessary parent-child nodes. This can result in // substantially fewer nodes, but any nicely-grouped // hierachical bounding volumes may be lost. // // It is generally a good idea to apply this kind of // flattening only to nodes that will be culled largely // as a single unit, like a car. Applying this to an // entire scene may result in overall poorer performance // because of less-effective culling. //////////////////////////////////////////////////////////////////// int NodePath:: flatten_strong() { nassertr_always(!is_empty(), 0); SceneGraphReducer gr; gr.apply_attribs(node()); int num_removed = gr.flatten(node(), ~0); if (flatten_geoms) { gr.make_compatible_state(node()); gr.collect_vertex_data(node(), ~(SceneGraphReducer::CVD_format | SceneGraphReducer::CVD_name | SceneGraphReducer::CVD_animation_type)); gr.unify(node(), false); } return num_removed; } //////////////////////////////////////////////////////////////////// // Function: NodePath::apply_texture_colors // Access: Published // Description: Removes textures from Geoms at this node and below by // applying the texture colors to the vertices. This is // primarily useful to simplify a low-LOD model. The // texture colors are replaced by flat colors that // approximate the original textures. // // Only the bottommost texture on each Geom is used (if // there is more than one), and it is applied as if it // were M_modulate, and WM_repeat, regardless of its // actual settings. If the texture has a // simple_ram_image, this may be used if the main image // isn't resident. // // After this call, there will be no texturing specified // at this level and below. Of course, there might // still be texturing inherited from above. //////////////////////////////////////////////////////////////////// void NodePath:: apply_texture_colors() { nassertv_always(!is_empty()); SceneGraphReducer gr; gr.apply_attribs(node(), SceneGraphReducer::TT_apply_texture_color | SceneGraphReducer::TT_tex_matrix | SceneGraphReducer::TT_other); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_net_tag // Access: Published // Description: Returns the lowest ancestor of this node that // contains a tag definition with the indicated key, if // any, or an empty NodePath if no ancestor of this node // contains this tag definition. See set_tag(). //////////////////////////////////////////////////////////////////// NodePath NodePath:: find_net_tag(const string &key) const { if (is_empty()) { return NodePath::not_found(); } if (has_tag(key)) { return *this; } return get_parent().find_net_tag(key); } //////////////////////////////////////////////////////////////////// // Function: NodePath::write_bam_file // Access: Published // Description: Writes the contents of this node and below out to a // bam file with the indicated filename. This file may // then be read in again, as is, at some later point. // Returns true if successful, false on some kind of // error. //////////////////////////////////////////////////////////////////// bool NodePath:: write_bam_file(const Filename &filename) const { nassertr_always(!is_empty(), false); BamFile bam_file; bool okflag = false; if (bam_file.open_write(filename)) { if (bam_file.write_object(node())) { okflag = true; } bam_file.close(); } return okflag; } //////////////////////////////////////////////////////////////////// // Function: NodePath::write_bam_stream // Access: Published // Description: Writes the contents of this node and below out to the // indicated stream. //////////////////////////////////////////////////////////////////// bool NodePath:: write_bam_stream(ostream &out) const { nassertr_always(!is_empty(), false); BamFile bam_file; bool okflag = false; if (bam_file.open_write(out)) { if (bam_file.write_object(node())) { okflag = true; } bam_file.close(); } return okflag; } //////////////////////////////////////////////////////////////////// // Function: NodePath::encode_to_bam_stream // Access: Published // Description: Converts the NodePath object into a single // stream of data using a BamWriter, and stores that // data in the indicated string. Returns true on // success, false on failure. // // If the BamWriter is NULL, this behaves the same way // as NodePath::write_bam_stream() and // PandaNode::encode_to_bam_stream(), in the sense that // it only writes this node and all nodes below it. // // However, if the BamWriter is not NULL, it behaves // very differently. In this case, it encodes the // *entire graph* of all nodes connected to the // NodePath, including all parent nodes and siblings. // This is necessary for correct streaming of related // NodePaths and restoration of instances, etc., but it // does mean you must detach() a node before writing it // if you want to limit the nodes that get written. // // This method is used by __reduce__ to handle streaming // of NodePaths to a pickle file. The BamWriter case is // used by the direct.stdpy.pickle module, while the // saner, non-BamWriter case is used when the standard // pickle module calls this function. //////////////////////////////////////////////////////////////////// bool NodePath:: encode_to_bam_stream(string &data, BamWriter *writer) const { data.clear(); ostringstream stream; DatagramOutputFile dout; if (!dout.open(stream)) { return false; } BamWriter local_writer; bool used_local_writer = false; if (writer == NULL) { // Create our own writer. if (!dout.write_header(_bam_header)) { return false; } writer = &local_writer; used_local_writer = true; } writer->set_target(&dout); int num_nodes = get_num_nodes(); if (used_local_writer && num_nodes > 1) { // In this case--no BamWriter--we only write the bottom node. num_nodes = 1; } // Write an initial Datagram to represent the error type and // number of nodes. Datagram dg; dg.add_uint8(_error_type); dg.add_int32(num_nodes); if (!dout.put_datagram(dg)) { writer->set_target(NULL); return false; } // Now write the nodes, one at a time. for (int i = 0; i < num_nodes; ++i) { PandaNode *node = get_node(num_nodes - i - 1); nassertr(node != NULL, false); if (!writer->write_object(node)) { writer->set_target(NULL); return false; } } writer->set_target(NULL); data = stream.str(); return true; } //////////////////////////////////////////////////////////////////// // Function: NodePath::decode_from_bam_stream // Access: Published, Static // Description: Reads the string created by a previous call to // encode_to_bam_stream(), and extracts and // returns the NodePath on that string. Returns NULL on // error. //////////////////////////////////////////////////////////////////// NodePath NodePath:: decode_from_bam_stream(const string &data, BamReader *reader) { NodePath result; istringstream stream(data); DatagramInputFile din; if (!din.open(stream)) { return NodePath::fail(); } BamReader local_reader; if (reader == NULL) { // Create a local reader. string head; if (!din.read_header(head, _bam_header.size())) { return NodePath::fail(); } if (head != _bam_header) { return NodePath::fail(); } reader = &local_reader; } reader->set_source(&din); // One initial datagram to encode the error type, and the number of nodes. Datagram dg; if (!din.get_datagram(dg)) { return NodePath::fail(); } DatagramIterator dgi(dg); ErrorType error_type = (ErrorType)dgi.get_uint8(); int num_nodes = dgi.get_int32(); if (num_nodes == 0) { // An empty NodePath. result._error_type = error_type; } else { // A real NodePath. Ignore error_type. for (int i = 0; i < num_nodes; ++i) { TypedWritable *object = reader->read_object(); if (object == (TypedWritable *)NULL || !object->is_of_type(PandaNode::get_class_type())) { reader->set_source(NULL); return NodePath::fail(); } if (!reader->resolve()) { reader->set_source(NULL); return NodePath::fail(); } PandaNode *node = DCAST(PandaNode, object); result = NodePath(result, node); } } reader->set_source(NULL); return result; } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_common_ancestor // Access: Private, Static // Description: Walks up from both NodePaths to find the first node // that both have in common, if any. Fills a_count and // b_count with the number of nodes below the common // node in each path. // // The return value is the NodePathComponent of the node // they have in common, or NULL if they have nothing in // common. //////////////////////////////////////////////////////////////////// NodePathComponent *NodePath:: find_common_ancestor(const NodePath &a, const NodePath &b, int &a_count, int &b_count, Thread *current_thread) { nassertr(!a.is_empty() && !b.is_empty(), NULL); NodePathComponent *ac = a._head; NodePathComponent *bc = b._head; a_count = 0; b_count = 0; int pipeline_stage = current_thread->get_pipeline_stage(); // Shorten up the longer one until they are the same length. while (ac->get_length(pipeline_stage, current_thread) > bc->get_length(pipeline_stage, current_thread)) { nassertr(ac != (NodePathComponent *)NULL, NULL); ac = ac->get_next(pipeline_stage, current_thread); a_count++; } while (bc->get_length(pipeline_stage, current_thread) > ac->get_length(pipeline_stage, current_thread)) { nassertr(bc != (NodePathComponent *)NULL, NULL); bc = bc->get_next(pipeline_stage, current_thread); b_count++; } // Now shorten them both up until we reach the same component. while (ac != bc) { // These shouldn't go to NULL unless they both go there together. nassertr(ac != (NodePathComponent *)NULL, NULL); nassertr(bc != (NodePathComponent *)NULL, NULL); ac = ac->get_next(pipeline_stage, current_thread); a_count++; bc = bc->get_next(pipeline_stage, current_thread); b_count++; } return ac; } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_get_net_state // Access: Private // Description: Recursively determines the net state changes to the // indicated component node from the root of the graph. //////////////////////////////////////////////////////////////////// CPT(RenderState) NodePath:: r_get_net_state(NodePathComponent *comp, Thread *current_thread) const { if (comp == (NodePathComponent *)NULL) { return RenderState::make_empty(); } else { CPT(RenderState) state = comp->get_node()->get_state(current_thread); int pipeline_stage = current_thread->get_pipeline_stage(); return r_get_net_state(comp->get_next(pipeline_stage, current_thread), current_thread)->compose(state); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_get_partial_state // Access: Private // Description: Recursively determines the net state changes to the // indicated component node from the nth node above it. // If n exceeds the length of the path, this returns the // net transform from the root of the graph. //////////////////////////////////////////////////////////////////// CPT(RenderState) NodePath:: r_get_partial_state(NodePathComponent *comp, int n, Thread *current_thread) const { if (n == 0 || comp == (NodePathComponent *)NULL) { return RenderState::make_empty(); } else { CPT(RenderState) state = comp->get_node()->get_state(current_thread); int pipeline_stage = current_thread->get_pipeline_stage(); return r_get_partial_state(comp->get_next(pipeline_stage, current_thread), n - 1, current_thread)->compose(state); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_get_net_transform // Access: Private // Description: Recursively determines the net transform to the // indicated component node from the root of the graph. //////////////////////////////////////////////////////////////////// CPT(TransformState) NodePath:: r_get_net_transform(NodePathComponent *comp, Thread *current_thread) const { if (comp == (NodePathComponent *)NULL) { return TransformState::make_identity(); } else { int pipeline_stage = current_thread->get_pipeline_stage(); CPT(TransformState) net_transform = r_get_net_transform(comp->get_next(pipeline_stage, current_thread), current_thread); PandaNode *node = comp->get_node(); CPT(TransformState) transform = node->get_transform(current_thread); CPT(RenderEffects) effects = node->get_effects(current_thread); if (effects->has_adjust_transform()) { effects->adjust_transform(net_transform, transform, node); } return net_transform->compose(transform); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_get_partial_transform // Access: Private // Description: Recursively determines the net transform to the // indicated component node from the nth node above it. // If n exceeds the length of the path, this returns the // net transform from the root of the graph. // // If any node in the path had a net_transform effect // applied, returns NULL--in this case the partial // transform cannot be easily determined. //////////////////////////////////////////////////////////////////// CPT(TransformState) NodePath:: r_get_partial_transform(NodePathComponent *comp, int n, Thread *current_thread) const { if (n == 0 || comp == (NodePathComponent *)NULL) { return TransformState::make_identity(); } else { if (comp->get_node()->get_effects(current_thread)->has_adjust_transform()) { return NULL; } CPT(TransformState) transform = comp->get_node()->get_transform(current_thread); int pipeline_stage = current_thread->get_pipeline_stage(); CPT(TransformState) partial = r_get_partial_transform(comp->get_next(pipeline_stage, current_thread), n - 1, current_thread); if (partial == (const TransformState *)NULL) { return NULL; } return partial->compose(transform); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_get_net_prev_transform // Access: Private // Description: Recursively determines the net "previous" transform // to the indicated component node from the root of the // graph. //////////////////////////////////////////////////////////////////// CPT(TransformState) NodePath:: r_get_net_prev_transform(NodePathComponent *comp, Thread *current_thread) const { if (comp == (NodePathComponent *)NULL) { return TransformState::make_identity(); } else { CPT(TransformState) transform = comp->get_node()->get_prev_transform(current_thread); int pipeline_stage = current_thread->get_pipeline_stage(); return r_get_net_prev_transform(comp->get_next(pipeline_stage, current_thread), current_thread)->compose(transform); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_get_partial_prev_transform // Access: Private // Description: Recursively determines the net "previous" transform // to the indicated component node from the nth node // above it. If n exceeds the length of the path, this // returns the net previous transform from the root of // the graph. //////////////////////////////////////////////////////////////////// CPT(TransformState) NodePath:: r_get_partial_prev_transform(NodePathComponent *comp, int n, Thread *current_thread) const { if (n == 0 || comp == (NodePathComponent *)NULL) { return TransformState::make_identity(); } else { CPT(TransformState) transform = comp->get_node()->get_prev_transform(current_thread); int pipeline_stage = current_thread->get_pipeline_stage(); return r_get_partial_prev_transform(comp->get_next(pipeline_stage, current_thread), n - 1, current_thread)->compose(transform); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_matches // Access: Private // Description: Finds up to max_matches matches against the given // path string from this node and deeper. The // max_matches count indicates the maximum number of // matches to return, or -1 not to limit the number // returned. //////////////////////////////////////////////////////////////////// void NodePath:: find_matches(NodePathCollection &result, const string &path, int max_matches) const { if (is_empty()) { pgraph_cat.warning() << "Attempt to extend an empty NodePath by '" << path << "'.\n"; return; } FindApproxPath approx_path; if (approx_path.add_string(path)) { find_matches(result, approx_path, max_matches); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_matches // Access: Private // Description: Finds up to max_matches matches against the given // approx_path from this node and deeper. The // max_matches count indicates the maximum number of // matches to return, or -1 not to limit the number // returned. //////////////////////////////////////////////////////////////////// void NodePath:: find_matches(NodePathCollection &result, FindApproxPath &approx_path, int max_matches) const { if (is_empty()) { pgraph_cat.warning() << "Attempt to extend an empty NodePath by: " << approx_path << ".\n"; return; } // We start with just one entry on the level. FindApproxLevelEntry *level = new FindApproxLevelEntry(WorkingNodePath(*this), approx_path); nassertv(level->_node_path.is_valid()); find_matches(result, level, max_matches); } //////////////////////////////////////////////////////////////////// // Function: NodePath::find_matches // Access: Private // Description: The fundamental implementation of find_matches(), // given a starting level (a linked list of // FindApproxLevelEntry objects). //////////////////////////////////////////////////////////////////// void NodePath:: find_matches(NodePathCollection &result, FindApproxLevelEntry *level, int max_matches) const { int num_levels_remaining = _max_search_depth; FindApproxLevelEntry *deleted_entries = NULL; while (num_levels_remaining > 0 && level != NULL) { if (pgraph_cat.is_spam()) { pgraph_cat.spam() << "find_matches pass: " << result << ", " << max_matches << ", " << num_levels_remaining << "\n"; level->write_level(pgraph_cat.spam(false), 4); } num_levels_remaining--; FindApproxLevelEntry *next_level = NULL; // For each node in the current level, build up the set of possible // matches in the next level. FindApproxLevelEntry *entry = level; while (entry != (FindApproxLevelEntry *)NULL) { if (entry->consider_node(result, next_level, max_matches, 0)) { // If we found the requisite number of matches, we can stop. // Delete all remaining entries and return immediately. while (entry != (FindApproxLevelEntry *)NULL) { FindApproxLevelEntry *next = entry->_next; delete entry; entry = next; } while (next_level != (FindApproxLevelEntry *)NULL) { FindApproxLevelEntry *next = next_level->_next; delete next_level; next_level = next; } while (deleted_entries != (FindApproxLevelEntry *)NULL) { FindApproxLevelEntry *next = deleted_entries->_next; delete deleted_entries; deleted_entries = next; } return; } // Move the entry to the delete chain so we can delete it before // we return from this method. (We can't delete it immediately, // because there might be WorkingNodePaths in the next_level // that reference the WorkingNodePath object within the entry.) FindApproxLevelEntry *next = entry->_next; entry->_next = deleted_entries; deleted_entries = entry; entry = next; } // Make sure the remaining entries from this level are added to // the delete chain. while (entry != (FindApproxLevelEntry *)NULL) { FindApproxLevelEntry *next = entry->_next; entry->_next = deleted_entries; deleted_entries = entry; entry = next; } level = next_level; } // Now it's safe to delete all entries on the delete chain. while (deleted_entries != (FindApproxLevelEntry *)NULL) { FindApproxLevelEntry *next = deleted_entries->_next; delete deleted_entries; deleted_entries = next; } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_clear_model_nodes // Access: Private // Description: The recursive implementation of // clear_model_nodes(). This walks through the // subgraph defined by the indicated node and below. //////////////////////////////////////////////////////////////////// int NodePath:: r_clear_model_nodes(PandaNode *node) { int count = 0; if (node->is_of_type(ModelNode::get_class_type())) { ModelNode *mnode; DCAST_INTO_R(mnode, node, count); mnode->set_preserve_transform(ModelNode::PT_drop_node); ++count; } PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { count += r_clear_model_nodes(cr.get_child(i)); } return count; } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_adjust_all_priorities // Access: Private // Description: The recursive implementation of // adjust_all_priorities(). This walks through the // subgraph defined by the indicated node and below. //////////////////////////////////////////////////////////////////// void NodePath:: r_adjust_all_priorities(PandaNode *node, int adjustment) { node->set_state(node->get_state()->adjust_all_priorities(adjustment)); if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_V(gnode, node); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { gnode->set_geom_state(i, gnode->get_geom_state(i)->adjust_all_priorities(adjustment)); } } PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { r_adjust_all_priorities(cr.get_child(i), adjustment); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_force_recompute_bounds // Access: Private // Description: //////////////////////////////////////////////////////////////////// void NodePath:: r_force_recompute_bounds(PandaNode *node) { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_V(gnode, node); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { const Geom *geom = gnode->get_geom(i); geom->mark_bounds_stale(); } } node->mark_bounds_stale(); // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { r_force_recompute_bounds(cr.get_child(i)); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_set_collide_mask // Access: Private // Description: Recursively applies the indicated collide mask to the // nodes at and below this node. //////////////////////////////////////////////////////////////////// void NodePath:: r_set_collide_mask(PandaNode *node, CollideMask and_mask, CollideMask or_mask, TypeHandle node_type) { if (node->is_of_type(node_type)) { CollideMask into_collide_mask = node->get_into_collide_mask(); into_collide_mask = (into_collide_mask & and_mask) | or_mask; node->set_into_collide_mask(into_collide_mask); } PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { r_set_collide_mask(cr.get_child(i), and_mask, or_mask, node_type); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_has_vertex_column // Access: Private // Description: //////////////////////////////////////////////////////////////////// bool NodePath:: r_has_vertex_column(PandaNode *node, const InternalName *name) const { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_R(gnode, node, false); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { const Geom *geom = gnode->get_geom(i); CPT(GeomVertexData) vdata = geom->get_vertex_data(); if (vdata->has_column(name)) { return true; } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); if (r_has_vertex_column(child, name)) { return true; } } return false; } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_all_vertex_columns // Access: Private // Description: //////////////////////////////////////////////////////////////////// void NodePath:: r_find_all_vertex_columns(PandaNode *node, NodePath::InternalNames &vertex_columns) const { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_V(gnode, node); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; ++i) { const Geom *geom = gnode->get_geom(i); const GeomVertexFormat *format = geom->get_vertex_data()->get_format(); int num_arrays = format->get_num_arrays(); for (int j = 0; j < num_arrays; ++j) { const GeomVertexArrayFormat *array = format->get_array(j); int num_columns = array->get_num_columns(); for (int k = 0; k < num_columns; ++k) { const GeomVertexColumn *column = array->get_column(k); vertex_columns.insert(column->get_name()); } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); r_find_all_vertex_columns(child, vertex_columns); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_texture // Access: Private // Description: //////////////////////////////////////////////////////////////////// Texture *NodePath:: r_find_texture(PandaNode *node, const RenderState *state, const GlobPattern &glob) const { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_R(gnode, node, NULL); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) geom_state = state->compose(gnode->get_geom_state(i)); // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { Texture *texture = ta->get_on_texture(ta->get_on_stage(i)); if (texture != (Texture *)NULL) { if (glob.matches(texture->get_name())) { return texture; } } } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); CPT(RenderState) next_state = state->compose(child->get_state()); Texture *result = r_find_texture(child, next_state, glob); if (result != (Texture *)NULL) { return result; } } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_all_textures // Access: Private // Description: //////////////////////////////////////////////////////////////////// void NodePath:: r_find_all_textures(PandaNode *node, const RenderState *state, NodePath::Textures &textures) const { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_V(gnode, node); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) geom_state = state->compose(gnode->get_geom_state(i)); // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { Texture *texture = ta->get_on_texture(ta->get_on_stage(i)); if (texture != (Texture *)NULL) { textures.insert(texture); } } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); CPT(RenderState) next_state = state->compose(child->get_state()); r_find_all_textures(child, next_state, textures); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_texture // Access: Private // Description: //////////////////////////////////////////////////////////////////// Texture * NodePath:: r_find_texture(PandaNode *node, TextureStage *stage) const { // Look for a TextureAttrib on the node. const RenderAttrib *attrib = node->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); if (ta->has_on_stage(stage)) { return ta->get_on_texture(stage); } } if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_R(gnode, node, NULL); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) geom_state = gnode->get_geom_state(i); // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); if (ta->has_on_stage(stage)) { return ta->get_on_texture(stage); } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); Texture *result = r_find_texture(child, stage); if (result != (Texture *)NULL) { return result; } } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_all_textures // Access: Private // Description: //////////////////////////////////////////////////////////////////// void NodePath:: r_find_all_textures(PandaNode *node, TextureStage *stage, NodePath::Textures &textures) const { // Look for a TextureAttrib on the node. const RenderAttrib *attrib = node->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); if (ta->has_on_stage(stage)) { textures.insert(ta->get_on_texture(stage)); } } if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_V(gnode, node); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) geom_state = gnode->get_geom_state(i); // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); if (ta->has_on_stage(stage)) { textures.insert(ta->get_on_texture(stage)); } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); r_find_all_textures(child, stage, textures); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_texture_stage // Access: Private // Description: //////////////////////////////////////////////////////////////////// TextureStage * NodePath:: r_find_texture_stage(PandaNode *node, const RenderState *state, const GlobPattern &glob) const { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_R(gnode, node, NULL); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) geom_state = state->compose(gnode->get_geom_state(i)); // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { TextureStage *texture_stage = ta->get_on_stage(i); if (texture_stage != (TextureStage *)NULL) { if (glob.matches(texture_stage->get_name())) { return texture_stage; } } } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); CPT(RenderState) next_state = state->compose(child->get_state()); TextureStage *result = r_find_texture_stage(child, next_state, glob); if (result != (TextureStage *)NULL) { return result; } } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_all_texture_stages // Access: Private // Description: //////////////////////////////////////////////////////////////////// void NodePath:: r_find_all_texture_stages(PandaNode *node, const RenderState *state, NodePath::TextureStages &texture_stages) const { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_V(gnode, node); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) geom_state = state->compose(gnode->get_geom_state(i)); // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { TextureStage *texture_stage = ta->get_on_stage(i); if (texture_stage != (TextureStage *)NULL) { texture_stages.insert(texture_stage); } } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); CPT(RenderState) next_state = state->compose(child->get_state()); r_find_all_texture_stages(child, next_state, texture_stages); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_unify_texture_stages // Access: Private // Description: //////////////////////////////////////////////////////////////////// void NodePath:: r_unify_texture_stages(PandaNode *node, TextureStage *stage) { // Look for a TextureAttrib on the state. const RenderAttrib *attrib = node->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); CPT(RenderAttrib) new_attrib = ta->unify_texture_stages(stage); if (new_attrib != ta) { node->set_attrib(new_attrib); } } if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_V(gnode, node); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) state = gnode->get_geom_state(i); // Look for a TextureAttrib on the state. const RenderAttrib *attrib = state->get_attrib(TextureAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); CPT(RenderAttrib) new_attrib = ta->unify_texture_stages(stage); if (new_attrib != ta) { CPT(RenderState) new_state = state->add_attrib(new_attrib); gnode->set_geom_state(i, new_state); } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); r_unify_texture_stages(child, stage); } } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_material // Access: Private // Description: //////////////////////////////////////////////////////////////////// Material *NodePath:: r_find_material(PandaNode *node, const RenderState *state, const GlobPattern &glob) const { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_R(gnode, node, NULL); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) geom_state = state->compose(gnode->get_geom_state(i)); // Look for a MaterialAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(MaterialAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const MaterialAttrib *ta = DCAST(MaterialAttrib, attrib); if (!ta->is_off()) { Material *material = ta->get_material(); if (material != (Material *)NULL) { if (glob.matches(material->get_name())) { return material; } } } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); CPT(RenderState) next_state = state->compose(child->get_state()); Material *result = r_find_material(child, next_state, glob); if (result != (Material *)NULL) { return result; } } return NULL; } //////////////////////////////////////////////////////////////////// // Function: NodePath::r_find_all_materials // Access: Private // Description: //////////////////////////////////////////////////////////////////// void NodePath:: r_find_all_materials(PandaNode *node, const RenderState *state, NodePath::Materials &materials) const { if (node->is_geom_node()) { GeomNode *gnode; DCAST_INTO_V(gnode, node); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { CPT(RenderState) geom_state = state->compose(gnode->get_geom_state(i)); // Look for a MaterialAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(MaterialAttrib::get_class_slot()); if (attrib != (const RenderAttrib *)NULL) { const MaterialAttrib *ta = DCAST(MaterialAttrib, attrib); if (!ta->is_off()) { Material *material = ta->get_material(); if (material != (Material *)NULL) { materials.insert(material); } } } } } // Now consider children. PandaNode::Children cr = node->get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { PandaNode *child = cr.get_child(i); CPT(RenderState) next_state = state->compose(child->get_state()); r_find_all_materials(child, next_state, materials); } }
38.555084
278
0.569225
kestred
20a36919a2849dc05936f9aedecf1dcbee09ae40
2,536
cc
C++
test/integration/kinetic_energy_monitor_system.cc
jasmeet0915/ign-gazebo
fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2
[ "ECL-2.0", "Apache-2.0" ]
198
2020-04-15T16:56:09.000Z
2022-03-27T12:31:08.000Z
test/integration/kinetic_energy_monitor_system.cc
jasmeet0915/ign-gazebo
fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2
[ "ECL-2.0", "Apache-2.0" ]
1,220
2020-04-15T18:10:29.000Z
2022-03-31T22:37:06.000Z
test/integration/kinetic_energy_monitor_system.cc
jasmeet0915/ign-gazebo
fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2
[ "ECL-2.0", "Apache-2.0" ]
134
2020-04-15T16:59:57.000Z
2022-03-26T08:51:31.000Z
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <gtest/gtest.h> #include <ignition/msgs/double.pb.h> #include <mutex> #include <ignition/common/Console.hh> #include <ignition/common/Util.hh> #include <ignition/math/Pose3.hh> #include <ignition/transport/Node.hh> #include "ignition/gazebo/Server.hh" #include "ignition/gazebo/SystemLoader.hh" #include "ignition/gazebo/test_config.hh" #include "../helpers/EnvTestFixture.hh" using namespace ignition; using namespace gazebo; /// \brief Test Kinetic Energy Monitor system class KineticEnergyMonitorTest : public InternalFixture<::testing::Test> { }; std::mutex mutex; std::vector<msgs::Double> dblMsgs; ///////////////////////////////////////////////// void cb(const msgs::Double &_msg) { mutex.lock(); dblMsgs.push_back(_msg); mutex.unlock(); } ///////////////////////////////////////////////// // The test checks the world pose and sensor readings of a falling altimeter TEST_F(KineticEnergyMonitorTest, ModelFalling) { // Start server ServerConfig serverConfig; const auto sdfFile = std::string(PROJECT_SOURCE_PATH) + "/test/worlds/altimeter.sdf"; serverConfig.SetSdfFile(sdfFile); Server server(serverConfig); EXPECT_FALSE(server.Running()); EXPECT_FALSE(*server.Running(0)); const std::string sensorName = "altimeter_sensor"; // subscribe to kinetic energy topic std::string topic = "/model/altimeter_model/kinetic_energy"; transport::Node node; node.Subscribe(topic, &cb); // Run server size_t iters = 1000u; server.Run(true, iters, false); // Wait for messages to be received for (int sleep = 0; sleep < 30; ++sleep) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); mutex.lock(); bool received = dblMsgs.size() > 0; mutex.unlock(); if (received) break; } mutex.lock(); EXPECT_EQ(1u, dblMsgs.size()); auto firstMsg = dblMsgs.front(); mutex.unlock(); EXPECT_GT(firstMsg.data(), 2); }
26.416667
76
0.69164
jasmeet0915
20a383dc150347f4a66ce92e9e3607015dc031dd
10,264
cpp
C++
src/game/server/hl2/grenade_tripwire.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/server/hl2/grenade_tripwire.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/server/hl2/grenade_tripwire.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Implements the tripmine grenade. // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "util.h" #include "shake.h" #include "grenade_tripwire.h" #include "grenade_homer.h" #include "rope.h" #include "rope_shared.h" #include "engine/IEngineSound.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar sk_dmg_tripwire ( "sk_dmg_tripwire","0"); ConVar sk_tripwire_radius ( "sk_tripwire_radius","0"); #define GRENADETRIPWIRE_MISSILEMDL "models/Weapons/ar2_grenade.mdl" #define TGRENADE_LAUNCH_VEL 1200 #define TGRENADE_SPIN_MAG 50 #define TGRENADE_SPIN_SPEED 100 #define TGRENADE_MISSILE_OFFSET 50 #define TGRENADE_MAX_ROPE_LEN 1500 LINK_ENTITY_TO_CLASS( npc_tripwire, CTripwireGrenade ); BEGIN_DATADESC( CTripwireGrenade ) DEFINE_FIELD( m_flPowerUp, FIELD_TIME ), DEFINE_FIELD( m_nMissileCount, FIELD_INTEGER ), DEFINE_FIELD( m_vecDir, FIELD_VECTOR ), DEFINE_FIELD( m_vTargetPos, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vTargetOffset, FIELD_VECTOR ), DEFINE_FIELD( m_pRope, FIELD_CLASSPTR ), DEFINE_FIELD( m_pHook, FIELD_CLASSPTR ), // Function Pointers DEFINE_FUNCTION( WarningThink ), DEFINE_FUNCTION( PowerupThink ), DEFINE_FUNCTION( RopeBreakThink ), DEFINE_FUNCTION( FireThink ), END_DATADESC() CTripwireGrenade::CTripwireGrenade() { m_vecDir.Init(); } void CTripwireGrenade::Spawn( void ) { Precache( ); SetMoveType( MOVETYPE_FLY ); SetSolid( SOLID_BBOX ); AddSolidFlags( FSOLID_NOT_SOLID ); SetModel( "models/Weapons/w_slam.mdl" ); m_nMissileCount = 0; UTIL_SetSize(this, Vector( -4, -4, -2), Vector(4, 4, 2)); m_flPowerUp = gpGlobals->curtime + 1.2;//<<CHECK>>get rid of this SetThink( WarningThink ); SetNextThink( gpGlobals->curtime + 1.0f ); m_takedamage = DAMAGE_YES; m_iHealth = 1; m_pRope = NULL; m_pHook = NULL; // Tripwire grenade sits at 90 on wall so rotate back to get m_vecDir QAngle angles = GetLocalAngles(); angles.x -= 90; AngleVectors( angles, &m_vecDir ); } void CTripwireGrenade::Precache( void ) { PrecacheModel("models/Weapons/w_slam.mdl"); PrecacheModel(GRENADETRIPWIRE_MISSILEMDL); } void CTripwireGrenade::WarningThink( void ) { // play activate sound EmitSound( "TripwireGrenade.Activate" ); // set to power up SetThink( PowerupThink ); SetNextThink( gpGlobals->curtime + 1.0f ); } void CTripwireGrenade::PowerupThink( void ) { if (gpGlobals->curtime > m_flPowerUp) { MakeRope( ); RemoveSolidFlags( FSOLID_NOT_SOLID ); m_bIsLive = true; } SetNextThink( gpGlobals->curtime + 0.1f ); } void CTripwireGrenade::BreakRope( void ) { if (m_pRope) { m_pRope->m_RopeFlags |= ROPE_COLLIDE; m_pRope->DetachPoint(0); Vector vVelocity; m_pHook->GetVelocity( &vVelocity, NULL ); if (vVelocity.Length() > 1) { m_pRope->DetachPoint(1); } } } void CTripwireGrenade::MakeRope( void ) { SetThink( RopeBreakThink ); // Delay first think slightly so rope has time // to appear if person right in front of it SetNextThink( gpGlobals->curtime + 1.0f ); // Create hook for end of tripwire m_pHook = (CTripwireHook*)CBaseEntity::Create( "tripwire_hook", GetLocalOrigin(), GetLocalAngles() ); if (m_pHook) { Vector vShootVel = 800*(m_vecDir + Vector(0,0,0.3)+RandomVector(-0.01,0.01)); m_pHook->SetVelocity( vShootVel, vec3_origin); m_pHook->SetOwnerEntity( this ); m_pHook->m_hGrenade = this; m_pRope = CRopeKeyframe::Create(this,m_pHook,0,0); if (m_pRope) { m_pRope->m_Width = 1; m_pRope->m_RopeLength = 3; m_pRope->m_Slack = 100; CPASAttenuationFilter filter( this,"TripwireGrenade.ShootRope" ); EmitSound( filter, entindex(),"TripwireGrenade.ShootRope" ); } } } void CTripwireGrenade::Attach( void ) { StopSound( "TripwireGrenade.ShootRope" ); } void CTripwireGrenade::RopeBreakThink( void ) { // See if I can go solid yet (has dropper moved out of way?) if (IsSolidFlagSet(FSOLID_NOT_SOLID)) { trace_t tr; Vector vUpBit = GetAbsOrigin(); vUpBit.z += 5.0; UTIL_TraceEntity( this, GetAbsOrigin(), vUpBit, MASK_SHOT, &tr ); if ( !tr.startsolid && (tr.fraction == 1.0) ) { RemoveSolidFlags( FSOLID_NOT_SOLID ); } } // Check if rope had gotten beyond it's max length float flRopeLength = (GetAbsOrigin()-m_pHook->GetAbsOrigin()).Length(); if (flRopeLength > TGRENADE_MAX_ROPE_LEN) { // Shoot missiles at hook m_iHealth = 0; BreakRope(); m_vTargetPos = m_pHook->GetAbsOrigin(); CrossProduct ( m_vecDir, Vector(0,0,1), m_vTargetOffset ); m_vTargetOffset *=TGRENADE_MISSILE_OFFSET; SetThink(FireThink); FireThink(); } // Check to see if can see hook // NOT MASK_SHOT because we want only simple hit boxes trace_t tr; UTIL_TraceLine( GetAbsOrigin(), m_pHook->GetAbsOrigin(), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr ); // If can't see hook CBaseEntity *pEntity = tr.m_pEnt; if (tr.fraction != 1.0 && pEntity != m_pHook) { // Shoot missiles at place where rope was intersected m_iHealth = 0; BreakRope(); m_vTargetPos = tr.endpos; CrossProduct ( m_vecDir, Vector(0,0,1), m_vTargetOffset ); m_vTargetOffset *=TGRENADE_MISSILE_OFFSET; SetThink(FireThink); FireThink(); return; } SetNextThink( gpGlobals->curtime + 0.1f ); } //------------------------------------------------------------------------------ // Purpose : Die if I take any damage // Input : // Output : //------------------------------------------------------------------------------ int CTripwireGrenade::OnTakeDamage_Alive( const CTakeDamageInfo &info ) { // Killed upon any damage Event_Killed( info ); return 0; } //----------------------------------------------------------------------------- // Purpose: If someone damaged, me shoot of my missiles and die // Input : // Output : //----------------------------------------------------------------------------- void CTripwireGrenade::Event_Killed( const CTakeDamageInfo &info ) { if (m_iHealth > 0) { // Fire missiles and blow up for (int i=0;i<6;i++) { Vector vTargetPos = GetAbsOrigin() + RandomVector(-600,600); FireMissile(vTargetPos); } BreakRope(); UTIL_Remove(this); } } //------------------------------------------------------------------------------ // Purpose : Fire a missile at the target position // Input : // Output : //------------------------------------------------------------------------------ void CTripwireGrenade::FireMissile(const Vector &vTargetPos) { Vector vTargetDir = (vTargetPos - GetAbsOrigin()); VectorNormalize(vTargetDir); float flGravity = 0.0001; // No gravity on the missiles bool bSmokeTrail = true; float flHomingSpeed = 0; Vector vLaunchVelocity = TGRENADE_LAUNCH_VEL*vTargetDir; float flSpinMagnitude = TGRENADE_SPIN_MAG; float flSpinSpeed = TGRENADE_SPIN_SPEED; //<<CHECK>> hold in string_t CGrenadeHomer *pGrenade = CGrenadeHomer::CreateGrenadeHomer( MAKE_STRING(GRENADETRIPWIRE_MISSILEMDL), MAKE_STRING("TripwireGrenade.FlySound"), GetAbsOrigin(), vec3_angle, edict() ); pGrenade->Spawn( ); pGrenade->SetSpin(flSpinMagnitude,flSpinSpeed); pGrenade->SetHoming(0,0,0,0,0); pGrenade->SetDamage(sk_dmg_tripwire.GetFloat()); pGrenade->SetDamageRadius(sk_tripwire_radius.GetFloat()); pGrenade->Launch(this,NULL,vLaunchVelocity,flHomingSpeed,flGravity,bSmokeTrail); // Calculate travel time float flTargetDist = (GetAbsOrigin() - vTargetPos).Length(); pGrenade->m_flDetonateTime = gpGlobals->curtime + flTargetDist/TGRENADE_LAUNCH_VEL; } //------------------------------------------------------------------------------ // Purpose : Shoot off a series of missiles over time, then go intert // Input : // Output : //------------------------------------------------------------------------------ void CTripwireGrenade::FireThink() { SetNextThink( gpGlobals->curtime + 0.16f ); Vector vTargetPos = m_vTargetPos + (m_vTargetOffset * m_nMissileCount); FireMissile(vTargetPos); vTargetPos = m_vTargetPos - (m_vTargetOffset * m_nMissileCount); FireMissile(vTargetPos); m_nMissileCount++; if (m_nMissileCount > 4) { m_iHealth = -1; SetThink( NULL ); } } // #################################################################### // CTripwireHook // // This is what the tripwire shoots out at the end of the rope // #################################################################### LINK_ENTITY_TO_CLASS( tripwire_hook, CTripwireHook ); //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CTripwireHook ) DEFINE_FIELD( m_hGrenade, FIELD_EHANDLE ), DEFINE_FIELD( m_bAttached, FIELD_BOOLEAN ), END_DATADESC() void CTripwireHook::Spawn( void ) { Precache( ); SetModel( "models/Weapons/w_grenade.mdl" );//<<CHECK>> UTIL_SetSize(this, Vector( -1, -1, -1), Vector(1,1, 1)); m_takedamage = DAMAGE_NO; m_bAttached = false; CreateVPhysics(); } bool CTripwireHook::CreateVPhysics() { // Create the object in the physics system IPhysicsObject *pPhysicsObject = VPhysicsInitNormal( SOLID_BBOX, 0, false ); // Make sure I get touch called for static geometry if ( pPhysicsObject ) { int flags = pPhysicsObject->GetCallbackFlags(); flags |= CALLBACK_GLOBAL_TOUCH_STATIC; pPhysicsObject->SetCallbackFlags(flags); } return true; } void CTripwireHook::Precache( void ) { PrecacheModel("models/Weapons/w_grenade.mdl"); //<<CHECK>> } void CTripwireHook::EndTouch( CBaseEntity *pOther ) { //<<CHECK>>do instead by clearing touch function if (!m_bAttached) { m_bAttached = true; SetVelocity(vec3_origin, vec3_origin); SetMoveType( MOVETYPE_NONE ); EmitSound( "TripwireGrenade.Hook" ); // Let the tripwire grenade know that I've attached CTripwireGrenade* pGrenade = dynamic_cast<CTripwireGrenade*>((CBaseEntity*)m_hGrenade); if (pGrenade) { pGrenade->Attach(); } } } void CTripwireHook::SetVelocity( const Vector &velocity, const AngularImpulse &angVelocity ) { IPhysicsObject *pPhysicsObject = VPhysicsGetObject(); if ( pPhysicsObject ) { pPhysicsObject->AddVelocity( &velocity, &angVelocity ); } }
25.853904
183
0.651598
cstom4994
20a40fd50aeafde781c16d3638f6dae9fc9ff34d
2,219
cpp
C++
server/SchiffeVersenkenServer/Buffer.cpp
chronoB/VoIP-Framework
5a253dd665019e2f2acdd62fed11756cd7125286
[ "MIT" ]
null
null
null
server/SchiffeVersenkenServer/Buffer.cpp
chronoB/VoIP-Framework
5a253dd665019e2f2acdd62fed11756cd7125286
[ "MIT" ]
null
null
null
server/SchiffeVersenkenServer/Buffer.cpp
chronoB/VoIP-Framework
5a253dd665019e2f2acdd62fed11756cd7125286
[ "MIT" ]
null
null
null
/* This file is part of the project "Schiffe-Versenken" a Voice-over-IP chat with disturbance algorithms. This software package was developed as a practical project in the 6th semester at the TGM (@Jade-Hochschule) This project is released under the terms of the MIT-License. For license details see the License file. Copyright <c> 2016 Finn Bayer (finn.bayer@gmx.de) Michael Schaffert (pieter.michael.schaffert@googlemail.com) Nils L. Westhausen (n.westhausen@web.de) */ #include "Buffer.h" /* counstructor lengthOfBuffer -> number of blocks that can be saved in the buffer*/ Buffer::Buffer(int lengthOfBuffer) { length = lengthOfBuffer; buf = new float[length*FRAMES_PER_BUFFER]; status = BUFFEREMPTY; readPtr = 0; count = 0; writePtr = 0; } /* Destructor*/ Buffer::~Buffer(void) { delete[] buf; } /* Function to return the status of the Buffer Returns: BUFFERFULL -> if its full BUFFEREMPTY -> if its empty 0 -> if everythings ok*/ int Buffer::getStatus(void) { return status; } /* Function to retrieve the block from the buffer *outputBlock-> pointer to an array where the data should be stored*/ int Buffer::getBlock(float* outputBlock) { if (status != BUFFEREMPTY) { for (int i = 0; i < FRAMES_PER_BUFFER; i++) { outputBlock[i] = buf[readPtr]; readPtr = (readPtr + 1) % (length*FRAMES_PER_BUFFER); } count--; if (count <= 0) { status = BUFFEREMPTY; } else status = 0; return 0; } else { return -1; } } /* Function to store a block of samples in the buffer *inputBlock -> pointer to an array that should be stored to the buffer*/ int Buffer::setBlock(float* inputBlock) { if (status != BUFFERFULL) { for (int i = 0; i < FRAMES_PER_BUFFER; i++) { buf[writePtr] = inputBlock[i]; writePtr = (writePtr + 1) % (this->length*FRAMES_PER_BUFFER); } count++; if (count >= length) { status = BUFFERFULL; } else status = 0; return 0; } else { return -1; } } /* Function to return the current number of blocks stored in the buffer*/ int Buffer::getCount(void) { return count; } /* Function to clear the Buffer*/ int Buffer::clearBuffer(void) { readPtr = writePtr = count = 0; status = BUFFEREMPTY; return 0; }
18.805085
108
0.683641
chronoB
20a421a21adb494f67bfd0333cb69b1258419f2e
210
cpp
C++
2014/Communications/car-wire/slave_car_wire.cpp
WE-Bots/project-car-archive
388fabc6e6c0cdde76a91d8277e29d29f01c5087
[ "MIT" ]
null
null
null
2014/Communications/car-wire/slave_car_wire.cpp
WE-Bots/project-car-archive
388fabc6e6c0cdde76a91d8277e29d29f01c5087
[ "MIT" ]
null
null
null
2014/Communications/car-wire/slave_car_wire.cpp
WE-Bots/project-car-archive
388fabc6e6c0cdde76a91d8277e29d29f01c5087
[ "MIT" ]
1
2018-08-15T14:30:54.000Z
2018-08-15T14:30:54.000Z
#include "slave_car_wire.h" void slave_car_wire::receiveEvent(){ if (Wire.available()){} _cmd = Wire.readByte(); } } void slave_car_wire::requestEvent(){ //You kinda need to write this one yourself }
14
44
0.7
WE-Bots
20a626f8336273447e6fe5faa3a0fb2513d6251c
55
hpp
C++
addons/admin/functions/script_component.hpp
ARCOMMADMIN/ARCORE
5d8a632017abb646e6f01aa3eebf6c0747028213
[ "MIT" ]
1
2018-02-15T07:43:55.000Z
2018-02-15T07:43:55.000Z
addons/admin/functions/script_component.hpp
ARCOMMADMIN/ARCORE
5d8a632017abb646e6f01aa3eebf6c0747028213
[ "MIT" ]
36
2017-07-08T21:25:36.000Z
2020-05-03T18:59:23.000Z
addons/admin/functions/script_component.hpp
ARCOMMADMIN/ARCORE
5d8a632017abb646e6f01aa3eebf6c0747028213
[ "MIT" ]
4
2019-08-01T00:19:01.000Z
2020-05-07T20:40:38.000Z
#include "\z\arcore\addons\admin\script_component.hpp"
27.5
54
0.8
ARCOMMADMIN
20a87caf8f6c132cf5237aa225734403bf7d678b
286
cpp
C++
test_ext_core.cpp
tz-lom/thir
c85482f9fe6f7ecdfd9db6960f8e8277b3fe3979
[ "MIT" ]
null
null
null
test_ext_core.cpp
tz-lom/thir
c85482f9fe6f7ecdfd9db6960f8e8277b3fe3979
[ "MIT" ]
null
null
null
test_ext_core.cpp
tz-lom/thir
c85482f9fe6f7ecdfd9db6960f8e8277b3fe3979
[ "MIT" ]
null
null
null
#include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/stringize.hpp> #include BOOST_PP_STRINGIZE(BOOST_PP_CAT(BOOST_PP_CAT(test_ext_, THIR_TEST_EXTENSION), _.h)) int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
26
92
0.751748
tz-lom
20a8d17dbb8eb529256e1e9c377f8c032ecc34bf
280
hpp
C++
src/Elba/Graphics/GraphicsForwardDeclarations.hpp
nicholasammann/kotor-builder
ab0e042c09974a024a9884c6f9e34cf85ad63eeb
[ "MIT" ]
1
2018-10-01T19:34:57.000Z
2018-10-01T19:34:57.000Z
src/Elba/Graphics/GraphicsForwardDeclarations.hpp
nicholasammann/kotor-builder
ab0e042c09974a024a9884c6f9e34cf85ad63eeb
[ "MIT" ]
9
2018-09-09T16:07:22.000Z
2018-11-06T20:34:30.000Z
src/Elba/Graphics/GraphicsForwardDeclarations.hpp
nicholasammann/kotor-builder
ab0e042c09974a024a9884c6f9e34cf85ad63eeb
[ "MIT" ]
null
null
null
/** * \file GraphicsForwardDeclarations.hpp * \author Nicholas Ammann * \date 2/24/2018 * \brief Forward declarations for all graphics classes. */ #pragma once namespace Elba { class GraphicsModule; class GraphicsFactory; class Mesh; class Submesh; } // End of Elba namespace
14.736842
55
0.753571
nicholasammann
20a9fe709a650a0488eabb4e8d111ad85844a408
923
cpp
C++
codeforces/1480/A.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
codeforces/1480/A.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
codeforces/1480/A.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define inf INT_MAX #define int long long #define ump unordered_map #define endl "\n" #define mod 1000000007 void OJ() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } void lego() { string s; cin >> s; int n = s.length(); int turn = 1; for (int i = 0; i < n; i++) { if (turn) { if (s[i] == 'a') { cout << 'b'; } else { cout << 'a'; } } else { if (s[i] == 'z') { cout << 'y'; } else { cout << 'z'; } } turn = !turn; } cout << endl; } signed main() { OJ(); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tt = 1; if (true) cin >> tt; while (tt--) lego(); return 0; }
17.75
39
0.422535
gnomegeek
20ad9d60b5312298599d58361616d05d28bb3cfc
8,143
cpp
C++
Gizmo/Sysex.cpp
eclab/gizmo
4c429486c7231f6f8fbf708b03f8e23c76af5019
[ "Apache-2.0" ]
61
2016-11-21T08:43:45.000Z
2022-03-12T13:34:01.000Z
Gizmo/Sysex.cpp
eclab/gizmo
4c429486c7231f6f8fbf708b03f8e23c76af5019
[ "Apache-2.0" ]
7
2017-07-17T14:10:45.000Z
2022-01-26T05:16:29.000Z
Gizmo/Sysex.cpp
eclab/gizmo
4c429486c7231f6f8fbf708b03f8e23c76af5019
[ "Apache-2.0" ]
7
2019-08-22T19:05:41.000Z
2021-08-20T18:31:05.000Z
////// Copyright 2020 by Sean Luke ////// Licensed under the Apache 2.0 License #include "All.h" #ifdef INCLUDE_SYSEX void loadHeader(uint8_t bytes[]) { bytes[0] = 0xF0; bytes[1] = 0x7D; bytes[2] = 'G'; bytes[3] = 'I'; bytes[4] = 'Z'; bytes[5] = 'M'; bytes[6] = 'O'; bytes[7] = SYSEX_VERSION; } void sendSlotSysex() { loadSlot(local.sysex.slot); // Our format is: // 0xF0 // 0x7D [Private, Test, Educational Use] // G I Z M O // Version number [Currently 0] // Sysex Type [ 0 = slot, 1 = Arp] // Nybblized Data, high nybble first // checksum, just sum of data // 0xF7 uint8_t bytes[sizeof(struct _slot) * 2 + 11]; loadHeader(bytes); bytes[8] = SYSEX_TYPE_SLOT; uint8_t sum = 0; for(uint16_t i = 0; i < sizeof(struct _slot); i++) { bytes[9 + i * 2] = (uint8_t)((data.bytes[i] >> 4) & 0xF); // unsigned char right shifts are probably logical shifts, but we mask anyway bytes[9 + i * 2 + 1] = (uint8_t)(data.bytes[i] & 0xF); sum += bytes[9 + i * 2]; sum += bytes[9 + i * 2 + 1]; /* if (data.bytes[i] != ((uint8_t)(bytes[9 + i * 2] << 4) | (bytes[9 + i * 2 + 1] & 0xF))) debug(999); */ } bytes[sizeof(struct _slot) * 2 + 11 - 2] = (sum & 127); bytes[sizeof(struct _slot) * 2 + 11 - 1] = 0xF7; MIDI.sendSysEx(sizeof(struct _slot) * 2 + 11, bytes, true); } void sendArpSysex() { LOAD_ARPEGGIO(local.sysex.slot); // Our format is: // 0xF0 // 0x7D [Private, Test, Educational Use] // G I Z M O // Version number [Currently 0] // Sysex Type [ 0 = slot, 1 = Arp] // Nybblized Data, high nybble first // checksum, just sum of data // 0xF7 uint8_t bytes[sizeof(struct _arp) * 2 + 11]; loadHeader(bytes); bytes[8] = SYSEX_TYPE_ARP; uint8_t sum = 0; for(uint16_t i = 0; i < sizeof(struct _arp); i++) { bytes[9 + i * 2] = (uint8_t)((data.bytes[i] >> 4) & 0xF); // unsigned char right shifts are probably logical shifts, but we mask anyway bytes[9 + i * 2 + 1] = (uint8_t)(data.bytes[i] & 0xF); sum += bytes[9 + i * 2]; sum += bytes[9 + i * 2 + 1]; } bytes[sizeof(struct _arp) * 2 + 11 - 2] = (sum & 127); bytes[sizeof(struct _arp) * 2 + 11 - 1] = 0xF7; MIDI.sendSysEx(sizeof(struct _arp) * 2 + 11, bytes, true); } uint8_t receiveSlotSysex(unsigned char* bytes) { // verify checksum uint8_t sum = 0; for(uint16_t i = 0; i < sizeof(struct _slot); i++) { sum += bytes[9 + i * 2]; sum += bytes[9 + i * 2 + 1]; } if ((sum & 127) != bytes[sizeof(struct _slot) * 2 + 11 - 2]) // second to last return false; // load for(uint16_t i = 0; i < sizeof(struct _slot); i++) { data.bytes[i] = (uint8_t)(bytes[9 + i * 2] << 4) | (bytes[9 + i * 2 + 1] & 0xF); } saveSlot(local.sysex.slot); return true; } uint8_t receiveArpSysex(unsigned char* bytes) { // verify checksum uint8_t sum = 0; for(uint16_t i = 0; i < sizeof(struct _arp); i++) { sum += bytes[9 + i * 2]; sum += bytes[9 + i * 2 + 1]; } if ((sum & 127) != bytes[sizeof(struct _arp) * 2 + 11 - 2]) // second to last return false; // load for(uint16_t i = 0; i < sizeof(struct _arp); i++) { data.bytes[i] = (uint8_t)(bytes[9 + i * 2] << 4) | (bytes[9 + i * 2 + 1] & 0xF); } SAVE_ARPEGGIO(local.sysex.slot); return true; } void handleSysex(unsigned char* bytes, int len) { // We only process incoming sysex *at all*, even if to generate an error message, if we're // in STATE_SYSEX_GO. if (state != STATE_SYSEX_GO) return; // Our format is: // 0xF0 // 0x7D [Private, Test, Educational Use] // G I Z M O // Version number [Currently 0] // Sysex Type [ 0 = slot, 1 = Arp] // Nybblized Data, high nybble first // checksum, just sum of data // 0xF7 if (bytes[1] == 0x7D && bytes[2] == 'G' && bytes[3] == 'I' && bytes[4] == 'Z' && bytes[5] == 'M' && bytes[6] == 'O' && bytes[7] == SYSEX_VERSION) // it's me { if (local.sysex.type == SYSEX_TYPE_SLOT && bytes[8] == SYSEX_TYPE_SLOT) { if (len != sizeof(struct _slot) * 2 + 11 || !receiveSlotSysex(bytes)) { local.sysex.received = RECEIVED_BAD; } else { local.sysex.received++; if (local.sysex.received <= 0) // previous was BAD or WRONG, or we wrapped around local.sysex.received = 1; } } else if (local.sysex.type == SYSEX_TYPE_ARP && bytes[8] == SYSEX_TYPE_ARP) { if (len != sizeof(struct _arp) * 2 + 11 | !receiveArpSysex(bytes)) { local.sysex.received = RECEIVED_BAD; } else { local.sysex.received++; if (local.sysex.received <= 0) // previous was BAD or WRONG, or we wrapped around local.sysex.received = 1; } } else { local.sysex.received = RECEIVED_WRONG; // we're not the right type (slot vs. arp) to receive } } else { local.sysex.received = RECEIVED_BAD; } } void stateSysexSlot() { local.sysex.type = SYSEX_TYPE_SLOT; // make sure that we're reset properly local.sysex.received = RECEIVED_NONE; uint8_t result = doNumericalDisplay(0, NUM_SLOTS - 1, 1, false, GLYPH_NONE); switch (result) { case NO_MENU_SELECTED: break; case MENU_SELECTED: local.sysex.slot = currentDisplay; goDownState(STATE_SYSEX_GO); break; case MENU_CANCELLED: goUpState(STATE_SYSEX); break; } } void stateSysexArp() { local.sysex.type = SYSEX_TYPE_ARP; // make sure that we're reset properly local.sysex.received = RECEIVED_NONE; uint8_t result = doNumericalDisplay(0, NUM_ARPS - 1, 1, false, GLYPH_NONE); switch (result) { case NO_MENU_SELECTED: break; case MENU_SELECTED: local.sysex.slot = currentDisplay; goDownState(STATE_SYSEX_GO); break; case MENU_CANCELLED: goUpState(STATE_SYSEX); break; } } void stateSysexGo() { // display if (local.sysex.received == RECEIVED_NONE) { clearScreen(); // is this necessary? write3x5Glyphs(GLYPH_OFF); } else if (local.sysex.received == RECEIVED_WRONG) { clearScreen(); // is this necessary? write3x5Glyphs(GLYPH_SYSEX); } else if (local.sysex.received == RECEIVED_BAD) { clearScreen(); // is this necessary? write3x5Glyphs(GLYPH_FAIL); } else { clearScreen(); writeShortNumber(led, ((uint8_t)local.sysex.received), false); } // handle buttons if (isUpdated(BACK_BUTTON, RELEASED)) { goUpState(local.sysex.type == SYSEX_TYPE_SLOT ? STATE_SYSEX_SLOT : STATE_SYSEX_ARP); } else if (isUpdated(SELECT_BUTTON, PRESSED)) { if (local.sysex.type == SYSEX_TYPE_SLOT) { sendSlotSysex(); } else { sendArpSysex(); } local.sysex.received++; if (local.sysex.received <= 0) // previous was BAD or WRONG, or we wrapped around local.sysex.received = 1; } } #endif INCLUDE_SYSEX
29.18638
144
0.503868
eclab
20b337b691666a3934e9e24260931cf31af9cfba
75,778
cpp
C++
Code/WinApp/Render.cpp
spencerparkin/GAVisTool
fb61a1789d58aedce4dbb5a53b181fbc06172a2a
[ "MIT" ]
null
null
null
Code/WinApp/Render.cpp
spencerparkin/GAVisTool
fb61a1789d58aedce4dbb5a53b181fbc06172a2a
[ "MIT" ]
null
null
null
Code/WinApp/Render.cpp
spencerparkin/GAVisTool
fb61a1789d58aedce4dbb5a53b181fbc06172a2a
[ "MIT" ]
null
null
null
// Render.cpp /* * Copyright (C) 2013-2014 Spencer T. Parkin * * This software has been released under the MIT License. * See the "License.txt" file in the project root directory * for more information about this license. * */ #include "Render.h" #include "Application.h" #include "wxAll.h" // TODO: Use the VectorMath::ProgressInterface while building the BSP tree. //============================================================================= GAVisToolRender::GAVisToolRender( void ) : selectionPrimitiveCache( 1024, 1024, 128, 0 ), noAlphaBlendingPrimitiveCache( 1024 * 8, 1024 * 8, 1024 * 16, 0 ), alphaBlendingPrimitiveCache( 1024 * 64, 1024 * 16, 1024 * 16, 1024 * 16 ) { SetRenderMode( RENDER_MODE_NO_ALPHA_SORTING ); userResolution = RES_MEDIUM; shading = SHADE_SMOOTH; draw3DVectors = false; doLighting = true; showBspDetail = false; bspTreeCreationMethod = RANDOM_TRIANGLE_INSERTION; currentHighlightMethod = NO_HIGHLIGHTING; for( int index = 0; index < NUM_RES_TYPES; index++ ) { tubeGeometry[ index ] = 0; sphereGeometry[ index ] = 0; torusGeometry[ index ] = 0; diskGeometry[ index ] = 0; vectorGeometry[ index ] = 0; } } //============================================================================= /*virtual*/ GAVisToolRender::~GAVisToolRender( void ) { for( int index = 0; index < NUM_RES_TYPES; index++ ) { if( tubeGeometry[ index ] ) delete tubeGeometry[ index ]; if( sphereGeometry[ index ] ) delete sphereGeometry[ index ]; if( torusGeometry[ index ] ) delete torusGeometry[ index ]; if( diskGeometry[ index ] ) delete diskGeometry[ index ]; if( vectorGeometry[ index ] ) delete vectorGeometry[ index ]; } } //============================================================================= bool GAVisToolRender::ShowBspDetail( void ) { return showBspDetail; } //============================================================================= void GAVisToolRender::ShowBspDetail( bool showBspDetail ) { this->showBspDetail = showBspDetail; } //============================================================================= void GAVisToolRender::SetRenderMode( RenderMode renderMode ) { this->renderMode = renderMode; switch( renderMode ) { case RENDER_MODE_SELECTION: { activePrimitiveCache = &selectionPrimitiveCache; break; } case RENDER_MODE_NO_ALPHA_SORTING: { activePrimitiveCache = &noAlphaBlendingPrimitiveCache; break; } case RENDER_MODE_ALPHA_SORTING: { activePrimitiveCache = &alphaBlendingPrimitiveCache; break; } default: { activePrimitiveCache = 0; break; } } } //============================================================================= GAVisToolRender::RenderMode GAVisToolRender::GetRenderMode( void ) { return renderMode; } //============================================================================= void GAVisToolRender::SetGeometryMode( GeometryMode geometryMode ) { this->geometryMode = geometryMode; } //============================================================================= GAVisToolRender::GeometryMode GAVisToolRender::GetGeometryMode( void ) { return geometryMode; } //============================================================================= void GAVisToolRender::SetResolution( Resolution resolution ) { userResolution = resolution; } //============================================================================= GAVisToolRender::Resolution GAVisToolRender::GetResolution( void ) { return userResolution; } //============================================================================= void GAVisToolRender::SetShading( Shading shading ) { this->shading = shading; } //============================================================================= GAVisToolRender::Shading GAVisToolRender::GetShading( void ) { return shading; } //============================================================================= void GAVisToolRender::SetDraw3DVectors( bool draw3DVectors ) { this->draw3DVectors = draw3DVectors; } //============================================================================= bool GAVisToolRender::GetDraw3DVectors( void ) { return draw3DVectors; } //============================================================================= void GAVisToolRender::SetDoLighting( bool doLighting ) { this->doLighting = doLighting; } //============================================================================= bool GAVisToolRender::GetDoLighting( void ) { return doLighting; } //============================================================================= GAVisToolRender::BspTreeCreationMethod GAVisToolRender::GetBspTreeCreationMethod( void ) { return bspTreeCreationMethod; } //============================================================================= void GAVisToolRender::SetBspTreeCreationMethod( BspTreeCreationMethod bspTreeCreationMethod ) { this->bspTreeCreationMethod = bspTreeCreationMethod; } //============================================================================= void GAVisToolRender::Draw( Drawer& drawer ) { srand(0); if( doLighting ) glEnable( GL_LIGHTING ); else glDisable( GL_LIGHTING ); switch( renderMode ) { case RENDER_MODE_SELECTION: { // We want back-facing polygons to be selectable. glEnable( GL_DEPTH_TEST ); glDisable( GL_CULL_FACE ); break; } case RENDER_MODE_NO_ALPHA_SORTING: { glEnable( GL_DEPTH_TEST ); glEnable( GL_CULL_FACE ); glCullFace( GL_BACK ); glFrontFace( GL_CCW ); break; } case RENDER_MODE_ALPHA_SORTING: { glDisable( GL_CULL_FACE ); // If everything drawn was done using the BSP tree, then // we could actually turn this off. glEnable( GL_DEPTH_TEST ); break; } } // Is the cache valid? if( !activePrimitiveCache->IsValid() ) { // No, wipe and repopulate the cache. activePrimitiveCache->Wipe(); drawer.Draw( *this ); // If we're doing alpha sorting, then do it! if( renderMode == RENDER_MODE_ALPHA_SORTING ) activePrimitiveCache->OptimizeForAlphaSorting( bspTreeCreationMethod ); // The cache is now valid. activePrimitiveCache->Validate(); } // Go draw what's in the cache. activePrimitiveCache->Draw( *this ); } //============================================================================= void GAVisToolRender::InvalidatePrimitiveCache( void ) { activePrimitiveCache->Invalidate(); } //============================================================================= GAVisToolRender::PrimitiveCache::PrimitiveCache( int triangleHeapSize, int lineHeapSize, int pointHeapSize, int bspNodeHeapSize ) : triangleHeap( triangleHeapSize ), lineHeap( lineHeapSize ), pointHeap( pointHeapSize ) { if( bspNodeHeapSize > 0 ) bspTree = new BspTree( bspNodeHeapSize ); else bspTree = 0; cacheValid = false; optimizedForAlphaSorting = false; } //============================================================================= /*virtual*/ GAVisToolRender::PrimitiveCache::~PrimitiveCache( void ) { Wipe(); if( bspTree ) delete bspTree; } //============================================================================= GAVisToolRender::Triangle* GAVisToolRender::PrimitiveCache::AllocateTriangle( void ) { Triangle* triangle = triangleHeap.AllocateFresh(); if( triangle ) triangleList.InsertRightOf( triangleList.RightMost(), triangle ); return triangle; } //============================================================================= GAVisToolRender::Line* GAVisToolRender::PrimitiveCache::AllocateLine( void ) { Line* line = lineHeap.Allocate(); if( line ) lineList.InsertRightOf( lineList.RightMost(), line ); return line; } //============================================================================= GAVisToolRender::Point* GAVisToolRender::PrimitiveCache::AllocatePoint( void ) { Point* point = pointHeap.Allocate(); if( point ) pointList.InsertRightOf( pointList.RightMost(), point ); return point; } //============================================================================= void GAVisToolRender::PrimitiveCache::Draw( GAVisToolRender& render ) { // Draw the points seperately from the lines and triangles. // I'm not sure yet if I want to put them into the BSP tree. // Probably not, because they really should always be drawn // as fully opaque dots, in which case, we just draw them before // everything else anyway. if( pointList.Count() > 0 ) { glPointSize( 3.f ); VectorMath::CoordFrame cameraFrame; wxGetApp().canvasFrame->canvas->camera.CameraFrame( cameraFrame ); for( Point* point = ( Point* )pointList.LeftMost(); point; point = ( Point* )point->Right() ) point->Draw( render.GetDoLighting(), true, cameraFrame ); } // Now go draw all the lines and triangles. if( optimizedForAlphaSorting ) { const VectorMath::Vector& cameraEye = wxGetApp().canvasFrame->canvas->camera.Eye(); bspTree->Draw( cameraEye, render ); } else { for( Triangle* triangle = ( Triangle* )triangleList.LeftMost(); triangle; triangle = ( Triangle* )triangle->Right() ) triangle->Draw( render.GetShading(), render.GetDoLighting(), false ); for( Line* line = ( Line* )lineList.LeftMost(); line; line = ( Line* )line->Right() ) line->Draw( render.GetDoLighting() ); } } //============================================================================= void GAVisToolRender::PrimitiveCache::Wipe( void ) { if( bspTree ) { bspTree->Destroy(); optimizedForAlphaSorting = false; } triangleList.RemoveAll( false ); triangleHeap.FreeAll(); lineList.RemoveAll( false ); lineHeap.FreeAll(); pointList.RemoveAll( false ); pointHeap.FreeAll(); } //============================================================================= void GAVisToolRender::PrimitiveCache::Flush( GAVisToolRender& render ) { Draw( render ); Wipe(); } //============================================================================= void GAVisToolRender::PrimitiveCache::Invalidate( void ) { cacheValid = false; } //============================================================================= void GAVisToolRender::PrimitiveCache::Validate( void ) { cacheValid = true; } //============================================================================= bool GAVisToolRender::PrimitiveCache::IsValid( void ) { return cacheValid; } //============================================================================= void GAVisToolRender::PrimitiveCache::OptimizeForAlphaSorting( BspTreeCreationMethod bspTreeCreationMethod ) { if( bspTree ) { bspTree->Create( triangleList, triangleHeap, lineList, lineHeap, bspTreeCreationMethod ); optimizedForAlphaSorting = true; float triangleGrowthFactor = 1.0; if( bspTree->preBspTriangleCount > 0 ) triangleGrowthFactor = float( bspTree->postBspTriangleCount ) / float( bspTree->preBspTriangleCount ); float lineGrowthFactor = 1.0; if( bspTree->preBspLineCount > 0 ) lineGrowthFactor = float( bspTree->postBspLineCount ) / float( bspTree->preBspLineCount ); wxString bspStats = wxString::Format( #if 0 wxT( "triangles{ pre-bsp: %d, post-bsp: %d, cuts: %d, growth: %f }; " "lines{ pre-bsp: %d, post-bsp: %d, cuts %d, growth: %f }" ), #else wxT( "triangles{ pre-bsp: %d, post-bsp: %d, cuts: %d, growth: %f }; lines{ pre-bsp: %d, post-bsp: %d, cuts %d, growth: %f }" ), #endif bspTree->preBspTriangleCount, bspTree->postBspTriangleCount, bspTree->triangleSplitCount, triangleGrowthFactor, bspTree->preBspLineCount, bspTree->postBspLineCount, bspTree->lineSplitCount, lineGrowthFactor ); wxGetApp().canvasFrame->statusBar->SetStatusText( bspStats ); } } //============================================================================= GAVisToolRender::Primitive::Primitive( void ) { doubleSided = false; VectorMath::RandomVector( bspDetailColor, 0.0, 1.0 ); } //============================================================================= /*virtual*/ GAVisToolRender::Primitive::~Primitive( void ) { } //============================================================================= void GAVisToolRender::Primitive::CopyBaseData( const Primitive& primitive ) { VectorMath::Copy( color, primitive.color ); VectorMath::Copy( normal, primitive.normal ); alpha = primitive.alpha; highlightMethod = primitive.highlightMethod; doubleSided = primitive.doubleSided; } //============================================================================= GAVisToolRender::Triangle::Triangle( void ) { bspAnalysisData = 0; } //============================================================================= /*virtual*/ GAVisToolRender::Triangle::~Triangle( void ) { } //============================================================================= void GAVisToolRender::Triangle::Reset( void ) { bspAnalysisData = 0; } //============================================================================= /*virtual*/ void GAVisToolRender::Triangle::CalcCenter( VectorMath::Vector& center ) { VectorMath::CalcCenter( triangle, center ); } //============================================================================= // Per-triangle highlighting is done so that perhaps we can achieve // some more interesting effects. void GAVisToolRender::Primitive::Color( bool doLighting, bool showBspDetail ) { VectorMath::Vector finalColor; double finalAlpha; // Showing the BSP tree detail is a debugging thing. if( showBspDetail ) { VectorMath::Copy( finalColor, bspDetailColor ); finalAlpha = alpha; } else { // TODO: If something is highlighted, we could have the idle loop // continually request a redraw so that we could animate some // colors flashing here or something like that. switch( highlightMethod ) { default: case NO_HIGHLIGHTING: { VectorMath::Copy( finalColor, color ); finalAlpha = alpha; break; } case NORMAL_HIGHLIGHTING: { VectorMath::Set( finalColor, 1.0, 1.0, 1.0 ); VectorMath::Sub( finalColor, finalColor, color ); finalAlpha = alpha; break; } case SPACIAL_HIGHLIGHTING: { break; } } } GLfloat r, g, b, a; r = GLfloat( finalColor.x ); g = GLfloat( finalColor.y ); b = GLfloat( finalColor.z ); a = GLfloat( finalAlpha ); if( !doLighting ) glColor4f( r, g, b, a ); else { GLfloat diffuseColor[] = { r, g, b, a }; GLfloat specularColor[] = { 1.f, 1.f, 1.f, a }; GLfloat ambientColor[] = { r, g, b, a }; GLfloat shininess[] = { 30.f }; glMaterialfv( GL_FRONT, GL_DIFFUSE, diffuseColor ); glMaterialfv( GL_FRONT, GL_SPECULAR, specularColor ); glMaterialfv( GL_FRONT, GL_AMBIENT, ambientColor ); glMaterialfv( GL_FRONT, GL_SHININESS, shininess ); glMaterialfv( GL_BACK, GL_DIFFUSE, diffuseColor ); glMaterialfv( GL_BACK, GL_SPECULAR, specularColor ); glMaterialfv( GL_BACK, GL_AMBIENT, ambientColor ); glMaterialfv( GL_BACK, GL_SHININESS, shininess ); } } //============================================================================= void GAVisToolRender::Triangle::Draw( Shading shading, bool doLighting, bool showBspDetail ) { GLboolean cullingEnabled = glIsEnabled( GL_CULL_FACE ); bool drawCCW = true; bool drawCW = false; if( cullingEnabled ) { if( doubleSided ) drawCW = true; } else { if( doubleSided ) { VectorMath::Vector cameraLookVec; wxGetApp().canvasFrame->canvas->camera.CameraLookVec( cameraLookVec ); double dot = VectorMath::Dot( cameraLookVec, normal ); if( dot > 0.0 ) { drawCCW = false; drawCW = true; } } } glBegin( GL_TRIANGLES ); Color( doLighting, showBspDetail ); if( drawCCW ) { if( shading == SHADE_FLAT ) { glNormal3f( normal.x, normal.y, normal.z ); glVertex3f( triangle.vertex[0].x, triangle.vertex[0].y, triangle.vertex[0].z ); glVertex3f( triangle.vertex[1].x, triangle.vertex[1].y, triangle.vertex[1].z ); glVertex3f( triangle.vertex[2].x, triangle.vertex[2].y, triangle.vertex[2].z ); } else if( shading == SHADE_SMOOTH ) { glNormal3f( triangleNormals.normal[0].x, triangleNormals.normal[0].y, triangleNormals.normal[0].z ); glVertex3f( triangle.vertex[0].x, triangle.vertex[0].y, triangle.vertex[0].z ); glNormal3f( triangleNormals.normal[1].x, triangleNormals.normal[1].y, triangleNormals.normal[1].z ); glVertex3f( triangle.vertex[1].x, triangle.vertex[1].y, triangle.vertex[1].z ); glNormal3f( triangleNormals.normal[2].x, triangleNormals.normal[2].y, triangleNormals.normal[2].z ); glVertex3f( triangle.vertex[2].x, triangle.vertex[2].y, triangle.vertex[2].z ); } } if( drawCW ) { if( shading == SHADE_FLAT ) { glNormal3f( -normal.x, -normal.y, -normal.z ); glVertex3f( triangle.vertex[2].x, triangle.vertex[2].y, triangle.vertex[2].z ); glVertex3f( triangle.vertex[1].x, triangle.vertex[1].y, triangle.vertex[1].z ); glVertex3f( triangle.vertex[0].x, triangle.vertex[0].y, triangle.vertex[0].z ); } else if( shading == SHADE_SMOOTH ) { glNormal3f( -triangleNormals.normal[2].x, -triangleNormals.normal[2].y, -triangleNormals.normal[2].z ); glVertex3f( triangle.vertex[2].x, triangle.vertex[2].y, triangle.vertex[2].z ); glNormal3f( -triangleNormals.normal[1].x, -triangleNormals.normal[1].y, -triangleNormals.normal[1].z ); glVertex3f( triangle.vertex[1].x, triangle.vertex[1].y, triangle.vertex[1].z ); glNormal3f( -triangleNormals.normal[0].x, -triangleNormals.normal[0].y, -triangleNormals.normal[0].z ); glVertex3f( triangle.vertex[0].x, triangle.vertex[0].y, triangle.vertex[0].z ); } } glEnd(); } //============================================================================= GAVisToolRender::Line::Line( void ) { } //============================================================================= GAVisToolRender::Line::~Line( void ) { } //============================================================================= /*virtual*/ void GAVisToolRender::Line::CalcCenter( VectorMath::Vector& center ) { VectorMath::Lerp( center, vertex[0], vertex[1], 0.5 ); } //============================================================================= void GAVisToolRender::Line::Reset( void ) { } //============================================================================= void GAVisToolRender::Line::Draw( bool doLighting ) { glBegin( GL_LINES ); glLineWidth( 2.f ); Color( doLighting, false ); VectorMath::Vector cameraLookVec; wxGetApp().canvasFrame->canvas->camera.CameraLookVec( cameraLookVec ); double dot = VectorMath::Dot( cameraLookVec, normal ); if( dot > 0.0 ) glNormal3f( -normal.x, -normal.y, -normal.z ); else glNormal3f( normal.x, normal.y, normal.z ); glVertex3f( vertex[0].x, vertex[0].y, vertex[0].z ); glVertex3f( vertex[1].x, vertex[1].y, vertex[1].z ); glEnd(); } //============================================================================= GAVisToolRender::Point::Point( void ) { } //============================================================================= /*virtual*/ GAVisToolRender::Point::~Point( void ) { } //============================================================================= // We draw points as triangle fans, mainly because OpenGL selection // does not work with GL_POINTS very well for some reason that I am // too retarded to figure out. void GAVisToolRender::Point::Draw( bool doLighting, bool asPoint, VectorMath::CoordFrame& cameraFrame ) { Color( doLighting, false ); if( asPoint ) { glBegin( GL_POINTS ); glNormal3f( normal.x, normal.y, normal.z ); glVertex3f( vertex.x, vertex.y, vertex.z ); glEnd(); } else { glBegin( GL_TRIANGLE_FAN ); glNormal3f( normal.x, normal.y, normal.z ); glVertex3f( vertex.x, vertex.y, vertex.z ); double dotRadius = 0.4; int segmentCount = 10; for( int segment = 0; segment <= segmentCount; segment++ ) { double angle = 2.0 * PI * double( segment ) / double( segmentCount ); VectorMath::Vector circleVertex; VectorMath::Set( circleVertex, dotRadius * cos( angle ), dotRadius * sin( angle ), 0.0 ); VectorMath::Transform( circleVertex, cameraFrame, circleVertex ); VectorMath::Add( circleVertex, circleVertex, vertex ); glNormal3f( normal.x, normal.y, normal.z ); glVertex3f( circleVertex.x, circleVertex.y, circleVertex.z ); } glEnd(); } } //============================================================================= /*virtual*/ void GAVisToolRender::Point::CalcCenter( VectorMath::Vector& center ) { VectorMath::Copy( center, vertex ); } //============================================================================= void GAVisToolRender::Highlight( HighlightMethod highlightMethod ) { currentHighlightMethod = highlightMethod; } //============================================================================= void GAVisToolRender::Color( const VectorMath::Vector& color, double alpha ) { if( renderMode == RENDER_MODE_SELECTION ) alpha = 1.0; VectorMath::Copy( currentColor, color ); currentAlpha = alpha; } //============================================================================= void GAVisToolRender::Color( double r, double g, double b, double a ) { if( renderMode == RENDER_MODE_SELECTION ) a = 1.0; VectorMath::Set( currentColor, r, g, b ); currentAlpha = a; } //============================================================================= void GAVisToolRender::InstanceGeometry( const VectorMath::CoordFrame& coordFrame, const VectorMath::Vector& origin, const Geometry& geometry ) { for( int index = 0; index < geometry.triangleArraySize; index++ ) { Triangle* triangle = activePrimitiveCache->AllocateTriangle(); if( !triangle ) break; VectorMath::Copy( triangle->color, currentColor ); triangle->alpha = currentAlpha; triangle->highlightMethod = currentHighlightMethod; triangle->doubleSided = geometry.triangleArray[ index ].doubleSided; VectorMath::Transform( triangle->triangle.vertex[0], coordFrame, geometry.triangleArray[ index ].triangle.vertex[0] ); VectorMath::Transform( triangle->triangle.vertex[1], coordFrame, geometry.triangleArray[ index ].triangle.vertex[1] ); VectorMath::Transform( triangle->triangle.vertex[2], coordFrame, geometry.triangleArray[ index ].triangle.vertex[2] ); VectorMath::Add( triangle->triangle.vertex[0], triangle->triangle.vertex[0], origin ); VectorMath::Add( triangle->triangle.vertex[1], triangle->triangle.vertex[1], origin ); VectorMath::Add( triangle->triangle.vertex[2], triangle->triangle.vertex[2], origin ); VectorMath::TransformNormal( triangle->triangleNormals.normal[0], coordFrame, geometry.triangleArray[ index ].triangleNormals.normal[0] ); VectorMath::TransformNormal( triangle->triangleNormals.normal[1], coordFrame, geometry.triangleArray[ index ].triangleNormals.normal[1] ); VectorMath::TransformNormal( triangle->triangleNormals.normal[2], coordFrame, geometry.triangleArray[ index ].triangleNormals.normal[2] ); // This normal does not need to be transformed, because it is being calculated in world space. VectorMath::CalcNormal( triangle->triangle, triangle->normal, true ); VectorMath::MakePlane( triangle->triangle, triangle->trianglePlane ); } } //============================================================================= GAVisToolRender::Resolution GAVisToolRender::DetermineResolution( Resolution overrideResolution, double sizeFactor ) { if( overrideResolution < NUM_RES_TYPES ) return overrideResolution; // This is not a valid value for "userResolution", so just return the default here. if( userResolution == RES_USER ) return RES_MEDIUM; return userResolution; } //============================================================================= void GAVisToolRender::DrawPoint( const VectorMath::Vector& pos, const VectorMath::Vector& normal ) { Point* point = activePrimitiveCache->AllocatePoint(); if( !point ) return; VectorMath::Copy( point->color, currentColor ); point->alpha = currentAlpha; point->highlightMethod = currentHighlightMethod; VectorMath::Copy( point->vertex, pos ); VectorMath::Normalize( point->normal, normal ); if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } //============================================================================= void GAVisToolRender::DrawTriangle( const VectorMath::Triangle& triangleGeometry, const VectorMath::TriangleNormals* triangleNormals /*= 0*/ ) { Triangle* triangle = activePrimitiveCache->AllocateTriangle(); if( !triangle ) return; VectorMath::Copy( triangle->color, currentColor ); triangle->alpha = currentAlpha; triangle->highlightMethod = currentHighlightMethod; VectorMath::CopyTriangle( triangle->triangle, triangleGeometry ); VectorMath::CalcNormal( triangleGeometry, triangle->normal, true ); if( triangleNormals ) CopyTriangleNormals( triangle->triangleNormals, *triangleNormals ); else { VectorMath::Copy( triangle->triangleNormals.normal[0], triangle->normal ); VectorMath::Copy( triangle->triangleNormals.normal[1], triangle->normal ); VectorMath::Copy( triangle->triangleNormals.normal[2], triangle->normal ); } VectorMath::MakePlane( triangle->triangle, triangle->trianglePlane ); if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } //============================================================================= void GAVisToolRender::DrawLine( const VectorMath::Vector& pos0, const VectorMath::Vector& pos1 ) { Line* line = activePrimitiveCache->AllocateLine(); if( line ) { VectorMath::Copy( line->color, currentColor ); line->alpha = currentAlpha; line->highlightMethod = currentHighlightMethod; VectorMath::Copy( line->vertex[0], pos0 ); VectorMath::Copy( line->vertex[1], pos1 ); VectorMath::Sub( line->normal, line->vertex[1], line->vertex[0] ); VectorMath::Normalize( line->normal, line->normal ); } if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } //============================================================================= void GAVisToolRender::DrawTube( const VectorMath::Vector& pos0, const VectorMath::Vector& pos1, double tubeRadius, Resolution resolution /*= RES_USER*/ ) { if( geometryMode == GEOMETRY_MODE_SKINNY && tubeRadius < 0.5 ) { DrawLine( pos0, pos1 ); return; } VectorMath::CoordFrame coordFrame; VectorMath::Sub( coordFrame.zAxis, pos1, pos0 ); VectorMath::Orthogonal( coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Cross( coordFrame.xAxis, coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Normalize( coordFrame.xAxis, coordFrame.xAxis ); VectorMath::Normalize( coordFrame.yAxis, coordFrame.yAxis ); VectorMath::Scale( coordFrame.xAxis, coordFrame.xAxis, tubeRadius ); VectorMath::Scale( coordFrame.yAxis, coordFrame.yAxis, tubeRadius ); resolution = DetermineResolution( resolution, 0.0 ); if( !tubeGeometry[ resolution ] ) tubeGeometry[ resolution ] = new Geometry(); tubeGeometry[ resolution ]->GenerateGeometry( Geometry::GEO_TUBE, resolution ); InstanceGeometry( coordFrame, pos0, *tubeGeometry[ resolution ] ); if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } //============================================================================= void GAVisToolRender::DrawSphere( const VectorMath::Vector& pos, double sphereRadius, Resolution resolution /*= RES_USER*/ ) { if( geometryMode == GEOMETRY_MODE_SKINNY && sphereRadius < 0.5 ) { VectorMath::Vector normal; VectorMath::Set( normal, 0.0, 1.0, 0.0 ); DrawPoint( pos, normal ); return; } VectorMath::CoordFrame coordFrame; VectorMath::Set( coordFrame.xAxis, sphereRadius, 0.0, 0.0 ); VectorMath::Set( coordFrame.yAxis, 0.0, sphereRadius, 0.0 ); VectorMath::Set( coordFrame.zAxis, 0.0, 0.0, sphereRadius ); resolution = DetermineResolution( resolution, 0.0 ); if( !sphereGeometry[ resolution ] ) sphereGeometry[ resolution ] = new Geometry(); sphereGeometry[ resolution ]->GenerateGeometry( Geometry::GEO_SPHERE, resolution ); InstanceGeometry( coordFrame, pos, *sphereGeometry[ resolution ] ); if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } //============================================================================= void GAVisToolRender::DrawCircle( const VectorMath::Vector& pos, const VectorMath::Vector& norm, double circleRadius, Resolution resolution /*= RES_USER*/ ) { VectorMath::CoordFrame coordFrame; VectorMath::Normalize( coordFrame.zAxis, norm ); VectorMath::Orthogonal( coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Cross( coordFrame.xAxis, coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Scale( coordFrame.xAxis, coordFrame.xAxis, circleRadius ); VectorMath::Scale( coordFrame.yAxis, coordFrame.yAxis, circleRadius ); resolution = DetermineResolution( resolution, 0.0 ); int segmentCount = 3; if( resolution == RES_LOW ) segmentCount = 10; else if( resolution == RES_MEDIUM ) segmentCount = 20; else if( resolution == RES_HIGH ) segmentCount = 30; for( int segment = 0; segment < segmentCount; segment++ ) { double angle = 2.0 * PI * double( segment ) / double( segmentCount ); double nextAngle = 2.0 * PI * double( ( segment + 1 ) % segmentCount ) / double( segmentCount ); Line* line = activePrimitiveCache->AllocateLine(); if( line ) { VectorMath::Copy( line->color, currentColor ); line->alpha = currentAlpha; line->highlightMethod = currentHighlightMethod; VectorMath::Set( line->vertex[0], cos( angle ), sin( angle ), 0.0 ); VectorMath::Set( line->vertex[1], cos( nextAngle ), sin( nextAngle ), 0.0 ); VectorMath::Transform( line->vertex, coordFrame, pos, line->vertex, 2 ); VectorMath::Set( line->normal, 0.0, 0.0, 1.0 ); VectorMath::TransformNormal( line->normal, coordFrame, line->normal ); } } if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } //============================================================================= void GAVisToolRender::DrawTorus( const VectorMath::Vector& pos, const VectorMath::Vector& norm, double torusRadius, Resolution resolution /*= RES_USER*/ ) { if( geometryMode == GEOMETRY_MODE_SKINNY ) { DrawCircle( pos, norm, torusRadius, resolution ); return; } VectorMath::CoordFrame coordFrame; VectorMath::Normalize( coordFrame.zAxis, norm ); VectorMath::Orthogonal( coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Cross( coordFrame.xAxis, coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Scale( coordFrame.xAxis, coordFrame.xAxis, torusRadius ); VectorMath::Scale( coordFrame.yAxis, coordFrame.yAxis, torusRadius ); VectorMath::Scale( coordFrame.zAxis, coordFrame.zAxis, torusRadius ); resolution = DetermineResolution( resolution, 0.0 ); if( !torusGeometry[ resolution ] ) torusGeometry[ resolution ] = new Geometry(); torusGeometry[ resolution ]->GenerateGeometry( Geometry::GEO_TORUS, resolution ); InstanceGeometry( coordFrame, pos, *torusGeometry[ resolution ] ); if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } //============================================================================= void GAVisToolRender::DrawDisk( const VectorMath::Vector& pos, const VectorMath::Vector& norm, double diskRadius, Resolution resolution /*= RES_USER*/ ) { VectorMath::CoordFrame coordFrame; VectorMath::Normalize( coordFrame.zAxis, norm ); VectorMath::Orthogonal( coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Cross( coordFrame.xAxis, coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Scale( coordFrame.xAxis, coordFrame.xAxis, diskRadius ); VectorMath::Scale( coordFrame.yAxis, coordFrame.yAxis, diskRadius ); resolution = DetermineResolution( resolution, 0.0 ); if( !diskGeometry[ resolution ] ) diskGeometry[ resolution ] = new Geometry(); diskGeometry[ resolution ]->GenerateGeometry( Geometry::GEO_DISK, resolution ); InstanceGeometry( coordFrame, pos, *diskGeometry[ resolution ] ); if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } //============================================================================= void GAVisToolRender::DrawVector( const VectorMath::Vector& pos, const VectorMath::Vector& vec, Resolution resolution /*= RES_USER*/, bool draw1DVector /*= false*/ ) { // Always draw the stem using a simple GL_LINE primtives. Line* line = activePrimitiveCache->AllocateLine(); if( line ) { VectorMath::Copy( line->color, currentColor ); line->alpha = currentAlpha; line->highlightMethod = currentHighlightMethod; VectorMath::Copy( line->vertex[0], pos ); VectorMath::Add( line->vertex[1], pos, vec ); VectorMath::Normalize( line->normal, vec ); } // Draw the arrow head as 3D if desired. if( draw3DVectors && !draw1DVector ) { VectorMath::CoordFrame coordFrame; VectorMath::Copy( coordFrame.zAxis, vec ); VectorMath::Orthogonal( coordFrame.yAxis, coordFrame.zAxis ); VectorMath::Cross( coordFrame.xAxis, coordFrame.yAxis, coordFrame.zAxis ); double vecLength = VectorMath::Length( vec ); VectorMath::Scale( coordFrame.xAxis, coordFrame.xAxis, 1.0 / vecLength ); resolution = DetermineResolution( resolution, 0.0 ); if( !vectorGeometry[ resolution ] ) vectorGeometry[ resolution ] = new Geometry(); vectorGeometry[ resolution ]->GenerateGeometry( Geometry::GEO_VECTOR, resolution ); InstanceGeometry( coordFrame, pos, *vectorGeometry[ resolution ] ); if( renderMode == RENDER_MODE_SELECTION ) activePrimitiveCache->Flush( *this ); } } //============================================================================= void GAVisToolRender::DrawArrow( const VectorMath::Vector& pos, const VectorMath::Vector& vec ) { // bill-board a line-arrow here... } //============================================================================= GAVisToolRender::Geometry::Geometry( void ) { geoType = GEO_NONE; resolution = RES_MEDIUM; triangleArray = 0; triangleArraySize = 0; } //============================================================================= /*virtual*/ GAVisToolRender::Geometry::~Geometry( void ) { WipeGeometry(); } //============================================================================= GAVisToolRender::Geometry::Triangle::Triangle( void ) { doubleSided = false; } //============================================================================= void GAVisToolRender::Geometry::GenerateGeometry( GeoType geoType, Resolution resolution ) { if( geoType != this->geoType || resolution != this->resolution ) { WipeGeometry(); this->geoType = geoType; this->resolution = resolution; switch( geoType ) { case GEO_TUBE: GenerateCanonicalUnitTube(); break; case GEO_SPHERE: GenerateCanonicalUnitSphere(); break; case GEO_TORUS: GenerateCanonicalUnitTorus(); break; case GEO_DISK: GenerateCanonicalUnitDisk(); break; case GEO_VECTOR: GenerateCanonicalUnitVector(); break; } } } //============================================================================= void GAVisToolRender::Geometry::WipeGeometry( void ) { if( triangleArray ) delete[] triangleArray; triangleArray = 0; triangleArraySize = 0; geoType = GEO_NONE; resolution = RES_MEDIUM; } //============================================================================= void GAVisToolRender::Geometry::GenerateCanonicalUnitTube( void ) { int segmentCount = 3; if( resolution == RES_LOW ) segmentCount = 4; else if( resolution == RES_MEDIUM ) segmentCount = 8; else if( resolution == RES_HIGH ) segmentCount = 16; VectorMath::Vector* circle0 = new VectorMath::Vector[ segmentCount ]; VectorMath::Vector* circle1 = new VectorMath::Vector[ segmentCount ]; for( int segment = 0; segment < segmentCount; segment++ ) { double angle = 2.0 * PI * double( segment ) / double( segmentCount ); double cosAngle = cos( angle ); double sinAngle = sin( angle ); VectorMath::Set( circle0[ segment ], cosAngle, sinAngle, 0.0 ); VectorMath::Set( circle1[ segment ], cosAngle, sinAngle, 1.0 ); } triangleArraySize = segmentCount * 2; triangleArray = new Triangle[ triangleArraySize ]; Triangle* triangle = triangleArray; for( int segment = 0; segment < segmentCount; segment++ ) { int nextSegment = ( segment + 1 ) % segmentCount; VectorMath::Copy( triangle->triangle.vertex[0], circle0[ segment ] ); VectorMath::Copy( triangle->triangle.vertex[1], circle0[ nextSegment ] ); VectorMath::Copy( triangle->triangle.vertex[2], circle1[ nextSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[0], triangle->triangle.vertex[0] ); VectorMath::Copy( triangle->triangleNormals.normal[1], triangle->triangle.vertex[1] ); VectorMath::Copy( triangle->triangleNormals.normal[2], triangle->triangle.vertex[2] ); triangle++; VectorMath::Copy( triangle->triangle.vertex[0], circle0[ segment ] ); VectorMath::Copy( triangle->triangle.vertex[1], circle1[ nextSegment ] ); VectorMath::Copy( triangle->triangle.vertex[2], circle1[ segment ] ); VectorMath::Copy( triangle->triangleNormals.normal[0], triangle->triangle.vertex[0] ); VectorMath::Copy( triangle->triangleNormals.normal[1], triangle->triangle.vertex[1] ); VectorMath::Copy( triangle->triangleNormals.normal[2], triangle->triangle.vertex[2] ); triangle++; } delete[] circle0; delete[] circle1; } //============================================================================= void GAVisToolRender::Geometry::GenerateCanonicalUnitSphere( void ) { int latitudeSegmentCount = 4; int longitudeSegmentCount = 4; if( resolution == RES_LOW ) { latitudeSegmentCount = 6; longitudeSegmentCount = 6; } else if( resolution == RES_MEDIUM ) { latitudeSegmentCount = 10; longitudeSegmentCount = 10; } else if( resolution == RES_HIGH ) { latitudeSegmentCount = 16; longitudeSegmentCount = 16; } VectorMath::Vector** sphereVertices = new VectorMath::Vector*[ longitudeSegmentCount ]; for( int longitudeSegment = 0; longitudeSegment < longitudeSegmentCount; longitudeSegment++ ) { sphereVertices[ longitudeSegment ] = new VectorMath::Vector[ latitudeSegmentCount ]; double longitudeAngle = 2.0 * PI * double( longitudeSegment ) / double( longitudeSegmentCount ); for( int latitudeSegment = 0; latitudeSegment < latitudeSegmentCount; latitudeSegment++ ) { double latitudeAngle = PI * double( latitudeSegment ) / double( latitudeSegmentCount - 1 ); double cosLongitudeAngle = cos( longitudeAngle ); double sinLongitudeAngle = sin( longitudeAngle ); double cosLatitudeAngle = cos( latitudeAngle ); double sinLatitudeAngle = sin( latitudeAngle ); VectorMath::Vector* vertex = &sphereVertices[ longitudeSegment ][ latitudeSegment ]; VectorMath::Set( *vertex, cosLongitudeAngle * sinLatitudeAngle, cosLatitudeAngle, -sinLongitudeAngle * sinLatitudeAngle ); } } triangleArraySize = 2 * longitudeSegmentCount * ( latitudeSegmentCount - 2 ); triangleArray = new Triangle[ triangleArraySize ]; Triangle* triangle = triangleArray; for( int longitudeSegment = 0; longitudeSegment < longitudeSegmentCount; longitudeSegment++ ) { int nextLongitudeSegment = ( longitudeSegment + 1 ) % longitudeSegmentCount; VectorMath::Copy( triangle->triangle.vertex[0], sphereVertices[ longitudeSegment ][0] ); VectorMath::Copy( triangle->triangle.vertex[1], sphereVertices[ longitudeSegment ][1] ); VectorMath::Copy( triangle->triangle.vertex[2], sphereVertices[ nextLongitudeSegment ][1] ); VectorMath::Copy( triangle->triangleNormals.normal[0], triangle->triangle.vertex[0] ); VectorMath::Copy( triangle->triangleNormals.normal[1], triangle->triangle.vertex[1] ); VectorMath::Copy( triangle->triangleNormals.normal[2], triangle->triangle.vertex[2] ); triangle++; VectorMath::Copy( triangle->triangle.vertex[0], sphereVertices[ longitudeSegment ][ latitudeSegmentCount - 2 ] ); VectorMath::Copy( triangle->triangle.vertex[1], sphereVertices[ longitudeSegment ][ latitudeSegmentCount - 1 ] ); VectorMath::Copy( triangle->triangle.vertex[2], sphereVertices[ nextLongitudeSegment ][ latitudeSegmentCount - 2 ] ); VectorMath::Copy( triangle->triangleNormals.normal[0], triangle->triangle.vertex[0] ); VectorMath::Copy( triangle->triangleNormals.normal[1], triangle->triangle.vertex[1] ); VectorMath::Copy( triangle->triangleNormals.normal[2], triangle->triangle.vertex[2] ); triangle++; for( int latitudeSegment = 1; latitudeSegment < latitudeSegmentCount - 2; latitudeSegment++ ) { int nextLatitudeSegment = latitudeSegment + 1; VectorMath::Copy( triangle->triangle.vertex[0], sphereVertices[ longitudeSegment ][ latitudeSegment ] ); VectorMath::Copy( triangle->triangle.vertex[1], sphereVertices[ longitudeSegment ][ nextLatitudeSegment ] ); VectorMath::Copy( triangle->triangle.vertex[2], sphereVertices[ nextLongitudeSegment ][ nextLatitudeSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[0], triangle->triangle.vertex[0] ); VectorMath::Copy( triangle->triangleNormals.normal[1], triangle->triangle.vertex[1] ); VectorMath::Copy( triangle->triangleNormals.normal[2], triangle->triangle.vertex[2] ); triangle++; VectorMath::Copy( triangle->triangle.vertex[0], sphereVertices[ longitudeSegment ][ latitudeSegment ] ); VectorMath::Copy( triangle->triangle.vertex[1], sphereVertices[ nextLongitudeSegment ][ nextLatitudeSegment ] ); VectorMath::Copy( triangle->triangle.vertex[2], sphereVertices[ nextLongitudeSegment ][ latitudeSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[0], triangle->triangle.vertex[0] ); VectorMath::Copy( triangle->triangleNormals.normal[1], triangle->triangle.vertex[1] ); VectorMath::Copy( triangle->triangleNormals.normal[2], triangle->triangle.vertex[2] ); triangle++; } } for( int longitudeSegment = 0; longitudeSegment < longitudeSegmentCount; longitudeSegment++ ) delete[] sphereVertices[ longitudeSegment ]; delete[] sphereVertices; } //============================================================================= void GAVisToolRender::Geometry::GenerateCanonicalUnitTorus( void ) { int torusSegmentCount = 4; int torusTubeSegmentCount = 3; if( resolution == RES_LOW ) { torusSegmentCount = 6; torusTubeSegmentCount = 6; } else if( resolution == RES_MEDIUM ) { torusSegmentCount = 14; torusTubeSegmentCount = 8; } else if( resolution == RES_HIGH ) { torusSegmentCount = 18; torusTubeSegmentCount = 10; } double torusRadius = 1.0; double torusTubeRadius = 0.05; VectorMath::Vector** torusVertices = new VectorMath::Vector*[ torusSegmentCount ]; VectorMath::Vector** torusNormals = new VectorMath::Vector*[ torusSegmentCount ]; for( int torusSegment = 0; torusSegment < torusSegmentCount; torusSegment++ ) { double torusSegmentAngle = 2.0 * PI * double( torusSegment ) / double( torusSegmentCount ); double cosTorusSegmentAngle = cos( torusSegmentAngle ); double sinTorusSegmentAngle = sin( torusSegmentAngle ); torusVertices[ torusSegment ] = new VectorMath::Vector[ torusTubeSegmentCount ]; torusNormals[ torusSegment ] = new VectorMath::Vector[ torusTubeSegmentCount ]; for( int torusTubeSegment = 0; torusTubeSegment < torusTubeSegmentCount; torusTubeSegment++ ) { double torusTubeSegmentAngle = 2.0 * PI * double( torusTubeSegment ) / double( torusTubeSegmentCount ); double cosTorusTubeSegmentAngle = cos( torusTubeSegmentAngle ); double sinTorusTubeSegmentAngle = sin( torusTubeSegmentAngle ); VectorMath::Set( torusVertices[ torusSegment ][ torusTubeSegment ], cosTorusSegmentAngle * ( torusRadius + torusTubeRadius * cosTorusTubeSegmentAngle ), sinTorusSegmentAngle * ( torusRadius + torusTubeRadius * cosTorusTubeSegmentAngle ), torusTubeRadius * sinTorusTubeSegmentAngle ); VectorMath::Set( torusNormals[ torusSegment ][ torusTubeSegment ], cosTorusSegmentAngle * cosTorusTubeSegmentAngle, sinTorusSegmentAngle * cosTorusTubeSegmentAngle, sinTorusTubeSegmentAngle ); } } triangleArraySize = 2 * torusSegmentCount * torusTubeSegmentCount; triangleArray = new Triangle[ triangleArraySize ]; Triangle* triangle = triangleArray; for( int torusSegment = 0; torusSegment < torusSegmentCount; torusSegment++ ) { int nextTorusSegment = ( torusSegment + 1 ) % torusSegmentCount; for( int torusTubeSegment = 0; torusTubeSegment < torusTubeSegmentCount; torusTubeSegment++ ) { int nextTorusTubeSegment = ( torusTubeSegment + 1 ) % torusTubeSegmentCount; VectorMath::Copy( triangle->triangle.vertex[0], torusVertices[ torusSegment ][ torusTubeSegment ] ); VectorMath::Copy( triangle->triangle.vertex[1], torusVertices[ nextTorusSegment ][ torusTubeSegment ] ); VectorMath::Copy( triangle->triangle.vertex[2], torusVertices[ nextTorusSegment ][ nextTorusTubeSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[0], torusNormals[ torusSegment ][ torusTubeSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[1], torusNormals[ nextTorusSegment ][ torusTubeSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[2], torusNormals[ nextTorusSegment ][ nextTorusTubeSegment ] ); triangle++; VectorMath::Copy( triangle->triangle.vertex[0], torusVertices[ torusSegment ][ torusTubeSegment ] ); VectorMath::Copy( triangle->triangle.vertex[1], torusVertices[ nextTorusSegment ][ nextTorusTubeSegment ] ); VectorMath::Copy( triangle->triangle.vertex[2], torusVertices[ torusSegment ][ nextTorusTubeSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[0], torusNormals[ torusSegment ][ torusTubeSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[1], torusNormals[ nextTorusSegment ][ nextTorusTubeSegment ] ); VectorMath::Copy( triangle->triangleNormals.normal[2], torusNormals[ torusSegment ][ nextTorusTubeSegment ] ); triangle++; } } for( int torusSegment = 0; torusSegment < torusSegmentCount; torusSegment++ ) { delete[] torusVertices[ torusSegment ]; delete[] torusNormals[ torusSegment ]; } delete[] torusVertices; delete[] torusNormals; } //============================================================================= // The layers here are provided instead of one big triangle fan, because // I'm not doing any sort of fragment shader that would give us something // better than vertex lighting. void GAVisToolRender::Geometry::GenerateCanonicalUnitDisk( void ) { int segmentCount = 5; int layerCount = 5; if( resolution == RES_LOW ) { segmentCount = 6; layerCount = 6; } else if( resolution == RES_MEDIUM ) { segmentCount = 12; layerCount = 10; } else if( resolution == RES_HIGH ) { segmentCount = 20; layerCount = 14; } VectorMath::Vector** disk = new VectorMath::Vector*[ layerCount ]; for( int layer = 0; layer < layerCount; layer++ ) { disk[ layer ] = new VectorMath::Vector[ segmentCount ]; double radius = double( layer + 1 ) / double( layerCount ); for( int segment = 0; segment < segmentCount; segment++ ) { double angle = 2.0 * PI * double( segment ) / double( segmentCount ); double x = radius * cos( angle ); double y = radius * sin( angle ); VectorMath::Set( disk[ layer ][ segment ], x, y, 0.0 ); } } triangleArraySize = segmentCount * ( 2 * layerCount - 1 ); triangleArray = new Triangle[ triangleArraySize ]; Triangle* triangle = triangleArray; for( int layer = 0; layer < layerCount; layer++ ) { int prevLayer = layer - 1; for( int segment = 0; segment < segmentCount; segment++ ) { int nextSegment = ( segment + 1 ) % segmentCount; if( layer == 0 ) { VectorMath::Zero( triangle->triangle.vertex[0] ); VectorMath::Copy( triangle->triangle.vertex[1], disk[0][ segment ] ); VectorMath::Copy( triangle->triangle.vertex[2], disk[0][ nextSegment ] ); VectorMath::Set( triangle->triangleNormals.normal[0], 0.0, 0.0, 1.0 ); VectorMath::Set( triangle->triangleNormals.normal[1], 0.0, 0.0, 1.0 ); VectorMath::Set( triangle->triangleNormals.normal[2], 0.0, 0.0, 1.0 ); triangle->doubleSided = true; triangle++; } else { VectorMath::Copy( triangle->triangle.vertex[0], disk[ layer ][ segment ] ); VectorMath::Copy( triangle->triangle.vertex[1], disk[ layer ][ nextSegment ] ); VectorMath::Copy( triangle->triangle.vertex[2], disk[ prevLayer ][ segment ] ); VectorMath::Set( triangle->triangleNormals.normal[0], 0.0, 0.0, 1.0 ); VectorMath::Set( triangle->triangleNormals.normal[1], 0.0, 0.0, 1.0 ); VectorMath::Set( triangle->triangleNormals.normal[2], 0.0, 0.0, 1.0 ); triangle->doubleSided = true; triangle++; VectorMath::Copy( triangle->triangle.vertex[0], disk[ layer ][ nextSegment ] ); VectorMath::Copy( triangle->triangle.vertex[1], disk[ prevLayer ][ nextSegment ] ); VectorMath::Copy( triangle->triangle.vertex[2], disk[ prevLayer ][ segment ] ); VectorMath::Set( triangle->triangleNormals.normal[0], 0.0, 0.0, 1.0 ); VectorMath::Set( triangle->triangleNormals.normal[1], 0.0, 0.0, 1.0 ); VectorMath::Set( triangle->triangleNormals.normal[2], 0.0, 0.0, 1.0 ); triangle->doubleSided = true; triangle++; } } } for( int layer = 0; layer < layerCount; layer++ ) delete[] disk[ layer ]; delete[] disk; } //============================================================================= void GAVisToolRender::Geometry::GenerateCanonicalUnitVector( void ) { int segmentCount = 3; if( resolution == RES_LOW ) segmentCount = 4; else if( resolution == RES_MEDIUM ) segmentCount = 8; else if( resolution == RES_HIGH ) segmentCount = 16; double arrowHeadRadius = 0.1; double arrowHeadBase = 0.8; VectorMath::Vector* circle = new VectorMath::Vector[ segmentCount ]; for( int segment = 0; segment < segmentCount; segment++ ) { double angle = 2.0 * PI * double( segment ) / double( segmentCount ); double cosAngle = cos( angle ); double sinAngle = sin( angle ); VectorMath::Set( circle[ segment ], arrowHeadRadius * cosAngle, arrowHeadRadius * sinAngle, arrowHeadBase ); } triangleArraySize = 2 * segmentCount; triangleArray = new Triangle[ triangleArraySize ]; Triangle* triangle = triangleArray; for( int segment = 0; segment < segmentCount; segment++ ) { int nextSegment = ( segment + 1 ) % segmentCount; VectorMath::Copy( triangle->triangle.vertex[0], circle[ segment ] ); VectorMath::Copy( triangle->triangle.vertex[1], circle[ nextSegment ] ); VectorMath::Set( triangle->triangle.vertex[2], 0.0, 0.0, 1.0 ); VectorMath::Copy( triangle->triangleNormals.normal[0], triangle->triangle.vertex[0] ); VectorMath::Copy( triangle->triangleNormals.normal[1], triangle->triangle.vertex[1] ); VectorMath::Copy( triangle->triangleNormals.normal[2], triangle->triangle.vertex[2] ); triangle++; VectorMath::Copy( triangle->triangle.vertex[0], circle[ nextSegment ] ); VectorMath::Copy( triangle->triangle.vertex[1], circle[ segment ] ); VectorMath::Set( triangle->triangle.vertex[2], 0.0, 0.0, arrowHeadBase ); VectorMath::Set( triangle->triangleNormals.normal[0], 0.0, 0.0, -1.0 ); VectorMath::Set( triangle->triangleNormals.normal[1], 0.0, 0.0, -1.0 ); VectorMath::Set( triangle->triangleNormals.normal[2], 0.0, 0.0, -1.0 ); triangle++; } delete[] circle; } //============================================================================= GAVisToolRender::BspNode::BspNode( void ) { Reset(); } //============================================================================= GAVisToolRender::BspNode::~BspNode( void ) { } //============================================================================= void GAVisToolRender::BspNode::Reset( void ) { frontNode = 0; backNode = 0; partitionPlaneCreated = false; } //============================================================================= // Notice that like the triangle version of this routine, we don't leak memory // when the line is split and we insert the parts of the line and forget about // the original line that was broken up, because we're managing all line memory. void GAVisToolRender::BspNode::DistributeLine( Line* line, Line*& backLine, Line*& frontLine, ObjectHeap< Line >& lineHeap, BspTree* bspTree ) { double halfPlaneThickness = BspTree::HALF_PLANE_THICKNESS; VectorMath::Plane::Side planeSide[2]; planeSide[0] = VectorMath::PlaneSide( partitionPlane, line->vertex[0], halfPlaneThickness ); planeSide[1] = VectorMath::PlaneSide( partitionPlane, line->vertex[1], halfPlaneThickness ); backLine = 0; frontLine = 0; if( planeSide[0] == planeSide[1] ) { switch( planeSide[0] ) { case VectorMath::Plane::SIDE_BACK: { backLine = line; break; } case VectorMath::Plane::SIDE_FRONT: { frontLine = line; break; } case VectorMath::Plane::SIDE_NEITHER: { lineList.InsertRightOf( lineList.RightMost(), line ); break; } } } else if( planeSide[0] == VectorMath::Plane::SIDE_NEITHER ) { if( planeSide[1] == VectorMath::Plane::SIDE_BACK ) backLine = line; else frontLine = line; } else if( planeSide[1] == VectorMath::Plane::SIDE_NEITHER ) { if( planeSide[0] == VectorMath::Plane::SIDE_BACK ) backLine = line; else frontLine = line; } else { double lerp; VectorMath::PlaneLineIntersect( partitionPlane, line->vertex[0], line->vertex[1], lerp ); VectorMath::Vector vertex; VectorMath::Lerp( vertex, line->vertex[0], line->vertex[1], lerp ); // Keep track of some stats. bspTree->lineSplitCount++; backLine = lineHeap.AllocateFresh(); if( backLine ) { backLine->CopyBaseData( *line ); VectorMath::Copy( backLine->vertex[0], vertex ); } frontLine = lineHeap.AllocateFresh(); if( frontLine ) { frontLine->CopyBaseData( *line ); VectorMath::Copy( frontLine->vertex[0], vertex ); } if( frontLine && backLine ) { if( planeSide[0] == VectorMath::Plane::SIDE_BACK ) { VectorMath::Copy( backLine->vertex[1], line->vertex[0] ); VectorMath::Copy( frontLine->vertex[1], line->vertex[1] ); } else { VectorMath::Copy( backLine->vertex[1], line->vertex[1] ); VectorMath::Copy( frontLine->vertex[1], line->vertex[0] ); } // This was an attempt to compensate for the crappy look // of a line that was split into a sequence of several line segments. /* double deltaLength = 0.02; VectorMath::Vector delta; VectorMath::Sub( delta, backLine->vertex[0], backLine->vertex[1] ); VectorMath::Scale( delta, delta, deltaLength / VectorMath::Length( delta ) ); VectorMath::Add( backLine->vertex[0], backLine->vertex[0], delta ); VectorMath::Sub( delta, frontLine->vertex[0], frontLine->vertex[1] ); VectorMath::Scale( delta, delta, deltaLength / VectorMath::Length( delta ) ); VectorMath::Add( frontLine->vertex[0], frontLine->vertex[0], delta ); */ } } } //============================================================================= // Append to the given lists parts of the given triangle if it straddles the plane, // or append the given triangle to the correct list in all other cases. We assume // that the given triangle is not a member of any list. Notice that we put the given // triangle on this node's list if it is in the partition plane. void GAVisToolRender::BspNode::DistributeTriangle( Triangle* triangle, Utilities::List& backTriangleList, Utilities::List& frontTriangleList, ObjectHeap< Triangle >& triangleHeap, BspTree* bspTree ) { double halfPlaneThickness = BspTree::HALF_PLANE_THICKNESS; VectorMath::SideCountData sideCountData; VectorMath::SideCount( triangle->triangle, partitionPlane, sideCountData, halfPlaneThickness ); if( sideCountData.countOnPlane == 3 ) { triangleList.InsertRightOf( triangleList.RightMost(), triangle ); if( triangle->bspAnalysisData ) BspTree::OldTriangleDies( triangle ); } else if( sideCountData.countOnFront == 3 || ( sideCountData.countOnFront == 2 && sideCountData.countOnPlane == 1 ) || ( sideCountData.countOnFront == 1 && sideCountData.countOnPlane == 2 ) ) { frontTriangleList.InsertRightOf( frontTriangleList.RightMost(), triangle ); } else if( sideCountData.countOnBack == 3 || ( sideCountData.countOnBack == 2 && sideCountData.countOnPlane == 1 ) || ( sideCountData.countOnBack == 1 && sideCountData.countOnPlane == 2 ) ) { backTriangleList.InsertRightOf( backTriangleList.RightMost(), triangle ); } else { // In this case the triangle strattles the plane, and we need to cut it against the plane! VectorMath::Plane::Side sideArray[3]; VectorMath::Triangle triangleArray[3]; VectorMath::TriangleNormals triangleNormalsArray[3]; int triangleArraySize = 0; // Keep track of some stats. bspTree->triangleSplitCount++; // This should always return true here. VectorMath::SplitTriangle( triangle->triangle, &triangle->triangleNormals, partitionPlane, sideCountData, triangleArray, triangleNormalsArray, sideArray, triangleArraySize ); for( int index = 0; index < triangleArraySize; index++ ) { Triangle* trianglePart = triangleHeap.AllocateFresh(); if( !trianglePart ) break; VectorMath::CopyTriangle( trianglePart->triangle, triangleArray[ index ] ); VectorMath::CopyTriangleNormals( trianglePart->triangleNormals, triangleNormalsArray[ index ] ); trianglePart->CopyBaseData( *triangle ); VectorMath::MakePlane( trianglePart->triangle, trianglePart->trianglePlane ); // Each triangle part should be on either the back or the front of the partitioning plane. switch( sideArray[ index ] ) { case VectorMath::Plane::SIDE_FRONT: { frontTriangleList.InsertRightOf( frontTriangleList.RightMost(), trianglePart ); break; } case VectorMath::Plane::SIDE_BACK: { backTriangleList.InsertRightOf( backTriangleList.RightMost(), trianglePart ); break; } } if( triangle->bspAnalysisData ) BspTree::NewTriangleBornFromOld( trianglePart, triangle, bspTree->bspAnalysisDataHeap ); } if( triangle->bspAnalysisData ) BspTree::OldTriangleDies( triangle ); } } //============================================================================= /*static*/ void GAVisToolRender::BspTree::OldTriangleDies( Triangle* oldTriangle ) { BspAnalysisData* bspAnalysisData = 0; // All the triangles that the old triangle split are no longer split by this triangle. while( oldTriangle->bspAnalysisData->trianglesSplitByThis.Count() > 0 ) { bspAnalysisData = ( BspAnalysisData* )oldTriangle->bspAnalysisData->trianglesSplitByThis.LeftMost(); oldTriangle->bspAnalysisData->trianglesSplitByThis.Remove( bspAnalysisData, false ); bspAnalysisData->triangle->bspAnalysisData->trianglesSplittingThis.Remove( oldTriangle->bspAnalysisData, false ); } // All the triangles that the old triangle was split by no longer split this triangle. while( oldTriangle->bspAnalysisData->trianglesSplittingThis.Count() > 0 ) { bspAnalysisData = ( BspAnalysisData* )oldTriangle->bspAnalysisData->trianglesSplittingThis.LeftMost(); oldTriangle->bspAnalysisData->trianglesSplittingThis.Remove( bspAnalysisData, false ); bspAnalysisData->triangle->bspAnalysisData->trianglesSplitByThis.Remove( oldTriangle->bspAnalysisData, false ); } } //============================================================================= /*static*/ void GAVisToolRender::BspTree::NewTriangleBornFromOld( Triangle* newTriangle, Triangle* oldTriangle, ObjectHeap< BspAnalysisData >& bspAnalysisDataHeap ) { newTriangle->bspAnalysisData = bspAnalysisDataHeap.AllocateFresh(); // A triangle split by the triangle to be tesselated will also be split by one of its sub-triangles. newTriangle->bspAnalysisData->trianglesSplitByThis.Assign( oldTriangle->bspAnalysisData->trianglesSplitByThis, false ); // A triangle splitting the triangle to be tesselated, however, may not necessarily split one of its sub-triangles. BspAnalysisData* bspAnalysisData = ( BspAnalysisData* )oldTriangle->bspAnalysisData->trianglesSplittingThis.LeftMost(); while( bspAnalysisData ) { if( newTriangle->StraddlesPlane( bspAnalysisData->triangle->trianglePlane ) ) newTriangle->bspAnalysisData->trianglesSplittingThis.InsertRightOf( newTriangle->bspAnalysisData->trianglesSplittingThis.RightMost(), bspAnalysisData ); bspAnalysisData = ( BspAnalysisData* )bspAnalysisData->Right( &oldTriangle->bspAnalysisData->trianglesSplittingThis ); } } //============================================================================= // We have all the information here that I think we could ever need in figuring // out which triangle or set of triangles represent the best choice or choices. // It's now just a matter of knowing how to make the decision. Clearly any triangle // that cuts no other triangle is a good choice. If there are no such triangles, // then the decision becomes a little harder to make. Certainly we want to minimize // the number of cuts made by the chosen triangle. GAVisToolRender::Triangle* GAVisToolRender::BspNode::ChooseBestRootTriangle( Utilities::List& subTreeTriangleList ) { Triangle* bestTriangle = 0; int minimalCutCount = -1; int maximalCutByCount = -1; // I'm not sure that this matters at all. Why again did I think it mattered? for( Triangle* triangle = ( Triangle* )subTreeTriangleList.LeftMost(); triangle; triangle = ( Triangle* )triangle->Right() ) { Triangle* currentTriangle = bestTriangle; if( !bestTriangle ) bestTriangle = triangle; else { if( triangle->bspAnalysisData->trianglesSplitByThis.Count() < minimalCutCount ) bestTriangle = triangle; else if( triangle->bspAnalysisData->trianglesSplitByThis.Count() == minimalCutCount ) { // Again, I'm not sure that this matters at all. if( triangle->bspAnalysisData->trianglesSplittingThis.Count() > maximalCutByCount ) bestTriangle = triangle; } } if( currentTriangle != bestTriangle ) { minimalCutCount = triangle->bspAnalysisData->trianglesSplitByThis.Count(); maximalCutByCount = triangle->bspAnalysisData->trianglesSplittingThis.Count(); } } return bestTriangle; } //============================================================================= // Build a sub-tree at this node with the given list of triangles. // We assume that the triangle list of this node is empty to begin with. void GAVisToolRender::BspNode::Insert( Utilities::List& subTreeTriangleList, ObjectHeap< Triangle >& triangleHeap, BspTree* bspTree ) { // Our first task is to choose the best root node triangle. Triangle* rootTriangle = ChooseBestRootTriangle( subTreeTriangleList ); subTreeTriangleList.Remove( rootTriangle, false ); triangleList.InsertLeftOf( 0, rootTriangle ); VectorMath::CopyPlane( partitionPlane, rootTriangle->trianglePlane ); partitionPlaneCreated = true; // This isn't used in this algorithm, but set it none-the-less. // Remove this triangle from consideration within the entirety of our analysis data. BspTree::OldTriangleDies( rootTriangle ); // Having chosen a partition plane, go divide everything up into the seperate half-spaces. Utilities::List backTriangleList, frontTriangleList; while( subTreeTriangleList.Count() > 0 ) { Triangle* triangle = ( Triangle* )subTreeTriangleList.LeftMost(); subTreeTriangleList.Remove( triangle, false ); // Put the triangle in the correct list or split it across the front and back lists. DistributeTriangle( triangle, backTriangleList, frontTriangleList, triangleHeap, bspTree ); } // Now go divide and conquer. if( backTriangleList.Count() > 0 ) { if( !backNode ) backNode = bspTree->bspNodeHeap.AllocateFresh(); if( backNode ) backNode->Insert( backTriangleList, triangleHeap, bspTree ); } if( frontTriangleList.Count() > 0 ) { if( !frontNode ) frontNode = bspTree->bspNodeHeap.AllocateFresh(); if( frontNode ) frontNode->Insert( frontTriangleList, triangleHeap, bspTree ); } // If this is a leaf node, then this should not happen! A triangle all by itself // in its own half-space is not cutting any other triangle or being cut by any other // triangle, because there are no other triangles in that space. This also shouldn't // happen for any internal triangles, because the analysis data should dwindle to // empty as triangles are removed from consideration and put into the tree. In short, // this should never happen, but I'm putting this here just in case for now. if( rootTriangle->bspAnalysisData->trianglesSplitByThis.Count() > 0 ) rootTriangle->bspAnalysisData->trianglesSplitByThis.RemoveAll( false ); if( rootTriangle->bspAnalysisData->trianglesSplittingThis.Count() > 0 ) rootTriangle->bspAnalysisData->trianglesSplittingThis.RemoveAll( false ); // Keep track of some stats. bspTree->postBspTriangleCount += triangleList.Count(); } //============================================================================= void GAVisToolRender::BspNode::Insert( Line* line, ObjectHeap< Line >& lineHeap, BspTree* bspTree ) { if( !partitionPlaneCreated ) { lineList.InsertLeftOf( 0, line ); // Arbitrarily choose a plane that contains the line. VectorMath::Vector lineVec; VectorMath::Sub( lineVec, line->vertex[1], line->vertex[0] ); VectorMath::Orthogonal( partitionPlane.normal, lineVec ); VectorMath::Normalize( partitionPlane.normal, partitionPlane.normal ); VectorMath::SetPlanePos( partitionPlane, line->vertex[0] ); partitionPlaneCreated = true; // Keep track of some stats. bspTree->postBspLineCount++; } else { int numLinesBefore = lineList.Count(); Line* backLine = 0, *frontLine = 0; DistributeLine( line, backLine, frontLine, lineHeap, bspTree ); int numLinesAfter = lineList.Count(); bspTree->postBspLineCount += numLinesAfter - numLinesBefore; if( backLine ) { if( !backNode ) backNode = bspTree->bspNodeHeap.AllocateFresh(); if( backNode ) backNode->Insert( backLine, lineHeap, bspTree ); } if( frontLine ) { if( !frontNode ) frontNode = bspTree->bspNodeHeap.AllocateFresh(); if( frontNode ) frontNode->Insert( frontLine, lineHeap, bspTree ); } } } //============================================================================= void GAVisToolRender::BspNode::Insert( Triangle* triangle, ObjectHeap< Triangle >& triangleHeap, BspTree* bspTree ) { if( !partitionPlaneCreated ) { triangleList.InsertLeftOf( 0, triangle ); VectorMath::CopyPlane( partitionPlane, triangle->trianglePlane ); partitionPlaneCreated = true; // Keep track of some stats. bspTree->postBspTriangleCount++; } else { int numTrianglesBefore = triangleList.Count(); Utilities::List backTriangleList, frontTriangleList; DistributeTriangle( triangle, backTriangleList, frontTriangleList, triangleHeap, bspTree ); int numTrianglesAfter = triangleList.Count(); bspTree->postBspTriangleCount += numTrianglesAfter - numTrianglesBefore; if( backTriangleList.Count() > 0 ) { if( !backNode ) backNode = bspTree->bspNodeHeap.AllocateFresh(); if( backNode ) { do { Triangle* triangle = ( Triangle* )backTriangleList.LeftMost(); backTriangleList.Remove( triangle, false ); backNode->Insert( triangle, triangleHeap, bspTree ); } while( backTriangleList.Count() > 0 ); } } if( frontTriangleList.Count() > 0 ) { if( !frontNode ) frontNode = bspTree->bspNodeHeap.AllocateFresh(); if( frontNode ) { do { Triangle* triangle = ( Triangle* )frontTriangleList.LeftMost(); frontTriangleList.Remove( triangle, false ); frontNode->Insert( triangle, triangleHeap, bspTree ); } while( frontTriangleList.Count() > 0 ); } } } } //============================================================================= void GAVisToolRender::BspTree::Draw( const VectorMath::Vector& cameraEye, GAVisToolRender& render ) { if( rootNode ) rootNode->Draw( cameraEye, render ); } //============================================================================= void GAVisToolRender::BspNode::Draw( const VectorMath::Vector& cameraEye, GAVisToolRender& render ) { BspNode* firstNode = 0; BspNode* lastNode = 0; switch( VectorMath::PlaneSide( partitionPlane, cameraEye ) ) { case VectorMath::Plane::SIDE_NEITHER: case VectorMath::Plane::SIDE_BACK: { firstNode = frontNode; lastNode = backNode; break; } case VectorMath::Plane::SIDE_FRONT: { firstNode = backNode; lastNode = frontNode; break; } } if( firstNode ) firstNode->Draw( cameraEye, render ); for( Triangle* triangle = ( Triangle* )triangleList.LeftMost(); triangle; triangle = ( Triangle* )triangle->Right() ) triangle->Draw( render.GetShading(), render.GetDoLighting(), render.ShowBspDetail() ); for( Line* line = ( Line* )lineList.LeftMost(); line; line = ( Line* )line->Right() ) line->Draw( render.GetDoLighting() ); if( lastNode ) lastNode->Draw( cameraEye, render ); } //============================================================================= const double GAVisToolRender::BspTree::HALF_PLANE_THICKNESS = 0.002; //============================================================================= GAVisToolRender::BspTree::BspTree( int bspNodeHeapSize ) : bspNodeHeap( bspNodeHeapSize ), bspAnalysisDataHeap( bspNodeHeapSize ) { } //============================================================================= GAVisToolRender::BspTree::~BspTree( void ) { } //============================================================================= void GAVisToolRender::BspTree::Destroy( void ) { for( int index = 0; index < bspNodeHeap.AllocationCount(); index++ ) { BspNode* node = bspNodeHeap.Access( index ); node->triangleList.RemoveAll( false ); node->lineList.RemoveAll( false ); } bspNodeHeap.FreeAll(); rootNode = 0; } // Minimal Cut BSP Tree // ==================== // // We could throw all the triangles into the BSP tree in any order // and get a BSP tree that would do proper alpha blending. However, // this tree may produce way more triangles than we really need. To // solve this problem, we want to find a BSP tree that can contain // all of our triangles with the fewest number of triangle cuts. An // idea for accomplishing this is to perform a recursive algorithm where // at each recursive iteration we choose from the set of best choices // for the root node at a sub-tree that is to contain all triangles that // will live in the half-space of the root node. In consideration of // which triangle should be the root, we need not compare it with any // triangles in the original set except for those that will live with // it in the same half-space. There seems to me to be two criteria // for choosing a sub-tree root node. The first is: how much damage // does a given triangle do in terms of triangle cuts to its fellow // triangles; and secondly, how much damage is there done to a given // triangle by its fellow members of the half-space? After selecting // all triangles that damage the least number of other half-space // members, we may choose among these which is damaged the most // by its fellow members. All of this seems like it would help to // minimize the number of triangle cuts in the finally constructed // tree, however, it would be interesting and nice if we could prove // that this or some other method really did give us one of the possible // minimially cut BSP trees. The proof would lie in knowing that the // choice we made for each sub-tree root was really the best choice, // or one of the best choices, for the entire sub-tree. //============================================================================= void GAVisToolRender::BspTree::Create( Utilities::List& triangleList, ObjectHeap< Triangle >& triangleHeap, Utilities::List& lineList, ObjectHeap< Line >& lineHeap, BspTreeCreationMethod creationMethod ) { preBspTriangleCount = triangleList.Count(); postBspTriangleCount = 0; preBspLineCount = lineList.Count(); postBspLineCount = 0; triangleSplitCount = 0; lineSplitCount = 0; if( creationMethod == RANDOM_TRIANGLE_INSERTION ) { while( triangleList.Count() > 0 ) { int randomIndex = rand() % triangleList.Count(); Triangle* triangle = ( Triangle* )triangleList[ randomIndex ]; triangleList.Remove( triangle, false ); if( !rootNode ) rootNode = bspNodeHeap.AllocateFresh(); if( rootNode ) rootNode->Insert( triangle, triangleHeap, this ); } } else if( creationMethod == ANALYZED_TRIANGLE_INSERTION ) { if( triangleList.Count() > 0 ) { AnalyzeTriangleList( triangleList ); if( !rootNode ) rootNode = bspNodeHeap.AllocateFresh(); if( rootNode ) rootNode->Insert( triangleList, triangleHeap, this ); bspAnalysisDataHeap.FreeAll(); } } // Once all triangles are in the BSP tree, we throw in the lines. // I'm just going to randomly throw these in and forgo any analysis. // We want lines in here too, because we want to do propery anti- // aliasing, which require proper alpha blending. while( lineList.Count() > 0 ) { int randomIndex = rand() % lineList.Count(); Line* line = ( Line* )lineList[ randomIndex ]; lineList.Remove( line, false ); if( !rootNode ) rootNode = bspNodeHeap.AllocateFresh(); if( rootNode ) rootNode->Insert( line, lineHeap, this ); } } //============================================================================= void GAVisToolRender::BspTree::AnalyzeTriangleList( Utilities::List& triangleList ) { for( Triangle* triangle = ( Triangle* )triangleList.LeftMost(); triangle; triangle = ( Triangle* )triangle->Right() ) { triangle->bspAnalysisData = bspAnalysisDataHeap.AllocateFresh(); triangle->bspAnalysisData->triangle = triangle; } // This is expensive! for( Triangle* triangle0 = ( Triangle* )triangleList.LeftMost(); triangle0; triangle0 = ( Triangle* )triangle0->Right() ) for( Triangle* triangle1 = ( Triangle* )triangle0->Right(); triangle1; triangle1 = ( Triangle* )triangle1->Right() ) AnalyzeTrianglePair( triangle0, triangle1 ); } //============================================================================= /*static*/ void GAVisToolRender::BspTree::AnalyzeTrianglePair( Triangle* triangle0, Triangle* triangle1 ) { if( triangle0->StraddlesPlane( triangle1->trianglePlane ) ) { triangle1->bspAnalysisData->trianglesSplitByThis.InsertRightOf( triangle1->bspAnalysisData->trianglesSplitByThis.RightMost(), triangle0->bspAnalysisData ); triangle0->bspAnalysisData->trianglesSplittingThis.InsertRightOf( triangle0->bspAnalysisData->trianglesSplittingThis.RightMost(), triangle1->bspAnalysisData ); } if( triangle1->StraddlesPlane( triangle0->trianglePlane ) ) { triangle0->bspAnalysisData->trianglesSplitByThis.InsertRightOf( triangle0->bspAnalysisData->trianglesSplitByThis.RightMost(), triangle1->bspAnalysisData ); triangle1->bspAnalysisData->trianglesSplittingThis.InsertRightOf( triangle1->bspAnalysisData->trianglesSplittingThis.RightMost(), triangle0->bspAnalysisData ); } } //============================================================================= bool GAVisToolRender::Triangle::StraddlesPlane( const VectorMath::Plane& plane ) const { VectorMath::SideCountData sideCountData; VectorMath::SideCount( triangle, plane, sideCountData, BspTree::HALF_PLANE_THICKNESS ); if( sideCountData.countOnFront > 0 && sideCountData.countOnBack > 0 ) return true; return false; } //============================================================================= GAVisToolRender::BspAnalysisData::BspAnalysisData( void ) { triangle = 0; } //============================================================================= /*virtual*/ GAVisToolRender::BspAnalysisData::~BspAnalysisData( void ) { } //============================================================================= void GAVisToolRender::BspAnalysisData::Reset( void ) { triangle = 0; } // Render.cpp
35.761208
176
0.647088
spencerparkin
20b3a6230986b886d86ef65657b634c9394a52db
265
cpp
C++
Engine/Source/Runtime/AIModule/Private/Perception/AISightTargetInterface.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/AIModule/Private/Perception/AISightTargetInterface.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/AIModule/Private/Perception/AISightTargetInterface.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "AIModulePrivate.h" #include "Perception/AISightTargetInterface.h" UAISightTargetInterface::UAISightTargetInterface(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { }
26.5
93
0.818868
PopCap
20b479b78885e0f0fb45bbd1798d4e0d44758c53
641
cpp
C++
src/main.cpp
EpicKiwi/Hero-fight
e3bae023006f25ffe0c4fc3f7141416c2b636da2
[ "MIT" ]
null
null
null
src/main.cpp
EpicKiwi/Hero-fight
e3bae023006f25ffe0c4fc3f7141416c2b636da2
[ "MIT" ]
null
null
null
src/main.cpp
EpicKiwi/Hero-fight
e3bae023006f25ffe0c4fc3f7141416c2b636da2
[ "MIT" ]
null
null
null
#include <iostream> #include "characters/Character.h" #include "characters/Warrior.h" #include "characters/Wizard.h" int main(int argc, char *argv[]) { Warrior bobby("Bobby"); bobby.sayHello(); cout << endl; Wizard tobby("Tobby"); tobby.sayHelloTo(bobby); cout << endl; cout << bobby.getName() << " frappe " << tobby.getName() << " avec " << bobby.getStrikes()[0]->getName() << endl; int amount = bobby.strike(tobby,0); cout << bobby.getName() << " à infligé " << to_string(amount) << " points de degats et " << tobby.getName() << " à maintenant " << tobby.getHealth() << " points de vie" << endl; }
30.52381
181
0.613105
EpicKiwi
20b9715992f88d1694fc0ecb8c9df1632683a1bc
12,804
cpp
C++
device/plugins/cpu_plugin/test/unittest/cpu_data_plugin_unittest.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
device/plugins/cpu_plugin/test/unittest/cpu_data_plugin_unittest.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
device/plugins/cpu_plugin/test/unittest/cpu_data_plugin_unittest.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
1
2021-09-13T11:17:44.000Z
2021-09-13T11:17:44.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 <cinttypes> #include <hwext/gtest-ext.h> #include <hwext/gtest-tag.h> #include <dlfcn.h> #include "cpu_data_plugin.h" #include "plugin_module_api.h" using namespace testing::ext; namespace { #if defined(__i386__) || defined(__x86_64__) const std::string DEFAULT_TEST_PATH = "./resources"; #else const std::string DEFAULT_TEST_PATH = "/data/local/tmp/resources"; #endif constexpr uint32_t BUF_SIZE = 4 * 1024 * 1024; const std::string SO_PATH = "/system/lib/libcpudataplugin.z.so"; constexpr int TEST_PID = 1; std::string g_path; std::string g_testPath; std::vector<int> g_tidList = {1872, 1965, 1966, 1967, 1968, 1995, 1996}; constexpr int CORE_NUM = 6; constexpr int THREAD_NUM = 7; struct TestSystemStat { int32_t core; int64_t user; int64_t nice; int64_t system; int64_t idle; int64_t iowait; int64_t irq; int64_t softirq; int64_t steal; }; struct TestStat { int64_t utime; int64_t stime; int64_t cutime; int64_t cstime; }; struct TestTidStat { int32_t tid; std::string name; ThreadState state; TestStat stat; }; struct TestFreq { int32_t curFreq; int32_t maxFreq; int32_t minFreq; }; TestSystemStat g_systemStat[CORE_NUM + 1] = { {-1, 24875428, 3952448, 11859815, 1193297105, 8980661, 0, 2607250, 0}, {0, 4165400, 662862, 1966195, 196987024, 3571925, 0, 817371, 0}, {1, 3861506, 676578, 1702753, 199535158, 1752008, 0, 401639, 0}, {2, 3549890, 676286, 1544630, 200640747, 1133743, 0, 205972, 0}, {3, 3336646, 676939, 1458898, 201176432, 854578, 0, 124812, 0}, {4, 4566158, 601107, 2305309, 197166395, 929594, 0, 1007959, 0}, {5, 5395826, 658673, 2882028, 197791346, 738811, 0, 49496, 0}, }; TestStat g_pidStat = {60, 10, 20, 30}; TestTidStat g_tidStat[THREAD_NUM] = { {1872, "ibus-x11", THREAD_RUNNING, {17, 5, 10, 10}}, {1965, "ibus-x1:disk$0", THREAD_SLEEPING, {8, 1, 5, 8}}, {1966, "ibus-x1:disk$1", THREAD_UNSPECIFIED, {0, 0, 0, 0}}, {1967, "ibus-x1:disk$2", THREAD_SLEEPING, {10, 1, 5, 8}}, {1968, "ibus-x1:disk$3", THREAD_STOPPED, {7, 0, 0, 0}}, {1995, "gmain", THREAD_SLEEPING, {15, 3, 0, 4}}, {1996, "gdbus", THREAD_WAITING, {5, 0, 0, 0}}, }; TestFreq g_Freq[CORE_NUM + 1] = { {1018, 3844, 509}, {1023, 2844, 509}, {1011, 3844, 509}, {1518, 3844, 1018}, {1245, 1844, 1018}, {1767, 3044, 1018}, }; class CpuDataPluginTest : public ::testing::Test { public: static void SetUpTestCase() {} static void TearDownTestCase() { if (access(g_testPath.c_str(), F_OK) == 0) { std::string str = "rm -rf " + g_testPath; printf("TearDown--> %s\r\n", str.c_str()); system(str.c_str()); } } }; string Getexepath() { char buf[PATH_MAX] = ""; std::string path = "/proc/self/exe"; size_t rslt = readlink(path.c_str(), buf, sizeof(buf)); if (rslt < 0 || (rslt >= sizeof(buf))) { return ""; } buf[rslt] = '\0'; for (int i = rslt; i >= 0; i--) { if (buf[i] == '/') { buf[i + 1] = '\0'; break; } } return buf; } std::string GetFullPath(std::string path) { if (path.size() > 0 && path[0] != '/') { return Getexepath() + path; } return path; } #if defined(__i386__) || defined(__x86_64__) bool CreatTestResource(std::string path, std::string exepath) { std::string str = "cp -r " + path + " " + exepath; printf("CreatTestResource:%s\n", str.c_str()); pid_t status = system(str.c_str()); if (-1 == status) { printf("system error!"); } else { printf("exit status value = [0x%x]\n", status); if (WIFEXITED(status)) { if (WEXITSTATUS(status) == 0) { return true; } else { printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status)); return false; } } else { printf("exit status = [%d]\n", WEXITSTATUS(status)); return true; } } return false; } #endif bool CheckTid(std::vector<int>& tidListTmp) { sort(g_tidList.begin(), g_tidList.end()); for (size_t i = 0; i < g_tidList.size(); i++) { if (tidListTmp.at(i) != g_tidList.at(i)) { return false; } } return true; } bool PluginCpuinfoStub(CpuDataPlugin& cpuPlugin, CpuData& cpuData, int pid, bool unusualBuff) { CpuConfig protoConfig; protoConfig.set_pid(pid); // serialize std::vector<uint8_t> configData(protoConfig.ByteSizeLong()); int ret = protoConfig.SerializeToArray(configData.data(), configData.size()); // start ret = cpuPlugin.Start(configData.data(), configData.size()); if (ret < 0) { return false; } printf("ut: serialize success start plugin ret = %d\n", ret); // report std::vector<uint8_t> bufferData(BUF_SIZE); if (unusualBuff) { // buffer异常,调整缓冲区长度为1,测试异常情况 bufferData.resize(1, 0); printf("ut: bufferData resize\n"); } ret = cpuPlugin.Report(bufferData.data(), bufferData.size()); if (ret > 0) { cpuData.ParseFromArray(bufferData.data(), ret); return true; } return false; } void GetSystemCpuTime(TestSystemStat& stat, int64_t Hz, int64_t& usageTime, int64_t& time) { usageTime = (stat.user + stat.nice + stat.system + stat.irq + stat.softirq + stat.steal) * Hz; time = (usageTime + stat.idle + stat.iowait) * Hz; } /** * @tc.name: cpu plugin * @tc.desc: Test whether the path exists. * @tc.type: FUNC */ HWTEST_F(CpuDataPluginTest, TestPath, TestSize.Level1) { g_path = GetFullPath(DEFAULT_TEST_PATH); g_testPath = g_path; printf("g_path:%s\n", g_path.c_str()); EXPECT_NE("", g_path); #if defined(__i386__) || defined(__x86_64__) if (DEFAULT_TEST_PATH != g_path) { if ((access(g_path.c_str(), F_OK) != 0) && (access(DEFAULT_TEST_PATH.c_str(), F_OK) == 0)) { EXPECT_TRUE(CreatTestResource(DEFAULT_TEST_PATH, g_path)); } } #endif } /** * @tc.name: cpu plugin * @tc.desc: Tid list test in a specific directory. * @tc.type: FUNC */ HWTEST_F(CpuDataPluginTest, TestTidlist, TestSize.Level1) { CpuDataPlugin cpuPlugin; std::string path = g_path + "/proc/1872/task/"; printf("path:%s\n", path.c_str()); DIR* dir = cpuPlugin.OpenDestDir(path); EXPECT_NE(nullptr, dir); std::vector<int> tidListTmp; while (int32_t pid = cpuPlugin.GetValidTid(dir)) { tidListTmp.push_back(pid); sort(tidListTmp.begin(), tidListTmp.end()); } EXPECT_TRUE(CheckTid(tidListTmp)); } /** * @tc.name: cpu plugin * @tc.desc: a part of cpu information test for specific pid. * @tc.type: FUNC */ HWTEST_F(CpuDataPluginTest, TestPluginInfo, TestSize.Level1) { CpuDataPlugin cpuPlugin; CpuData cpuData; cpuPlugin.SetFreqPath(g_path); g_path += "/proc/"; cpuPlugin.SetPath(g_path); EXPECT_TRUE(PluginCpuinfoStub(cpuPlugin, cpuData, 1872, false)); int64_t systemCpuTime = 0; int64_t systemBootTime = 0; int64_t Hz = cpuPlugin.GetUserHz(); printf("Hz : %" PRId64 "\n", Hz); int64_t processCpuTime = (g_pidStat.utime + g_pidStat.stime + g_pidStat.cutime + g_pidStat.cstime) * Hz; GetSystemCpuTime(g_systemStat[0], Hz, systemCpuTime, systemBootTime); CpuUsageInfo cpuUsageInfo = cpuData.cpu_usage_info(); EXPECT_EQ(cpuUsageInfo.prev_process_cpu_time_ms(), 0); EXPECT_EQ(cpuUsageInfo.prev_system_cpu_time_ms(), 0); EXPECT_EQ(cpuUsageInfo.prev_system_boot_time_ms(), 0); EXPECT_EQ(cpuUsageInfo.process_cpu_time_ms(), processCpuTime); EXPECT_EQ(cpuUsageInfo.system_cpu_time_ms(), systemCpuTime); printf("systemCpuTime = %" PRId64 "\n", systemCpuTime); EXPECT_EQ(cpuUsageInfo.system_boot_time_ms(), systemBootTime); printf("systemBootTime = %" PRId64 "\n", systemBootTime); ASSERT_EQ(cpuUsageInfo.cores_size(), 6); for (int i = 1; i <= CORE_NUM; i++) { CpuCoreUsageInfo cpuCoreUsageInfo = cpuUsageInfo.cores()[i - 1]; GetSystemCpuTime(g_systemStat[i], Hz, systemCpuTime, systemBootTime); EXPECT_EQ(cpuCoreUsageInfo.cpu_core(), g_systemStat[i].core); EXPECT_EQ(cpuCoreUsageInfo.prev_system_cpu_time_ms(), 0); EXPECT_EQ(cpuCoreUsageInfo.prev_system_boot_time_ms(), 0); EXPECT_EQ(cpuCoreUsageInfo.system_cpu_time_ms(), systemCpuTime); EXPECT_EQ(cpuCoreUsageInfo.system_boot_time_ms(), systemBootTime); EXPECT_EQ(cpuCoreUsageInfo.frequency().min_frequency_khz(), g_Freq[i - 1].minFreq); EXPECT_EQ(cpuCoreUsageInfo.frequency().max_frequency_khz(), g_Freq[i - 1].maxFreq); EXPECT_EQ(cpuCoreUsageInfo.frequency().cur_frequency_khz(), g_Freq[i - 1].curFreq); if (i == 1) { // cpu0为大核 EXPECT_EQ(cpuCoreUsageInfo.is_little_core(), false); } else { EXPECT_EQ(cpuCoreUsageInfo.is_little_core(), true); } } } /** * @tc.name: cpu plugin * @tc.desc: cpu information test for specific pid. * @tc.type: FUNC */ HWTEST_F(CpuDataPluginTest, TestPlugin, TestSize.Level1) { CpuDataPlugin cpuPlugin; CpuData cpuData; g_path = g_testPath; cpuPlugin.SetFreqPath(g_path); g_path += "/proc/"; cpuPlugin.SetPath(g_path); EXPECT_TRUE(PluginCpuinfoStub(cpuPlugin, cpuData, 1872, false)); int64_t Hz = cpuPlugin.GetUserHz(); int64_t threadCpuTime; ASSERT_EQ(cpuData.thread_info_size(), 7); for (int i = 0; i < THREAD_NUM; i++) { threadCpuTime = (g_tidStat[i].stat.utime + g_tidStat[i].stat.stime + g_tidStat[i].stat.cutime + g_tidStat[i].stat.cstime) * Hz; ThreadInfo threadInfo = cpuData.thread_info()[i]; EXPECT_EQ(threadInfo.tid(), g_tidStat[i].tid); EXPECT_STREQ(threadInfo.thread_name().c_str(), g_tidStat[i].name.c_str()); EXPECT_EQ(threadInfo.thread_state(), g_tidStat[i].state); EXPECT_EQ(threadInfo.thread_cpu_time_ms(), threadCpuTime); EXPECT_EQ(threadInfo.prev_thread_cpu_time_ms(), 0); } EXPECT_EQ(cpuPlugin.Stop(), 0); // 缓冲区异常 EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin, cpuData, 1872, true)); EXPECT_EQ(cpuPlugin.Stop(), 0); } /** * @tc.name: cpu plugin * @tc.desc: cpu information test for unusual path. * @tc.type: FUNC */ HWTEST_F(CpuDataPluginTest, TestPluginBoundary, TestSize.Level1) { CpuDataPlugin cpuPlugin; CpuData cpuData; g_path += "/proc/"; cpuPlugin.SetPath(g_path); EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin, cpuData, -1, false)); EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin, cpuData, 12345, false)); CpuDataPlugin cpuPlugin2; cpuPlugin2.SetPath("123"); EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin2, cpuData, 1872, false)); EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin2, cpuData, -1, false)); EXPECT_FALSE(PluginCpuinfoStub(cpuPlugin2, cpuData, 12345, false)); } /** * @tc.name: cpu plugin * @tc.desc: cpu plugin registration test. * @tc.type: FUNC */ HWTEST_F(CpuDataPluginTest, TestPluginRegister, TestSize.Level1) { void* handle = dlopen(SO_PATH.c_str(), RTLD_LAZY); ASSERT_NE(handle, nullptr); PluginModuleStruct* cpuPlugin = (PluginModuleStruct*)dlsym(handle, "g_pluginModule"); ASSERT_NE(cpuPlugin, nullptr); EXPECT_STREQ(cpuPlugin->name, "cpu-plugin"); EXPECT_EQ(cpuPlugin->resultBufferSizeHint, BUF_SIZE); // Serialize config CpuConfig protoConfig; protoConfig.set_pid(TEST_PID); int configLength = protoConfig.ByteSizeLong(); ASSERT_GT(configLength, 0); std::vector<uint8_t> configBuffer(configLength); EXPECT_TRUE(protoConfig.SerializeToArray(configBuffer.data(), configLength)); // run plugin std::vector<uint8_t> dataBuffer(cpuPlugin->resultBufferSizeHint); EXPECT_EQ(cpuPlugin->callbacks->onPluginSessionStart(configBuffer.data(), configLength), RET_SUCC); ASSERT_GT(cpuPlugin->callbacks->onPluginReportResult(dataBuffer.data(), cpuPlugin->resultBufferSizeHint), 0); EXPECT_EQ(cpuPlugin->callbacks->onPluginSessionStop(), 0); // 反序列化失败导致的start失败 EXPECT_EQ(cpuPlugin->callbacks->onPluginSessionStart(configBuffer.data(), configLength+1), RET_FAIL); } } // namespace
32.090226
120
0.658466
openharmony-gitee-mirror
20b975eab6655b804b6e51d9954e802b1fe52f69
686
cpp
C++
All About C/Pointers/4. Arithmatic Operation 1.cpp
tausiq2003/C-with-DS
3ec324b180456116b03aec58f2a85025180af9aa
[ "Apache-2.0" ]
7
2020-10-01T13:31:02.000Z
2021-11-06T16:22:31.000Z
All About C/Pointers/4. Arithmatic Operation 1.cpp
tausiq2003/C-with-DS
3ec324b180456116b03aec58f2a85025180af9aa
[ "Apache-2.0" ]
9
2020-10-01T10:35:59.000Z
2021-10-03T15:00:18.000Z
All About C/Pointers/4. Arithmatic Operation 1.cpp
tausiq2003/C-with-DS
3ec324b180456116b03aec58f2a85025180af9aa
[ "Apache-2.0" ]
44
2020-10-01T08:49:30.000Z
2021-10-31T18:19:48.000Z
#include<iostream> using namespace std; int main(){ int A[]{1,2,3,4,5,6}; int *p=A; //base address of A is given to pointer P. cout<<*p<<endl; cout<<p<<endl; // output will be 1 and address p++; //writing *p++ is not necessory. cout<<*p<<endl; // * is used for derefrencing, it will print address without * cout<<p<<endl; // output will be next digit with address, In pointer value shift either left or right., and value doesn't increment or decrement using ++ or --. //output = 2 p--; //writing *p++ is not necessory. cout<<*p<<endl; cout<<p<<endl; // output =1 with address cout<<*p<<endl; cout<<*(p+2)<<endl; // *p = let say 1., then *(p+2)=3 return 0; }
19.6
145
0.625364
tausiq2003
20be09e4c096718daf43243eb9724aeaaed76ec1
1,508
cpp
C++
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter3Exercise6.cpp
Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
9
2018-10-24T15:16:47.000Z
2021-12-14T13:53:50.000Z
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter3Exercise6.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
null
null
null
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter3Exercise6.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
7
2018-10-29T15:30:37.000Z
2021-01-18T15:15:09.000Z
/* TITLE Comparison & Ordering Chapter3Exercise6.cpp Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: Put in order three input numbers; Next to each other if they are equal. Input: Requests 3 numbers. Output: Prints numbers in order. Author: Chris B. Kirov Date: 01.02.2014 */ #include "../../std_lib_facilities.h" int main() { cout << "Please enter three numbers." << endl; cout << "The first number:\t" << endl; int var1 = 0; cin >> var1; cout << "The second number:\t" << endl; int var2 = 0; cin >> var2; cout << "The third number:\t" << endl; int var3 = 0; cin >> var3; // Brute force (all possible permutations) = 3! => (number of comparisons) = 6 string res_msg = "The numbers in ascending order are: "; if (var1 <= var2 && var2 <= var3) { cout << res_msg << var1 << ',' << var2 << ',' << var3 << endl; } else if (var1 >= var2 && var1 <= var3) { cout << res_msg << var2 << ',' << var1 << ',' << var3 << endl; } else if (var1 > var2 && var1 >= var3 && var2 <= var3) { cout << res_msg << var2 << ',' << var3 << ',' << var1 << endl; } else if (var1 >= var2 && var2 >= var3) { cout << res_msg << var3 << ',' << var2 << ',' << var1 << endl; } else if (var1 >= var3 && var1 >= var2) { cout << res_msg << var3 << ',' << var1 << ',' << var3 << endl; } else if (var1 <= var3 && var3 <= var2) { cout << res_msg << var1 << ',' << var3 << ',' << var2 << endl; } return 0; }
25.559322
80
0.547082
Ziezi
20be582a26d284e303c4f964404cc071d7226025
694
cpp
C++
problem_solving/SPOJ/OPCPIZZA/14158584_AC_180ms_16384kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
2
2020-09-02T12:07:47.000Z
2020-11-17T11:17:16.000Z
problem_solving/SPOJ/OPCPIZZA/14158584_AC_180ms_16384kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
null
null
null
problem_solving/SPOJ/OPCPIZZA/14158584_AC_180ms_16384kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
4
2020-08-11T14:23:34.000Z
2020-11-17T10:52:31.000Z
#include <bits/stdc++.h> #define le 100005 using namespace std; int n[le]; bool fnc(int a, int b, int key){ int lo = a + 1, hi = b - 1, mid; while(lo <= hi){ mid = (lo + hi) >> 1; if(n[mid] == key) return 1; else if(n[mid] > key) hi = mid - 1; else lo = mid + 1; } return 0; } int main(){ int t, len, m; for(scanf("%d", &t); t--; ){ scanf("%d %d", &len, &m); for(int i = 0; i < len; scanf("%d", &n[i]), i++); sort(n, n + len); int c = 0; for(int i = 0; i < len - 1; i++){ int ve = m - n[i]; if(fnc(i, len, ve)) c++; } printf("%d\n", c); } return 0; }
23.931034
57
0.402017
cosmicray001
20be7c71644405fc4ff4703bb47fd3432d191d0f
15,016
cpp
C++
src/density/nearest_neighbor_density.cpp
cogsys-tuebingen/muse_armcl
63eb0c8d3a1d03d84222acbb5b0c9978065bcc3c
[ "BSD-3-Clause" ]
5
2020-01-19T09:35:28.000Z
2021-11-04T10:08:24.000Z
src/density/nearest_neighbor_density.cpp
cxdcxd/muse_armcl
63eb0c8d3a1d03d84222acbb5b0c9978065bcc3c
[ "BSD-3-Clause" ]
null
null
null
src/density/nearest_neighbor_density.cpp
cxdcxd/muse_armcl
63eb0c8d3a1d03d84222acbb5b0c9978065bcc3c
[ "BSD-3-Clause" ]
1
2019-11-10T23:40:59.000Z
2019-11-10T23:40:59.000Z
#include <muse_armcl/density/sample_density.hpp> #include <unordered_map> #include <cslibs_math/statistics/weighted_distribution.hpp> #include <sensor_msgs/PointCloud2.h> #include <cslibs_math_3d/linear/pointcloud.hpp> #include <cslibs_math/color/color.hpp> #include <cslibs_math_ros/sensor_msgs/conversion_3d.hpp> namespace muse_armcl { class EIGEN_ALIGN16 NearestNeighborDensity : public muse_armcl::SampleDensity { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW using vertex_t = cslibs_mesh_map::MeshMap::VertexHandle; using distribution_t = cslibs_math::statistics::WeightedDistribution<double,3>; struct EIGEN_ALIGN16 vertex_distribution { EIGEN_MAKE_ALIGNED_OPERATOR_NEW using allocator_t = Eigen::aligned_allocator<vertex_distribution>; using Ptr = std::shared_ptr<vertex_distribution>; vertex_t handle; distribution_t distribution; int cluster_id = 0; std::set<sample_t const*> samples; }; struct EIGEN_ALIGN16 cluster_distribution { EIGEN_MAKE_ALIGNED_OPERATOR_NEW using allocator_t = Eigen::aligned_allocator<cluster_distribution>; using Ptr = std::shared_ptr<cluster_distribution>; std::size_t map_id; distribution_t distribution; std::set<sample_t const*> samples; std::set<int> vertex_ids; }; using vertex_distributions_t = std::unordered_map<std::size_t, std::unordered_map<int, vertex_distribution::Ptr>>; using vertex_labels_t = std::unordered_map<int, int>; using cluster_map_t = std::unordered_map<int, cluster_distribution::Ptr>; void setup(const map_provider_map_t &map_providers, ros::NodeHandle &nh) override { auto param_name = [this](const std::string &name){return name_ + "/" + name;}; ignore_weight_ = nh.param(param_name("ignore_weight"), false); radius_ = nh.param(param_name("radius"), 0.1); radius_ *= radius_; relative_weight_threshold_ = nh.param(param_name("relative_weight_threshold"), 0.8); n_contacts_ = nh.param(param_name("number_of_contacts"), 10); min_cluster_size_ = nh.param(param_name("min_cluster_size"), 10); const std::string map_provider_id = nh.param<std::string>("map", ""); /// toplevel parameter if (map_provider_id == "") throw std::runtime_error("[SampleDensity]: No map provider was found!"); if (map_providers.find(map_provider_id) == map_providers.end()) throw std::runtime_error("[SampleDensity]: Cannot find map provider '" + map_provider_id + "'!"); map_provider_ = map_providers.at(map_provider_id); pub_ = nh.advertise<sensor_msgs::PointCloud2>("cluster_cloud",1); } std::size_t histogramSize() const override { return vertex_distributions_.size(); } void publishClusters(const cslibs_mesh_map::MeshMapTree* map) const { std::shared_ptr<cslibs_math_3d::PointcloudRGB3d> part_cloud(new cslibs_math_3d::PointcloudRGB3d); /// publish all particles for(auto &c : clusters_) { cslibs_math::color::Color<double> ccolor = cslibs_math::color::random<double>(); for(const sample_t* s : c.second->samples) { if(c.second->samples.size() < min_cluster_size_) continue; const cslibs_mesh_map::MeshMapTreeNode* p_map = map->getNode(s->state.map_id); if (p_map) { cslibs_math_3d::Transform3d T = map->getTranformToBase(p_map->map.frame_id_); cslibs_math_3d::Point3d pos = s->state.getPosition(p_map->map); pos = T * pos; cslibs_math_3d::PointRGB3d point(pos, 0.9f, ccolor); part_cloud->insert(point); } } } sensor_msgs::PointCloud2 cloud; cslibs_math_ros::sensor_msgs::conversion_3d::from<double>(part_cloud, cloud); cloud.header.frame_id = map->front()->frameId(); cloud.header.stamp = ros::Time::now(); pub_.publish(cloud); } void contacts(sample_vector_t &states) const override { const muse_smc::StateSpace<StateSpaceDescription>::ConstPtr ss = map_provider_->getStateSpace(); if (!ss->isType<MeshMap>()) return; using mesh_map_tree_t = cslibs_mesh_map::MeshMapTree; const mesh_map_tree_t *map = ss->as<MeshMap>().data(); auto get_nearest = [&map](const cluster_distribution &c, double& likely, double& sum_weight) { double min_distance = std::numeric_limits<double>::max(); sum_weight = 0; likely = 0; sample_t const * sample = nullptr; const Eigen::Vector3d mean = c.distribution.getMean(); for(const sample_t* s : c.samples) { const Eigen::Vector3d pos = s->state.getPosition(map->getNode(s->state.map_id)->map); const double distance = (mean - pos).squaredNorm(); // std::cout << s->state.map_id << std::endl; sum_weight += s->weight; likely += s->state.last_update; if(distance < min_distance) { min_distance = distance; sample = s; } } // sum_weight *= c.samples.size(); return sample; }; // std::cout << "====="<< std::endl; // double mean_weight = 0; // double max_weight = 0; // cluster_distribution::Ptr max; // for(auto &c : clusters_) { // const cluster_distribution::Ptr &d = c.second; // const double w = d->distribution.getWeight(); // mean_weight += w; // if(w > max_weight) { // max_weight = w; // max = d; // } // } // std::cout << clusters_.size() << std::endl; // mean_weight /= static_cast<double>(clusters_.size()); /// iterate the clusters and find the point nearest to the mean to estimate the contact /// mean cluster weights ... // std::map<double, std::map<double, std::map<std::size_t,std::vector<sample_t>>>> candidates; std::map<double, std::vector<sample_t, sample_t::allocator_t>> candidates; for(auto &c : clusters_) { if(c.second->samples.size() < min_cluster_size_) continue; /// drop a cluster if it is not weighted high enough compared to the others // if(c.second->distribution.getWeight() * relative_weight_threshold_ < mean_weight) // continue; double weight = 0; double likely = 0; sample_t const * s = get_nearest(*c.second, likely, weight); if( s != nullptr){ candidates[weight]/*[weight][c.second->samples.size()]*/.emplace_back(*s); // states.emplace_back(*s); // std::cout << c.first << " " << weight << " " << c.second->samples.size() << std::endl; } } states.clear(); auto it = candidates.rbegin(); while(states.size() < std::min(n_contacts_, clusters_.size()) && it != candidates.rend()){ std::size_t remaining = n_contacts_ - states.size(); if(it->second.size() > remaining){ std::map<double, std::vector<sample_t, sample_t::allocator_t>> cand2; for(auto s = it->second.begin(); s < it->second.end(); ++s){ cand2[s->state.last_update].emplace_back(*s); } auto it2 = cand2.rbegin(); while(states.size() < std::min(n_contacts_, clusters_.size()) && it2 != cand2.rend()){ std::size_t remaining = n_contacts_ - states.size(); if(it2->second.size() > remaining){ states.insert(states.end(), it2->second.begin(), it2->second.begin() + remaining); } else{ states.insert(states.end(), it2->second.begin(), it2->second.end()); } ++it2; } } else{ states.insert(states.end(), it->second.begin(), it->second.end()); } ++it; } // std::cout << " # clusters " << clusters_.size() << " # states: " << states.size() << std::endl; publishClusters(map); } void clear() override { vertex_distributions_.clear(); clusters_.clear(); vertex_labels_.clear(); } void insert(const sample_t &sample) override { const double s = sample.state.s; const auto &goal_handle = sample.state.goal_vertex; const auto &acti_handle = sample.state.active_vertex; const int id = s < 0.5 ? acti_handle.idx() : goal_handle.idx(); const std::size_t map_id = sample.state.map_id; vertex_distribution::Ptr &d = vertex_distributions_[map_id][id]; if(!d) { d.reset(new vertex_distribution); d->handle = s < 0.5 ? acti_handle : goal_handle; } const muse_smc::StateSpace<StateSpaceDescription>::ConstPtr ss = map_provider_->getStateSpace(); if (!ss->isType<MeshMap>()) return; using mesh_map_tree_t = cslibs_mesh_map::MeshMapTree; const mesh_map_tree_t *map = ss->as<MeshMap>().data(); const cslibs_math_3d::Vector3d pos = sample.state.getPosition(map->getNode(sample.state.map_id)->map); d->distribution.add(pos.data(), sample.weight); d->samples.insert(&sample); } void estimate() override { const muse_smc::StateSpace<StateSpaceDescription>::ConstPtr ss = map_provider_->getStateSpace(); if (!ss->isType<MeshMap>()) return; using mesh_map_tree_t = cslibs_mesh_map::MeshMapTree; const mesh_map_tree_t *map = ss->as<MeshMap>().data(); int cluster_id = 0; /// clustering by map for(auto &vd : vertex_distributions_) { for(auto &v : vd.second) { vertex_distribution::Ptr &d = v.second; if(d->cluster_id != 0) continue; const cslibs_mesh_map::MeshMapTreeNode* state_map = map->getNode(vd.first); const auto& neighbors = state_map->map.getNeighbors(d->handle); std::set<int> found_labels; for(const auto& n : neighbors){ int l = vertex_labels_[n.idx()]; found_labels.emplace(l); } found_labels.erase(0); if(found_labels.size() == 0) { /// the current node is alone ... ++cluster_id; d->cluster_id = cluster_id; cluster_distribution::Ptr &cd = clusters_[cluster_id]; cd.reset(new cluster_distribution); cd->samples = d->samples; cd->map_id = vd.first; vertex_labels_[d->handle.idx()]; for(const auto &n : neighbors) { vertex_labels_[n.idx()] = cluster_id; cd->vertex_ids.emplace(n.idx()); } cd->distribution = d->distribution; cd->vertex_ids.emplace(d->handle.idx()); } else if(found_labels.size() == 1) { const int fl = *(found_labels.begin()); cluster_distribution::Ptr &cd = clusters_[fl]; cd->samples.insert(d->samples.begin(), d->samples.end()); cd->distribution += d->distribution; cd->vertex_ids.emplace(d->handle.idx()); vertex_labels_[d->handle.idx()] = fl; } else { /// merge clusters /// biggest cluster so far std::size_t large_count = 0; int large_label = 0; cluster_distribution::Ptr large_cluster = nullptr; for(const int fl : found_labels) { cluster_distribution::Ptr &cd = clusters_[fl]; std::size_t cs = cd->vertex_ids.size(); if(cs > large_count) { large_count = cs; large_label = fl; large_cluster = cd; } } /// add other clusters found_labels.erase(large_label); for(const int fl : found_labels) { cluster_distribution::Ptr &cd = clusters_[fl]; large_cluster->distribution += cd->distribution; for(const int n : cd->vertex_ids) { vertex_labels_[n] = large_label; } large_cluster->samples.insert(cd->samples.begin(), cd->samples.end()); large_cluster->vertex_ids.insert(cd->vertex_ids.begin(), cd->vertex_ids.end()); clusters_.erase(fl); } /// add new node and neighbors large_cluster->samples.insert(d->samples.begin(), d->samples.end()); large_cluster->distribution += d->distribution; large_cluster->vertex_ids.emplace(d->handle.idx()); for(const auto &n : neighbors) { vertex_labels_[n.idx()] = large_label; large_cluster->vertex_ids.emplace(n.idx()); } } } vertex_labels_.clear(); ++cluster_id; } } private: vertex_distributions_t vertex_distributions_; vertex_labels_t vertex_labels_; cluster_map_t clusters_; MeshMapProvider::Ptr map_provider_; bool ignore_weight_; double radius_; double relative_weight_threshold_; std::size_t n_contacts_; mutable ros::Publisher pub_; int min_cluster_size_; }; } #include <class_loader/class_loader_register_macro.h> CLASS_LOADER_REGISTER_CLASS(muse_armcl::NearestNeighborDensity, muse_armcl::SampleDensity)
42.780627
110
0.533897
cogsys-tuebingen
20c020d145b9af195f2e069547fbfab8c1f1c5b7
753
cpp
C++
Modules/Module10/SampleCode/a_basics/Example8_ConcatenationAndAppending.cpp
hackettccp/CSCI112
103893f5c3532839f6b0a8ff460f069b324bc199
[ "MIT" ]
3
2019-10-23T03:25:31.000Z
2021-02-23T04:08:59.000Z
Modules/Module10/SampleCode/a_basics/Example8_ConcatenationAndAppending.cpp
hackettccp/CSCI112
103893f5c3532839f6b0a8ff460f069b324bc199
[ "MIT" ]
null
null
null
Modules/Module10/SampleCode/a_basics/Example8_ConcatenationAndAppending.cpp
hackettccp/CSCI112
103893f5c3532839f6b0a8ff460f069b324bc199
[ "MIT" ]
null
null
null
/** * Demonstrates concatenating and appending Strings * */ #include <iostream> using namespace std; /** * Main Function. */ int main() { string part1 = "Hello"; //std::string if std namespace is not used. string part2 = "World!"; string output = part1 + " " + part2; //Same process as Java for concatenation cout << "Value of output (result of concatenation): " + output + "\n" << endl; part1 += " "; //Same process as Java for appending part1 += part2; cout << "Value of part1 (result of appending): " + part1 << endl; return 0; }
31.375
131
0.472776
hackettccp
20c083c60bc05f9a0c0cc3e8f1f6fdf391477339
2,743
cpp
C++
src/Network/NetworkDevice.cpp
Harsh14901/COP290-Pacman
e9f821f0351a0ead5ed89becab81a3c8c0a7c18e
[ "BSD-3-Clause" ]
null
null
null
src/Network/NetworkDevice.cpp
Harsh14901/COP290-Pacman
e9f821f0351a0ead5ed89becab81a3c8c0a7c18e
[ "BSD-3-Clause" ]
null
null
null
src/Network/NetworkDevice.cpp
Harsh14901/COP290-Pacman
e9f821f0351a0ead5ed89becab81a3c8c0a7c18e
[ "BSD-3-Clause" ]
null
null
null
#include "Network/NetworkDevice.hpp" #include "Network/Packet.hpp" const int NetworkDevice::MAX_BUFFER; NetworkDevice::NetworkDevice() { recv_socket = nullptr; send_socket = nullptr; ps_buffer = queue<PacketStore>(); } NetworkDevice::NetworkDevice(TCPsocket* recv_socket, TCPsocket* send_socket) : recv_socket(recv_socket), send_socket(send_socket) {} bool NetworkDevice::packet_ready() { return !ps_buffer.empty(); } void NetworkDevice::get_packets(PacketStore& ps) { ps = ps_buffer.front(); ps_buffer.pop(); } void NetworkDevice::recv() { char buffer[MAX_BUFFER]; // cout << "NetworkDevice::recv() called" << endl; if (SDLNet_TCP_Recv(*recv_socket, buffer, MAX_BUFFER) > 0) { // printf("packet data recieved: %s\n", buffer); auto ps = PacketStore(); ps.decode(buffer); ps_buffer.push(ps); } // printf("buffer size: %ld\n", ps_buffer.size()); } int NetworkDevice::send(PacketStore& ps) { char buffer[MAX_BUFFER]; int n = ps.encode(buffer); int size = strlen(buffer) + 1; // printf("Sending buffer: %s\n", buffer); if (SDLNet_TCP_Send(*send_socket, buffer, size) < size) { fatalError("Error sending packet store: " + string(SDLNet_GetError()), false); network_error = true; } else { // cout << "packet store sent" << endl; } return n; } Server::Server(int port) : NetworkDevice(&csd, &csd), port(port) {} Server::Server() : Server(PORT) {} void Server::init() { if (SDLNet_ResolveHost(&ip, NULL, port) < 0) { fatalError("SDLNet_ResolveHost: " + string(SDLNet_GetError()), false); network_error = true; } if (!(sd = SDLNet_TCP_Open(&ip))) { fatalError("SDLNet_TCP_Open: " + string(SDLNet_GetError()), false); network_error = true; } } void Server::wait_for_connection() { if ((csd = SDLNet_TCP_Accept(sd))) { IPaddress* remote_ip_ptr; if ((remote_ip_ptr = SDLNet_TCP_GetPeerAddress(csd))) { remote_ip = *remote_ip_ptr; printf("[+] Host connected: %x %d\n", SDLNet_Read32(&(remote_ip.host)), SDLNet_Read16(&(remote_ip.port))); connected = true; } else { fatalError("SDLNet_TCP_GetPeerAddress: " + string(SDLNet_GetError()), false); network_error = true; } } } bool Server::is_connected() { return connected; } Client::Client(string server_host, int port) : NetworkDevice(&sd, &sd), server_host(server_host), port(port) {} Client::Client() : Client("", PORT) {} void Client::init() { if (SDLNet_ResolveHost(&server_ip, server_host.c_str(), port) < 0) { fatalError("SDLNet_ResolveHost:" + string(SDLNet_GetError()), false); network_error = true; } } void Client::connect() { while (!(sd = SDLNet_TCP_Open(&server_ip))) ; }
28.278351
77
0.65731
Harsh14901
20c0cb79b7ebfbf47fa19688903bde1eec2ce3f1
4,775
cpp
C++
gui/renderers/VolumeRenderer.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
20
2021-04-02T04:30:08.000Z
2022-03-01T09:52:01.000Z
gui/renderers/VolumeRenderer.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
null
null
null
gui/renderers/VolumeRenderer.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
1
2022-01-22T11:44:52.000Z
2022-01-22T11:44:52.000Z
#include "gui/renderers/VolumeRenderer.h" #include "gui/Factory.h" #include "gui/objects/Camera.h" #include "gui/objects/Colorizer.h" #include "gui/renderers/FrameBuffer.h" #include "objects/finders/KdTree.h" #include "objects/utility/OutputIterators.h" NAMESPACE_SPH_BEGIN VolumeRenderer::VolumeRenderer(SharedPtr<IScheduler> scheduler, const GuiSettings& settings) : IRaytracer(scheduler, settings) {} VolumeRenderer::~VolumeRenderer() = default; const float MAX_DISTENTION = 50; const float MIN_NEIGHS = 8; void VolumeRenderer::initialize(const Storage& storage, const IColorizer& colorizer, const ICamera& UNUSED(camera)) { cached.r = storage.getValue<Vector>(QuantityId::POSITION).clone(); this->setColorizer(colorizer); cached.distention.resize(cached.r.size()); KdTree<KdNode> tree; tree.build(*scheduler, cached.r, FinderFlag::SKIP_RANK); Array<BvhSphere> spheres(cached.r.size()); spheres.reserve(cached.r.size()); ThreadLocal<Array<NeighborRecord>> neighs(*scheduler); parallelFor(*scheduler, neighs, 0, cached.r.size(), [&](const Size i, Array<NeighborRecord>& local) { const float initialRadius = cached.r[i][H]; float radius = initialRadius; while (radius < MAX_DISTENTION * initialRadius) { tree.findAll(cached.r[i], radius, local); if (local.size() >= MIN_NEIGHS) { break; } else { radius *= 1.5f; } } BvhSphere s(cached.r[i], radius); s.userData = i; spheres[i] = s; cached.distention[i] = min(radius / initialRadius, MAX_DISTENTION); }); ArrayView<const Float> m = storage.getValue<Float>(QuantityId::MASS); cached.referenceRadii.resize(cached.r.size()); if (storage.getMaterialCnt() > 0) { for (Size matId = 0; matId < storage.getMaterialCnt(); ++matId) { MaterialView mat = storage.getMaterial(matId); const Float rho = mat->getParam<Float>(BodySettingsId::DENSITY); for (Size i : mat.sequence()) { const Float volume = m[i] / rho; cached.referenceRadii[i] = root<3>(3._f * volume / (4._f * PI)); } } } else { // guess the dentity const Float rho = 1000._f; for (Size i = 0; i < m.size(); ++i) { const Float volume = m[i] / rho; cached.referenceRadii[i] = root<3>(3._f * volume / (4._f * PI)); } } bvh.build(std::move(spheres)); for (ThreadData& data : threadData) { data.data = RayData{}; } shouldContinue = true; } bool VolumeRenderer::isInitialized() const { return !cached.r.empty(); } void VolumeRenderer::setColorizer(const IColorizer& colorizer) { cached.colors.resize(cached.r.size()); for (Size i = 0; i < cached.r.size(); ++i) { cached.colors[i] = colorizer.evalColor(i); } } Rgba VolumeRenderer::shade(const RenderParams& params, const CameraRay& cameraRay, ThreadData& data) const { const Vector dir = getNormalized(cameraRay.target - cameraRay.origin); const Ray ray(cameraRay.origin, dir); RayData& rayData(data.data); Array<IntersectionInfo>& intersections = rayData.intersections; intersections.clear(); bvh.getAllIntersections(ray, backInserter(intersections)); if (params.volume.absorption > 0.f) { std::sort(intersections.begin(), intersections.end()); } Rgba result = this->getEnviroColor(cameraRay); for (const IntersectionInfo& is : reverse(intersections)) { const BvhSphere* s = static_cast<const BvhSphere*>(is.object); const Size i = s->userData; const Vector hit = ray.origin() + ray.direction() * is.t; const Vector center = cached.r[i]; const Vector toCenter = getNormalized(center - hit); const float cosPhi = abs(dot(toCenter, ray.direction())); const float distention = cached.distention[i]; // smoothing length should not have effect on the total emission const float radiiFactor = cached.referenceRadii[i] / cached.r[i][H]; const float secant = 2._f * getLength(center - hit) * cosPhi * radiiFactor; // make dilated particles absorb more result = result * exp(-params.volume.absorption * secant * distention * pow<3>(cosPhi)); // 3th power of cosPhi to give more weight to the sphere center, // divide by distention^3; distention should not affect the total emission const float magnitude = params.volume.emission * pow<3>(cosPhi / distention) * secant; result += cached.colors[i] * magnitude; result.a() += magnitude; } result.a() = min(result.a(), 1.f); return result; } NAMESPACE_SPH_END
37.015504
108
0.639372
pavelsevecek
20c11a4158a9b25d744f13c77336242061ea0686
2,212
cpp
C++
private/shell/cpls/appwiz/appsize.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/cpls/appwiz/appsize.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/cpls/appwiz/appsize.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//--------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation // // File: appsize.cpp // // Compute the size of an application // // History: // 2-17-98 by dli implemented CAppFolderSize //------------------------------------------------------------------------ #include "priv.h" // Do not build this file if on Win9X or NT4 #ifndef DOWNLEVEL_PLATFORM #include "appsize.h" // NOTE: CAppFolderSize and CAppFolderFinder are very similar to C*TreeWalkCB in Shell32. CAppFolderSize::CAppFolderSize(ULONGLONG * puSize): _cRef(1), _puSize(puSize) { CoInitialize(0); } CAppFolderSize::~CAppFolderSize() { if (_pstw) _pstw->Release(); CoUninitialize(); } HRESULT CAppFolderSize::QueryInterface(REFIID riid, LPVOID * ppvOut) { static const QITAB qit[] = { QITABENT(CAppFolderSize, IShellTreeWalkerCallBack), // IID_IShellTreeWalkerCallBack { 0 }, }; return QISearch(this, qit, riid, ppvOut); } ULONG CAppFolderSize::AddRef() { _cRef++; return _cRef; } ULONG CAppFolderSize::Release() { _cRef--; if (_cRef > 0) return _cRef; delete this; return 0; } HRESULT CAppFolderSize::Initialize() { return CoCreateInstance(CLSID_CShellTreeWalker, NULL, CLSCTX_INPROC_SERVER, IID_IShellTreeWalker, (LPVOID *)&_pstw); } // // IShellTreeWalkerCallBack::FoundFile // HRESULT CAppFolderSize::FoundFile(LPCWSTR pwszFolder, LPTREEWALKERSTATS ptws, WIN32_FIND_DATAW * pwfd) { HRESULT hres = S_OK; if (_puSize) *_puSize = ptws->ulActualSize; return hres; } HRESULT CAppFolderSize::EnterFolder(LPCWSTR pwszFolder, LPTREEWALKERSTATS ptws, WIN32_FIND_DATAW * pwfd) { return E_NOTIMPL; } // // IShellTreeWalkerCallBack::LeaveFolder // HRESULT CAppFolderSize::LeaveFolder(LPCWSTR pwszFolder, LPTREEWALKERSTATS ptws) { return E_NOTIMPL; } // // IShellTreeWalkerCallBack::HandleError // HRESULT CAppFolderSize::HandleError(LPCWSTR pwszFolder, LPTREEWALKERSTATS ptws, HRESULT ErrorCode) { return E_NOTIMPL; } #endif //DOWNLEVEL_PLATFORM
22.571429
121
0.627939
King0987654
20c12672fee4df28192a7f10dc5e6dc040f2090a
606
hh
C++
click/elements/local/igmp/AddIPRouterAlertOption.hh
BasilRommens/IGMPv3-click
cb5d63192f0c0344d35dab35d928835c7c6f370f
[ "MIT" ]
null
null
null
click/elements/local/igmp/AddIPRouterAlertOption.hh
BasilRommens/IGMPv3-click
cb5d63192f0c0344d35dab35d928835c7c6f370f
[ "MIT" ]
null
null
null
click/elements/local/igmp/AddIPRouterAlertOption.hh
BasilRommens/IGMPv3-click
cb5d63192f0c0344d35dab35d928835c7c6f370f
[ "MIT" ]
null
null
null
#ifndef CLICK_AddIPRouterAlertOption_HH #define CLICK_AddIPRouterAlertOption_HH #include <click/element.hh> #include <click/ipaddress.hh> CLICK_DECLS class AddIPRouterAlertOption : public Element { public: AddIPRouterAlertOption(); ~AddIPRouterAlertOption(); const char *class_name() const { return "AddIPRouterAlertOption"; } const char *port_count() const { return "1"; } const char *processing() const { return PUSH; } int configure(Vector <String> &conf, ErrorHandler *errh); void push(int port, Packet *p); }; CLICK_ENDDECLS #endif //CLICK_AddIPRouterAlertOption_HH
24.24
71
0.745875
BasilRommens
20c1a34f72fe6a0be98b8dda94854aaee65158a7
14,843
hpp
C++
library/src/include/tensile_host.hpp
amcamd/rocBLAS
f0986a922269c2fe343c414ec13a055cf8574bc3
[ "MIT" ]
null
null
null
library/src/include/tensile_host.hpp
amcamd/rocBLAS
f0986a922269c2fe343c414ec13a055cf8574bc3
[ "MIT" ]
null
null
null
library/src/include/tensile_host.hpp
amcamd/rocBLAS
f0986a922269c2fe343c414ec13a055cf8574bc3
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright 2019-2021 Advanced Micro Devices, Inc. * ************************************************************************/ /********************************************************* * Declaration of the rocBLAS<->Tensile interface layer. * *********************************************************/ #pragma once #ifndef USE_TENSILE_HOST #error "tensile_host.hpp #include'd when USE_TENSILE_HOST is undefined." #endif /***************************************************************************** * WARNING: Tensile-specific data types, functions and macros should only be * * referenced from tensile_host.cpp. This header file defines the interface * * that the rest of rocBLAS uses to access Tensile. If another Tensile * * feature needs to be accessed, the API for accessing it should be defined * * in this file, without referencing any Tensile-specific identifiers here. * *****************************************************************************/ #include "handle.hpp" #include "tuple_helper.hpp" #include <atomic> /******************************************************************** * RocblasContractionProblem captures the arguments for a GEMM-like * * contraction problem, to be passed to runContractionProblem. * ********************************************************************/ template <typename Ti, typename To = Ti, typename Tc = To> struct RocblasContractionProblem { rocblas_handle handle; rocblas_gemm_flags flags; rocblas_operation trans_a; rocblas_operation trans_b; // The RocblasContractionProblem data members should exactly match // Tensile's parameter types, even if rocBLAS uses differently // sized or signed types. The constructors should convert rocBLAS // types into the corresponding Tensile types stored in this class. size_t m; size_t n; size_t k; const Tc* alpha; const Ti* A; const Ti* const* batch_A; size_t row_stride_a; size_t col_stride_a; size_t batch_stride_a; size_t buffer_offset_a; const Ti* B; const Ti* const* batch_B; size_t row_stride_b; size_t col_stride_b; size_t batch_stride_b; size_t buffer_offset_b; const Tc* beta; const To* C; const To* const* batch_C; size_t row_stride_c; size_t col_stride_c; size_t batch_stride_c; size_t buffer_offset_c; To* D; To* const* batch_D; size_t row_stride_d; size_t col_stride_d; size_t batch_stride_d; size_t buffer_offset_d; size_t batch_count; bool strided_batch; // gemm // gemm_strided_batched RocblasContractionProblem(rocblas_handle handle, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_int m, rocblas_int n, rocblas_int k, const Tc* alpha, const Ti* A, const Ti* const* batch_A, rocblas_int ld_a, rocblas_stride batch_stride_a, rocblas_int offset_a, const Ti* B, const Ti* const* batch_B, rocblas_int ld_b, rocblas_stride batch_stride_b, rocblas_int offset_b, const Tc* beta, To* C, To* const* batch_C, rocblas_int ld_c, rocblas_stride batch_stride_c, rocblas_int offset_c, rocblas_int batch_count, bool strided_batch, rocblas_gemm_flags flags) : handle(handle) , flags(flags) , trans_a(trans_a) , trans_b(trans_b) , m(m) , n(n) , k(k) , alpha(alpha) , A(A) , batch_A(batch_A) , row_stride_a(1) , col_stride_a(ld_a) , batch_stride_a(batch_stride_a) , buffer_offset_a(offset_a) , B(B) , batch_B(batch_B) , row_stride_b(1) , col_stride_b(ld_b) , batch_stride_b(batch_stride_b) , buffer_offset_b(offset_b) , beta(beta) , C(C) , batch_C(batch_C) , row_stride_c(1) , col_stride_c(ld_c) , batch_stride_c(batch_stride_c) , buffer_offset_c(offset_c) , D(C) , batch_D(batch_C) , row_stride_d(1) , col_stride_d(ld_c) , batch_stride_d(batch_stride_c) , buffer_offset_d(offset_c) , batch_count(batch_count) , strided_batch(strided_batch) { } // gemm_ex // gemm_strided_batched_ex RocblasContractionProblem(rocblas_handle handle, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_int m, rocblas_int n, rocblas_int k, const Tc* alpha, const Ti* A, const Ti* const* batch_A, rocblas_int ld_a, rocblas_stride batch_stride_a, rocblas_int offset_a, const Ti* B, const Ti* const* batch_B, rocblas_int ld_b, rocblas_stride batch_stride_b, rocblas_int offset_b, const Tc* beta, const To* C, const To* const* batch_C, rocblas_int ld_c, rocblas_stride batch_stride_c, rocblas_int offset_c, To* D, To* const* batch_D, rocblas_int ld_d, rocblas_stride batch_stride_d, rocblas_int offset_d, rocblas_int batch_count, bool strided_batch, rocblas_gemm_flags flags) : handle(handle) , flags(flags) , trans_a(trans_a) , trans_b(trans_b) , m(m) , n(n) , k(k) , alpha(alpha) , A(A) , batch_A(batch_A) , row_stride_a(1) , col_stride_a(ld_a) , batch_stride_a(batch_stride_a) , buffer_offset_a(offset_a) , B(B) , batch_B(batch_B) , row_stride_b(1) , col_stride_b(ld_b) , batch_stride_b(batch_stride_b) , buffer_offset_b(offset_b) , beta(beta) , C(C) , batch_C(batch_C) , row_stride_c(1) , col_stride_c(ld_c) , batch_stride_c(batch_stride_c) , buffer_offset_c(offset_c) , D(D) , batch_D(batch_D) , row_stride_d(1) , col_stride_d(ld_d) , batch_stride_d(batch_stride_d) , buffer_offset_d(offset_d) , batch_count(batch_count) , strided_batch(strided_batch) { } // gemm_ext2 // gemm_strided_batched_ext2 RocblasContractionProblem(rocblas_handle handle, rocblas_int m, rocblas_int n, rocblas_int k, const Tc* alpha, const Ti* A, const Ti* const* batch_A, rocblas_stride row_stride_a, rocblas_stride col_stride_a, rocblas_stride batch_stride_a, rocblas_int offset_a, const Ti* B, const Ti* const* batch_B, rocblas_stride row_stride_b, rocblas_stride col_stride_b, rocblas_stride batch_stride_b, rocblas_int offset_b, const Tc* beta, const To* C, const To* const* batch_C, rocblas_stride row_stride_c, rocblas_stride col_stride_c, rocblas_stride batch_stride_c, rocblas_int offset_c, To* D, To* const* batch_D, rocblas_stride row_stride_d, rocblas_stride col_stride_d, rocblas_stride batch_stride_d, rocblas_int offset_d, rocblas_int batch_count, bool strided_batch) : handle(handle) , flags(rocblas_gemm_flags_none) , trans_a(rocblas_operation_none) , trans_b(rocblas_operation_none) , m(m) , n(n) , k(k) , alpha(alpha) , A(A) , batch_A(batch_A) , row_stride_a(row_stride_a) , col_stride_a(col_stride_a) , batch_stride_a(batch_stride_a) , buffer_offset_a(offset_a) , B(B) , batch_B(batch_B) , row_stride_b(row_stride_b) , col_stride_b(col_stride_b) , batch_stride_b(batch_stride_b) , buffer_offset_b(offset_b) , beta(beta) , C(C) , batch_C(batch_C) , row_stride_c(row_stride_c) , col_stride_c(col_stride_c) , batch_stride_c(batch_stride_c) , buffer_offset_c(offset_c) , D(D) , batch_D(batch_D) , row_stride_d(row_stride_d) , col_stride_d(col_stride_d) , batch_stride_d(batch_stride_d) , buffer_offset_d(offset_d) , batch_count(batch_count) , strided_batch(strided_batch) { } /*************************************************** * Print a RocblasContractionProblem for debugging * ***************************************************/ friend rocblas_ostream& operator<<(rocblas_ostream& os, const RocblasContractionProblem& prob) { return tuple_helper::print_tuple_pairs( os, std::make_tuple("a_type", rocblas_precision_string<Ti>, "b_type", rocblas_precision_string<Ti>, "c_type", rocblas_precision_string<To>, "d_type", rocblas_precision_string<To>, "compute_type", rocblas_precision_string<Tc>, "transA", rocblas_transpose_letter(prob.trans_a), "transB", rocblas_transpose_letter(prob.trans_b), "M", prob.m, "N", prob.n, "K", prob.k, "alpha", *prob.alpha, "row_stride_a", prob.row_stride_a, "col_stride_a", prob.col_stride_a, "row_stride_b", prob.row_stride_b, "col_stride_b", prob.col_stride_b, "row_stride_c", prob.row_stride_c, "col_stride_c", prob.col_stride_c, "row_stride_d", prob.row_stride_d, "col_stride_d", prob.col_stride_d, "beta", *prob.beta, "batch_count", prob.batch_count, "strided_batch", prob.strided_batch, "stride_a", prob.batch_stride_a, "stride_b", prob.batch_stride_b, "stride_c", prob.batch_stride_c, "stride_d", prob.batch_stride_d, "atomics_mode", prob.handle->atomics_mode)); }; }; /******************************************************************************* * runContractionProblem() solves a RocblasContractionProblem * *******************************************************************************/ template <typename Ti, typename To, typename Tc> rocblas_status runContractionProblem(RocblasContractionProblem<Ti, To, Tc> const& problem); /*********************************************************************************** * Whether Tensile has been initialized for at least one device (used for testing) * ***********************************************************************************/ ROCBLAS_EXPORT std::atomic_bool& rocblas_tensile_is_initialized(); /********************************************** * Whether to suppress Tensile error messages * **********************************************/ inline bool& rocblas_suppress_tensile_error_messages() { thread_local bool t_suppress = false; return t_suppress; }
39.687166
98
0.418042
amcamd
20c3c75d9d3987d1ed165025b829f6e846b99d79
2,111
cpp
C++
src/bluecadet/tangibleengine/TangibleEngineSimulator.cpp
bluecadet/Cinder-BluecadetTangibleEngine
a96e08a8a4556d5699aea90cd04e687999e772a5
[ "MIT" ]
null
null
null
src/bluecadet/tangibleengine/TangibleEngineSimulator.cpp
bluecadet/Cinder-BluecadetTangibleEngine
a96e08a8a4556d5699aea90cd04e687999e772a5
[ "MIT" ]
null
null
null
src/bluecadet/tangibleengine/TangibleEngineSimulator.cpp
bluecadet/Cinder-BluecadetTangibleEngine
a96e08a8a4556d5699aea90cd04e687999e772a5
[ "MIT" ]
null
null
null
#include "TangibleEngineSimulator.h" #include "cinder/Log.h" #include "cinder/Color.h" #include "bluecadet/core/ScreenCamera.h" #include "bluecadet/views/EllipseView.h" using namespace ci; using namespace ci::app; using namespace std; namespace bluecadet { namespace tangibleengine { //================================================== // Public // TangibleEngineSimulator::TangibleEngineSimulator() : mView(new views::BaseView()) { //mParams = params::InterfaceGl::create("Tangible Engine Simulator", ivec2(200, 250)); } TangibleEngineSimulator::~TangibleEngineSimulator() { } void TangibleEngineSimulator::setup(TangibleEnginePluginRef plugin, bluecadet::touch::TouchManagerRef touchManager) { destroy(); mPlugin = plugin; mTouchManager = touchManager; setupTangibles(); mUpdateSignalConnection = App::get()->getSignalUpdate().connect(bind(&TangibleEngineSimulator::handleUpdate, this)); } void TangibleEngineSimulator::destroy() { mUpdateSignalConnection.disconnect(); //mParams->clear(); mPlugin = nullptr; mTouchManager = nullptr; } //================================================== // Protected // void TangibleEngineSimulator::setupTangibles() { // TODO: move to heap/store permanently const int maxNumPatterns = 128; int numPatterns = maxNumPatterns; TE_Pattern patterns[maxNumPatterns]; TE_GetPatterns(patterns, &numPatterns); if (numPatterns <= 0) { CI_LOG_W("No patterns configured with Tangible Engine. Make sure to call setup() after Tangible Engine has been configured."); } mView->removeAllChildren(); for (int i = 0; i < numPatterns; ++i) { vec3 hsv = vec3((float)i / (float) numPatterns, 1.0f, 1.0f); ColorA color = ColorA(hsvToRgb(hsv), 0.5f); VirtualTangibleRef tangible(new VirtualTangible(patterns[i], color)); mTangibles.push_back(tangible); mView->addChild(tangible); } } void TangibleEngineSimulator::setupParams() { } void TangibleEngineSimulator::handleUpdate() { for (auto tangible : mTangibles) { tangible->updateTouches(); for (auto touch : tangible->getTouches()) { mTouchManager->addTouch(touch); } } } } }
23.455556
128
0.704879
bluecadet
20c737737bdc0360fd1d7e3b6522b18c4d90ae0e
381
cc
C++
BOJ/2953.cc
Yaminyam/Algorithm
fe49b37b4b310f03273864bcd193fe88139f1c01
[ "MIT" ]
1
2019-05-18T00:02:12.000Z
2019-05-18T00:02:12.000Z
BOJ/2953.cc
siontama/Algorithm
bb419e0d4dd09682bd4542f90038b492ee232bd2
[ "MIT" ]
null
null
null
BOJ/2953.cc
siontama/Algorithm
bb419e0d4dd09682bd4542f90038b492ee232bd2
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> using namespace std; int main() { int arr[5]={0,}; int ansn=0; int ans=0; for(int i=0;i<5;i++){ for(int j=0;j<4;j++){ int x; cin >> x; arr[i]+=x; } if(arr[i]>ans){ ansn = i+1; ans = arr[i]; } } cout << ansn << " " << ans; }
15.875
31
0.383202
Yaminyam
20c7395524317ec51015cc32d1dd164023b31905
536
cpp
C++
test/unit/math/mix/fun/csr_matrix_times_vector_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/mix/fun/csr_matrix_times_vector_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/mix/fun/csr_matrix_times_vector_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#include <test/unit/math/test_ad.hpp> #include <vector> TEST(MathMixMatFun, csr_matrix_times_vector) { auto f = [](const auto& w, const auto& b) { using stan::math::csr_matrix_times_vector; std::vector<int> v{1, 2, 3, 1, 2}; std::vector<int> u{1, 2, 3, 4, 5, 6}; return csr_matrix_times_vector(5, 5, w, v, u, b); }; Eigen::VectorXd w(5); w << -0.67082, 0.5, -0.223607, -0.223607, -0.5; Eigen::VectorXd b(5); b << 1, 2, 3, 4, 5; stan::test::expect_ad(f, w, b); stan::test::expect_ad_matvar(f, w, b); }
26.8
53
0.602612
LaudateCorpus1
20c7f5364e5566b486f8fe607f38e4e9b2a5dcc1
231
hpp
C++
Miracle/src/Miracle/Graphics/Vertex.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
Miracle/src/Miracle/Graphics/Vertex.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
3
2021-12-10T23:19:29.000Z
2022-03-27T05:04:14.000Z
Miracle/src/Miracle/Graphics/Vertex.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
#pragma once #include <Miracle/components/Miracle/Math/Vector2f.hpp> #include <Miracle/components/Miracle/Math/Vector3f.hpp> namespace Miracle::Graphics { struct Vertex { Math::Vector2f position; Math::Vector3f color; }; }
19.25
55
0.757576
McFlyboy
20c8d8ec0658ab05f8fa53f8730e999e9d8776c9
1,832
cpp
C++
C-Plus-Plus-Programming/b. Tokens,Expressions and control Structures/h_operators.cpp
deepraj1729/Coding-From-Scratch
6a7c5262f8843cc7e9447912aaa7260bbfa38e6e
[ "MIT" ]
2
2020-09-06T15:51:15.000Z
2020-10-04T23:29:20.000Z
C-Plus-Plus-Programming/b. Tokens,Expressions and control Structures/h_operators.cpp
deepraj1729/Coding-From-Scratch
6a7c5262f8843cc7e9447912aaa7260bbfa38e6e
[ "MIT" ]
null
null
null
C-Plus-Plus-Programming/b. Tokens,Expressions and control Structures/h_operators.cpp
deepraj1729/Coding-From-Scratch
6a7c5262f8843cc7e9447912aaa7260bbfa38e6e
[ "MIT" ]
null
null
null
/* The operators in C++ includes:- 1. :: --> Scope resolution operator (returns the global scope value of any variable) 2. ::* --> Pointer-to-member declarator 3. ->* --> pointer-to-member operator 4. .* --> Pointer-to-member operator 5. delete --> Used to free up memory space of variables (implicit call of malloc) 6. endl --> Used as end line 7. new --> Creates memory space for a variable based on its datatype 8. setw --> Field width operator */ #include<iostream> using namespace std; int a = 123; int main() { cout<<"\n\nVariable \'a\' in global scope = "<<a<<endl; cout<<"Variable \'a\' in global scope with scope resolution = "<<::a<<endl; int a = 99; // local main scope { int a = 987; // local scope inside curly braces cout<<"\n\nVariable \'a\' in local scope (under curly braces) = "<<a<<endl; cout<<"Variable \'a\' in global scope with scope resolution = "<<::a<<endl; } // end of scope for a = 987 cout<<"\n\nVariable \'a\' in main scope = "<<a<<endl; cout<<"Variable \'a\' in global scope with scope resolution = "<<::a<<endl; // Memory management operators include new, delete // "new" operator assigns memory as per the data type int *b,*c; b = new int(25); c = new int; *c= 23; cout<<"\n\n*b has address = "<<b<<" and it contains : "<<*b<<endl; cout<<"*c has address = "<<c<<" and it contains : "<<*c<<endl; // "delete" operator is used to free up memory for variables delete(c); delete(b); // This time the values in b and c will have garbage but same addresses cout<<"\n*b has address = "<<b<<" and it contains : "<<*b<<endl; cout<<"*c has address = "<<c<<" and it contains : "<<*c<<endl; return 0; }
31.050847
95
0.578057
deepraj1729
20c8ed7ee46a4d274d0249ce2a6cc66b953f6dd0
599
cpp
C++
Cplusplus/trik.cpp
Jayseff/OpenKattis
921ef2b6b5138505663edf53885fa8b6e655887e
[ "AFL-3.0" ]
null
null
null
Cplusplus/trik.cpp
Jayseff/OpenKattis
921ef2b6b5138505663edf53885fa8b6e655887e
[ "AFL-3.0" ]
null
null
null
Cplusplus/trik.cpp
Jayseff/OpenKattis
921ef2b6b5138505663edf53885fa8b6e655887e
[ "AFL-3.0" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string actions; int arr[3] = {1,0,0}; int temp = 0; cin >> actions; for (int i = 0; i < actions.length(); i++) { if (actions[i] == 'A') { temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; } if (actions[i] == 'B') { temp = arr[1]; arr[1] = arr[2]; arr[2] = temp; } if (actions[i] == 'C') { temp = arr[2]; arr[2] = arr[0]; arr[0] = temp; } } for (int i = 0; i < 3; i++) { if (arr[i] == 1) cout << i + 1; } return 0; }
14.609756
44
0.420701
Jayseff
20cba4e40438a256da188e5a8d2217fb7220e037
11,928
cpp
C++
src/screen_settings.cpp
puzrin/dispenser
e0283af232a65a840dedb15feaaccf1294a3a7cb
[ "MIT" ]
28
2019-09-02T05:23:00.000Z
2022-01-16T22:19:55.000Z
src/screen_settings.cpp
puzrin/dispenser
e0283af232a65a840dedb15feaaccf1294a3a7cb
[ "MIT" ]
null
null
null
src/screen_settings.cpp
puzrin/dispenser
e0283af232a65a840dedb15feaaccf1294a3a7cb
[ "MIT" ]
10
2019-12-31T02:22:22.000Z
2021-12-14T04:11:27.000Z
#include "app.h" #include "screen_settings.h" #include "etl/to_string.h" #include "etl/cyclic_value.h" enum setting_type { TYPE_NEEDLE_DIA = 0, TYPE_SYRINGE_DIA = 1, TYPE_VISCOSITY = 2, TYPE_FLUX_PERCENT = 3, TYPE_MOVE_PUSHER = 4 }; typedef struct { float step_scale = 0.0f; float current_step = 0.0f; uint16_t repeat_count = 0; } setting_data_state_t; typedef struct _setting_data { enum setting_type const type; const char * const title; const char * (* const val_get_text_fn)(const struct _setting_data * data); void (* const val_update_fn)(const struct _setting_data * data, lv_event_t e, int const key_code); float * const val_ref; const float min_value = 0.0f; const float max_value = 0.0f; const float min_step = 0.0f; const float max_step = 0.0f; const uint8_t precision = 1; const char * const suffix = ""; setting_data_state_t * const s; } setting_data_t; void base_update_value_fn(const setting_data_t * data, lv_event_t e, int key_code) { // lazy init for first run if (data->s->current_step < data->min_step) data->s->current_step = data->min_step; if (data->s->step_scale <= 0.0f) data->s->step_scale = 10.0f; if (e == LV_EVENT_RELEASED) { data->s->repeat_count = 0; data->s->current_step = data->min_step; return; } data->s->repeat_count++; if (data->s->repeat_count >= 10) { data->s->repeat_count = 0; data->s->current_step = fmin(data->s->current_step * data->s->step_scale, data->max_step); } float val = *data->val_ref; if (key_code == LV_KEY_RIGHT) val = fmin(val + data->s->current_step, data->max_value); else val = fmax(val - data->s->current_step, data->min_value); *data->val_ref = val; } static const char * base_get_text_fn(const setting_data_t * data) { static etl::string<10> buf; etl::to_string(*data->val_ref, buf, etl::format_spec().precision(data->precision)); buf += data->suffix; return buf.c_str(); } /*static setting_data_state_t s_data_needle_state = {}; static setting_data_t s_data_needle = { .type = TYPE_NEEDLE_DIA, .title = "Needle dia", .val_redraw_fn = &base_redraw_fn, .val_update_fn = &base_update_value_fn, .val_ref = &app_data.needle_dia, .min_value = 0.3f, .max_value = 2.0f, .min_step = 0.1f, .max_step = 0.1f, .precision = 1, .suffix = " mm", .s = &s_data_needle_state };*/ static setting_data_state_t s_data_syringe_state = {}; static const setting_data_t s_data_syringe = { .type = TYPE_SYRINGE_DIA, .title = "Syringe dia", .val_get_text_fn = &base_get_text_fn, .val_update_fn = &base_update_value_fn, .val_ref = &app_data.syringe_dia, .min_value = 4.0f, .max_value = 30.0f, .min_step = 0.1f, .max_step = 1.0f, .precision = 1, .suffix = " mm", .s = &s_data_syringe_state }; static setting_data_state_t s_data_viscosity_state = {}; static const setting_data_t s_data_viscosity = { .type = TYPE_VISCOSITY, .title = "Viscosity", .val_get_text_fn = &base_get_text_fn, .val_update_fn = &base_update_value_fn, .val_ref = &app_data.viscosity, .min_value = 1.0f, .max_value = 1000.0f, .min_step = 1.0f, .max_step = 100.0f, .precision = 1, .suffix = " P", .s = &s_data_viscosity_state }; static setting_data_state_t s_data_flux_percent_state = {}; static const setting_data_t s_data_flux_percent = { .type = TYPE_FLUX_PERCENT, .title = "Flux part", .val_get_text_fn = &base_get_text_fn, .val_update_fn = &base_update_value_fn, .val_ref = &app_data.flux_percent, .min_value = 1.0f, .max_value = 50.0f, .min_step = 1.0f, .max_step = 3.0f, .precision = 0, .suffix = "%", .s = &s_data_flux_percent_state }; static const char * move_pusher_get_text_fn(const setting_data_t * data) { (void)data; return U_ICON_ARROWS; } static void pusher_update_value_fn(const setting_data_t * data, lv_event_t e, int key_code) { // TODO run motor in specified direction (void)data; (void)e; (void) key_code; } static setting_data_state_t s_data_move_pusher_state = {}; static const setting_data_t s_data_move_pusher = { .type = TYPE_MOVE_PUSHER, .title = "Fast move", .val_get_text_fn = &move_pusher_get_text_fn, .val_update_fn = &pusher_update_value_fn, .val_ref = NULL, .min_value = 0.0f, .max_value = 0.0f, .min_step = 0.0f, .max_step = 0.0f, .precision = 0, .suffix = "", .s = &s_data_move_pusher_state }; static lv_obj_t * page; static bool destroyed = false; static lv_design_cb_t orig_design_cb; // Custom drawer to avoid labels create & save RAM. static bool list_item_design_cb(lv_obj_t * obj, const lv_area_t * mask_p, lv_design_mode_t mode) { auto * s_data = reinterpret_cast<const setting_data_t *>(lv_obj_get_user_data(obj)); if(mode == LV_DESIGN_DRAW_MAIN) { orig_design_cb(obj, mask_p, mode); lv_point_t title_pos = { .x = 4, .y = 4 }; lv_draw_label( &obj->coords, mask_p, &app_data.styles.list_title, lv_obj_get_opa_scale(obj), s_data->title, LV_TXT_FLAG_NONE, &title_pos, NULL, NULL, lv_obj_get_base_dir(obj) ); lv_point_t desc_pos = { .x = 4, .y = 19 }; lv_draw_label( &obj->coords, mask_p, &app_data.styles.list_desc, lv_obj_get_opa_scale(obj), s_data->val_get_text_fn(s_data), LV_TXT_FLAG_NONE, &desc_pos, NULL, NULL, lv_obj_get_base_dir(obj) ); return true; } return orig_design_cb(obj, mask_p, mode); } static void group_style_mod_cb(lv_group_t * group, lv_style_t * style) { if (destroyed) return; style->body.main_color = COLOR_BG_HIGHLIGHT; style->body.grad_color = COLOR_BG_HIGHLIGHT; (void)group; } static void screen_settings_menu_item_cb(lv_obj_t * item, lv_event_t e) { if (destroyed) return; // Next part is for keyboard only if ((e != LV_EVENT_KEY) && (e != LV_EVENT_LONG_PRESSED) && (e != LV_EVENT_RELEASED) && (e != HACK_EVENT_RELEASED)) { return; } int key_code = lv_indev_get_key(app_data.kbd); static etl::cyclic_value<uint8_t, 0, 1> skip_cnt; auto * s_data = reinterpret_cast<const setting_data_t *>(lv_obj_get_user_data(item)); switch (e) { // All keys except enter have `LV_EVENT_KEY` event for both // click & repeat. And do not provide release & long press events. case LV_EVENT_KEY: switch (key_code) { // List navigation case LV_KEY_UP: skip_cnt++; if (skip_cnt != 1) return; lv_group_focus_prev(app_data.group); // Scroll focused to visible area lv_page_focus(page, lv_group_get_focused(app_data.group), true); return; case LV_KEY_DOWN: skip_cnt++; if (skip_cnt != 1) return; lv_group_focus_next(app_data.group); // Scroll focused to visible area lv_page_focus(page, lv_group_get_focused(app_data.group), true); return; // Value change case LV_KEY_LEFT: case LV_KEY_RIGHT: s_data->val_update_fn(s_data, e, key_code); lv_obj_invalidate(item); app_update_settings(); return; } return; // for ENTER only case LV_EVENT_LONG_PRESSED: if (key_code == LV_KEY_ENTER) { app_data.skip_key_enter_release = true; app_screen_create(false); } return; // for ENTER only case LV_EVENT_RELEASED: if (key_code == LV_KEY_ENTER) { if (app_data.skip_key_enter_release) { app_data.skip_key_enter_release = false; return; } app_screen_create(false); return; } return; // injected event from hacked driver case HACK_EVENT_RELEASED: skip_cnt = 0; switch (key_code) { case LV_KEY_LEFT: case LV_KEY_RIGHT: s_data->val_update_fn(s_data, LV_EVENT_RELEASED, key_code); return; } return; } } void screen_settings_create() { lv_obj_t * screen = lv_scr_act(); lv_group_set_style_mod_cb(app_data.group, group_style_mod_cb); lv_obj_t * mode_label = lv_label_create(screen, NULL); lv_label_set_style(mode_label, LV_LABEL_STYLE_MAIN, &app_data.styles.header_icon); lv_label_set_text(mode_label, U_ICON_SETTINGS); lv_obj_set_pos(mode_label, 4, 4); // // Create list // page = lv_page_create(screen, NULL); lv_page_set_anim_time(page, 150); lv_page_set_style(page, LV_PAGE_STYLE_BG, &app_data.styles.list); lv_page_set_style(page, LV_PAGE_STYLE_SCRL, &app_data.styles.list); lv_page_set_sb_mode(page, LV_SB_MODE_OFF); lv_page_set_scrl_layout(page, LV_LAYOUT_COL_L); lv_obj_set_size( page, lv_obj_get_width(screen), lv_obj_get_height(lv_scr_act()) - LIST_MARGIN_TOP ); lv_obj_set_pos(page, 0, LIST_MARGIN_TOP); lv_obj_t * selected_item = NULL; uint8_t selected_id = (uint8_t)app_data.screen_settings_selected_id; const setting_data_t * s_data_list[] = { &s_data_syringe, //&s_data_needle, &s_data_viscosity, &s_data_flux_percent, &s_data_move_pusher, NULL }; for (uint8_t i = 0; s_data_list[i] != NULL; i++) { // // Create list item & attach user data // auto * data = s_data_list[i]; lv_obj_t * item = lv_obj_create(page, NULL); lv_obj_set_user_data(item, const_cast<setting_data_t *>(data)); lv_obj_set_style(item, &app_data.styles.main); lv_obj_set_size(item, lv_obj_get_width(page), 37); lv_obj_set_event_cb(item, screen_settings_menu_item_cb); lv_group_add_obj(app_data.group, item); // We use custom drawer to avoid labels use and reduce RAM comsumption // significantly. Now it's ~ 170 bytes per entry. // Since all callbacks are equal - use the same var to store old ones. orig_design_cb = lv_obj_get_design_cb(item); lv_obj_set_design_cb(item, list_item_design_cb); if (data->type == selected_id) selected_item = item; } // // Restore previous state // if (selected_item) { lv_group_focus_obj(selected_item); if (app_data.screen_settings_scroll_pos != INT16_MAX) { lv_obj_set_y(lv_page_get_scrl(page), app_data.screen_settings_scroll_pos); } else lv_page_focus(page, lv_group_get_focused(app_data.group), LV_ANIM_OFF); } destroyed = false; } void screen_settings_destroy() { if (destroyed) return; destroyed = true; app_data.screen_settings_scroll_pos = lv_obj_get_y(lv_page_get_scrl(page)); auto * s_data = reinterpret_cast<const setting_data_t *>(lv_obj_get_user_data( lv_group_get_focused(app_data.group) )); app_data.screen_settings_selected_id = s_data->type; lv_group_set_focus_cb(app_data.group, NULL); lv_group_set_style_mod_cb(app_data.group, NULL); lv_group_remove_all_objs(app_data.group); lv_obj_clean(lv_scr_act()); }
28.332542
102
0.618545
puzrin
20cc0bb0ae201641b69c9472060c3f71e47fff55
5,334
cc
C++
chromeos/services/secure_channel/nearby_connection_manager.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chromeos/services/secure_channel/nearby_connection_manager.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chromeos/services/secure_channel/nearby_connection_manager.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/services/secure_channel/nearby_connection_manager.h" #include "base/containers/contains.h" #include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/services/secure_channel/authenticated_channel.h" namespace chromeos { namespace secure_channel { NearbyConnectionManager::InitiatorConnectionAttemptMetadata:: InitiatorConnectionAttemptMetadata( ConnectionSuccessCallback success_callback, const FailureCallback& failure_callback) : success_callback(std::move(success_callback)), failure_callback(failure_callback) {} NearbyConnectionManager::InitiatorConnectionAttemptMetadata:: ~InitiatorConnectionAttemptMetadata() = default; NearbyConnectionManager::NearbyConnectionManager() = default; NearbyConnectionManager::~NearbyConnectionManager() = default; void NearbyConnectionManager::SetNearbyConnector( mojo::PendingRemote<mojom::NearbyConnector> nearby_connector) { if (nearby_connector_) nearby_connector_.reset(); nearby_connector_.Bind(std::move(nearby_connector)); } bool NearbyConnectionManager::IsNearbyConnectorSet() const { return nearby_connector_.is_bound(); } void NearbyConnectionManager::AttemptNearbyInitiatorConnection( const DeviceIdPair& device_id_pair, ConnectionSuccessCallback success_callback, const FailureCallback& failure_callback) { if (base::Contains(id_pair_to_initiator_metadata_map_, device_id_pair)) { PA_LOG(ERROR) << "Tried to add Nearby initiator connection attempt, but " << "one was already active. Device IDs: " << device_id_pair; NOTREACHED(); return; } id_pair_to_initiator_metadata_map_.emplace(std::make_pair( device_id_pair, std::make_unique<InitiatorConnectionAttemptMetadata>( std::move(success_callback), failure_callback))); remote_device_id_to_id_pair_map_[device_id_pair.remote_device_id()].insert( device_id_pair); PA_LOG(VERBOSE) << "Attempting Nearby connection for: " << device_id_pair; PerformAttemptNearbyInitiatorConnection(device_id_pair); } void NearbyConnectionManager::CancelNearbyInitiatorConnectionAttempt( const DeviceIdPair& device_id_pair) { RemoveRequestMetadata(device_id_pair); PA_LOG(VERBOSE) << "Canceling Nearby connection attempt for: " << device_id_pair; PerformCancelNearbyInitiatorConnectionAttempt(device_id_pair); } mojom::NearbyConnector* NearbyConnectionManager::GetNearbyConnector() { if (!nearby_connector_.is_bound()) return nullptr; return nearby_connector_.get(); } const base::flat_set<DeviceIdPair>& NearbyConnectionManager::GetDeviceIdPairsForRemoteDevice( const std::string& remote_device_id) const { return remote_device_id_to_id_pair_map_.find(remote_device_id)->second; } bool NearbyConnectionManager::DoesAttemptExist( const DeviceIdPair& device_id_pair) { return base::Contains(id_pair_to_initiator_metadata_map_, device_id_pair); } void NearbyConnectionManager::NotifyNearbyInitiatorFailure( const DeviceIdPair& device_id_pair, NearbyInitiatorFailureType failure_type) { PA_LOG(VERBOSE) << "Notifying client of Nearby initiator failure: " << device_id_pair; GetInitiatorEntry(device_id_pair).failure_callback.Run(failure_type); } void NearbyConnectionManager::NotifyNearbyInitiatorConnectionSuccess( const DeviceIdPair& device_id_pair, std::unique_ptr<AuthenticatedChannel> authenticated_channel) { PA_LOG(VERBOSE) << "Notifying client of successful Neraby connection for: " << device_id_pair; // Retrieve the success callback out of the map first, then remove the // associated metadata before invoking the callback. ConnectionSuccessCallback success_callback = std::move(GetInitiatorEntry(device_id_pair).success_callback); RemoveRequestMetadata(device_id_pair); std::move(success_callback).Run(std::move(authenticated_channel)); } NearbyConnectionManager::InitiatorConnectionAttemptMetadata& NearbyConnectionManager::GetInitiatorEntry(const DeviceIdPair& device_id_pair) { std::unique_ptr<InitiatorConnectionAttemptMetadata>& entry = id_pair_to_initiator_metadata_map_[device_id_pair]; DCHECK(entry); return *entry; } void NearbyConnectionManager::RemoveRequestMetadata( const DeviceIdPair& device_id_pair) { auto metadata_it = id_pair_to_initiator_metadata_map_.find(device_id_pair); if (metadata_it == id_pair_to_initiator_metadata_map_.end()) { PA_LOG(ERROR) << "Tried to remove Nearby initiator metadata, but none " << "existed. Device IDs: " << device_id_pair; NOTREACHED(); } else { id_pair_to_initiator_metadata_map_.erase(metadata_it); } auto id_pair_it = remote_device_id_to_id_pair_map_.find(device_id_pair.remote_device_id()); if (id_pair_it == remote_device_id_to_id_pair_map_.end()) { PA_LOG(ERROR) << "Tried to remove Nearby initiator attempt, but no attempt " << "existed. Device IDs: " << device_id_pair; NOTREACHED(); } else { id_pair_it->second.erase(device_id_pair); } } } // namespace secure_channel } // namespace chromeos
37.300699
80
0.772591
zealoussnow
20cd7b1f74e573bc0f0d699d4ce4f0fdddb9ffc6
1,655
cpp
C++
test/substring/longest_common_substring.test.cpp
camilne/cardigan
6cb07095c3dc06e558108a9986ab0e434c4b13e1
[ "MIT" ]
2
2018-04-26T04:24:47.000Z
2018-04-26T04:25:28.000Z
test/substring/longest_common_substring.test.cpp
camilne/cardigan
6cb07095c3dc06e558108a9986ab0e434c4b13e1
[ "MIT" ]
22
2018-04-26T04:41:19.000Z
2018-05-13T02:49:04.000Z
test/substring/longest_common_substring.test.cpp
camilne/cardigan
6cb07095c3dc06e558108a9986ab0e434c4b13e1
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include "third_party/catch.hpp" #include "substring/longest_common_substring.hpp" using namespace cgn; TEST_CASE("Longest Common Substring: Base cases", "[longest-common-substring]") { std::string a; auto substrings = longest_common_substring(a, a); REQUIRE(substrings.size() == 0); a = "a"; substrings = longest_common_substring(a, a); REQUIRE(substrings.size() == 1); REQUIRE(substrings[0] == a); std::vector<int> b; auto b_substrings = longest_common_substring(b.begin(), b.end(), b.begin(), b.end()); REQUIRE(b_substrings.size() == 0); b = {0}; b_substrings = longest_common_substring(b.begin(), b.end(), b.begin(), b.end()); REQUIRE(b_substrings.size() == 1); REQUIRE(b_substrings[0].first == b.begin()); REQUIRE(b_substrings[0].second == b.end()); } TEST_CASE("Longest Common Substring: String cases", "[longest-common-substring]") { std::string a = "asdfghjkl;"; std::string b = "fghasdjlk;"; auto substrings = longest_common_substring(a, b); REQUIRE(substrings.size() == 2); std::sort(substrings.begin(), substrings.end()); REQUIRE(substrings[0] == "asd"); REQUIRE(substrings[1] == "fgh"); } TEST_CASE("Longest Common Substring: Container cases", "[longest-common-substring]") { std::vector<int> a = {1, 2, 3, 4, 5, 6, 7}; std::vector<int> b = {3, 7, 4, 4, 3, 4, 5}; auto substrings = longest_common_substring(a.begin(), a.end(), b.begin(), b.end()); REQUIRE(substrings.size() == 1); REQUIRE(std::vector<int>(substrings[0].first, substrings[0].second) == std::vector<int>{3, 4, 5}); }
31.226415
102
0.642296
camilne
20cd9bcaea5ce1bc2259d381a832ae6a18340fe1
2,742
hpp
C++
OptFrame/Util/ScalarEvaluator.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
2
2018-05-24T11:04:12.000Z
2020-03-03T13:37:07.000Z
OptFrame/Util/ScalarEvaluator.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
null
null
null
OptFrame/Util/ScalarEvaluator.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
1
2019-06-06T16:57:49.000Z
2019-06-06T16:57:49.000Z
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_MULTIOBJECTIVEEVALUATOR_HPP_ #define OPTFRAME_MULTIOBJECTIVEEVALUATOR_HPP_ #include "Evaluator.hpp" #include "Evaluation.hpp" #include "Move.hpp" #include <iostream> using namespace std; namespace optframe { template<class R, class ADS = OPTFRAME_DEFAULT_ADS, class DS = OPTFRAME_DEFAULT_DS> class MultiObjectiveEvaluator: public Evaluator<R, ADS, DS> { protected: vector<Evaluator<R, ADS, DS>*> partialEvaluators; public: using Evaluator<R, ADS, DS>::evaluate; // prevents name hiding MultiObjectiveEvaluator(Evaluator<R, ADS, DS>& e) { partialEvaluators.push_back(&e); } virtual ~MultiObjectiveEvaluator() { } void add(Evaluator<R, ADS, DS>& e) { partialEvaluators.push_back(&e); } virtual Evaluation<DS>& evaluate(const R& r) { double objFunction = 0; double infMeasure = 0; Evaluation<DS>& e = partialEvaluators.at(0)->evaluate(r); objFunction += e.getObjFunction(); infMeasure += e.getInfMeasure(); for (unsigned i = 1; i < partialEvaluators.size(); i++) { partialEvaluators.at(i)->evaluate(e, r); objFunction += e.getObjFunction(); infMeasure += e.getInfMeasure(); } e.setObjFunction(objFunction); e.setInfMeasure(infMeasure); return e; } virtual void evaluate(Evaluation<DS>& e, const R& r) { double objFunction = 0; double infMeasure = 0; for (unsigned i = 0; i < partialEvaluators.size(); i++) { partialEvaluators[i]->evaluate(e, r); objFunction += e.getObjFunction(); infMeasure += e.getInfMeasure(); } e.setObjFunction(objFunction); e.setInfMeasure(infMeasure); } virtual bool betterThan(double a, double b) { return partialEvaluators[0]->betterThan(a, b); } static string idComponent() { return "OptFrame:moev"; } virtual string id() const { return idComponent(); } }; } #endif /*OPTFRAME_MULTIOBJECTIVEEVALUATOR_HPP_*/
23.435897
83
0.716265
216k155
20cf88f3e506226bffa4558f5702a7774f0c1c55
1,900
cpp
C++
EngineTest/TestTileFlip.cpp
petrsnd/tetrad
890221ca730011cac3437b92427d041cbc921db3
[ "MIT" ]
null
null
null
EngineTest/TestTileFlip.cpp
petrsnd/tetrad
890221ca730011cac3437b92427d041cbc921db3
[ "MIT" ]
null
null
null
EngineTest/TestTileFlip.cpp
petrsnd/tetrad
890221ca730011cac3437b92427d041cbc921db3
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include "Engine/Game.h" #include "Engine/GameMechanicsUtil.h" BOOST_AUTO_TEST_CASE( TestPositionFlip ) { { Implbits::Position pos( 0, 0 ); Implbits::Position posflip = FlipPosition( Implbits::Position( 3, 0 ) ); BOOST_CHECK( pos == posflip ); } { Implbits::Position pos( 1, 1 ); Implbits::Position posflip = FlipPosition( Implbits::Position( 2, 1 ) ); BOOST_CHECK( pos == posflip ); } { Implbits::Position pos( 2, 2 ); Implbits::Position posflip = FlipPosition( Implbits::Position( 1, 2 ) ); BOOST_CHECK( pos == posflip ); } { Implbits::Position pos( 3, 3 ); Implbits::Position posflip = FlipPosition( Implbits::Position( 0, 3 ) ); BOOST_CHECK( pos == posflip ); } } BOOST_AUTO_TEST_CASE( TestTileFlip ) { auto tile = Implbits::Tile::Create( 1, Implbits::Position( 2, 3 ), Implbits::TEAM_HOME, Implbits::Game::Ptr() ); auto tileflip = Implbits::Tile::Create( 1, Implbits::Position( 1, 3 ), Implbits::TEAM_AWAY, Implbits::Game::Ptr() ); tileflip->Flip(); BOOST_CHECK( tile.get() != tileflip.get() ); BOOST_CHECK( tile->GetId() == tileflip->GetId() ); BOOST_CHECK( tile->GetOwner() == tileflip->GetOwner() ); BOOST_CHECK( tile->GetPos() == tileflip->GetPos() ); } BOOST_AUTO_TEST_CASE( TestTileFlipTwice ) { auto tile = Implbits::Tile::Create( 1, Implbits::Position( 1, 1 ), Implbits::TEAM_HOME, Implbits::Game::Ptr() ); auto tiledup = Implbits::Tile::Create( 1, Implbits::Position( 1, 1 ), Implbits::TEAM_HOME, Implbits::Game::Ptr() ); tiledup->Flip(); tiledup->Flip(); BOOST_CHECK( tile.get() != tiledup.get() ); BOOST_CHECK( tile->GetId() == tiledup->GetId() ); BOOST_CHECK( tile->GetOwner() == tiledup->GetOwner() ); BOOST_CHECK( tile->GetPos() == tiledup->GetPos() ); }
38
120
0.620526
petrsnd
20d0257f1178916f6dea3a51319aa56b1cdada3d
726
hpp
C++
Framework/Common/BaseApplication.hpp
GameRay/GameEngineFromScratch
96fe4990f743606683cbc93f6a4bdfc7e6ca55db
[ "MIT" ]
null
null
null
Framework/Common/BaseApplication.hpp
GameRay/GameEngineFromScratch
96fe4990f743606683cbc93f6a4bdfc7e6ca55db
[ "MIT" ]
null
null
null
Framework/Common/BaseApplication.hpp
GameRay/GameEngineFromScratch
96fe4990f743606683cbc93f6a4bdfc7e6ca55db
[ "MIT" ]
1
2020-03-06T15:27:24.000Z
2020-03-06T15:27:24.000Z
#pragma once #include "IApplication.hpp" namespace My { class BaseApplication : implements IApplication { public: BaseApplication(GfxConfiguration& cfg); virtual int Initialize(); virtual void Finalize(); // One cycle of the main loop virtual void Tick(); virtual bool IsQuit(); inline GfxConfiguration& GetConfiguration() { return m_Config; }; protected: virtual void OnDraw() {}; protected: // Flag if need quit the main loop of the application static bool m_bQuit; GfxConfiguration m_Config; private: // hide the default construct to enforce a configuration BaseApplication(){}; }; }
22.6875
73
0.625344
GameRay
20d273159b2ef3eb4bfd9719dbfe4f6a1bf7156e
287
cpp
C++
BOJ/10000/10951.cpp
minyong-jeong/hello-algorithm
59f22c25cd4441254cfe91aed634d0a750021ea6
[ "MIT" ]
null
null
null
BOJ/10000/10951.cpp
minyong-jeong/hello-algorithm
59f22c25cd4441254cfe91aed634d0a750021ea6
[ "MIT" ]
null
null
null
BOJ/10000/10951.cpp
minyong-jeong/hello-algorithm
59f22c25cd4441254cfe91aed634d0a750021ea6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { cin.tie(NULL); ios::sync_with_stdio(false); int num1, num2; while (true) { cin >> num1 >> num2; if (cin.eof()) { break; } cout << num1 + num2 << "\n"; } }
14.35
36
0.449477
minyong-jeong
20dd0e723bee057be45aa79aa81930c73d7a233a
193
cpp
C++
07-Algorithm STL/01-Iterator/Pair.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
21
2020-10-03T03:57:19.000Z
2022-03-25T22:41:05.000Z
07-Algorithm STL/01-Iterator/Pair.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
40
2020-10-02T07:02:34.000Z
2021-10-30T16:00:07.000Z
07-Algorithm STL/01-Iterator/Pair.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
90
2020-10-02T07:06:22.000Z
2022-03-25T22:41:17.000Z
#include<iostream> #include<utility> using namespace std; int main() { pair<int,int>p(10,20), p1(30,40); cout<<(p==p1)<<endl; cout<<(p!=p1)<<endl; cout<<(p>p1)<<endl; cout<<(p<p1)<<endl; }
17.545455
34
0.611399
ShreyashRoyzada
22134f220212bbc2e29cea9a2a7dcdbc96c053ef
1,811
cpp
C++
source/ff.dxgi/source/data_blob.cpp
spadapet/ff-engine
244f653c5a25f22f2222842f32608f1101150c6f
[ "MIT" ]
null
null
null
source/ff.dxgi/source/data_blob.cpp
spadapet/ff-engine
244f653c5a25f22f2222842f32608f1101150c6f
[ "MIT" ]
null
null
null
source/ff.dxgi/source/data_blob.cpp
spadapet/ff-engine
244f653c5a25f22f2222842f32608f1101150c6f
[ "MIT" ]
null
null
null
#include "pch.h" #include "data_blob.h" ff::dxgi::data_blob_dx::data_blob_dx(ID3DBlob* blob) : data_blob_dx(blob, 0, blob->GetBufferSize()) {} ff::dxgi::data_blob_dx::data_blob_dx(ID3DBlob* blob, size_t offset, size_t size) : blob(blob) , offset(offset) , size_(size) { assert(blob && offset + size <= blob->GetBufferSize()); } size_t ff::dxgi::data_blob_dx::size() const { return this->size_; } const uint8_t* ff::dxgi::data_blob_dx::data() const { return reinterpret_cast<const uint8_t*>(this->blob->GetBufferPointer()) + this->offset; } std::shared_ptr<ff::data_base> ff::dxgi::data_blob_dx::subdata(size_t offset, size_t size) const { assert(offset + size <= this->size_); return std::make_shared<data_blob_dx>(this->blob.Get(), this->offset + offset, size); } ff::dxgi::data_blob_dxtex::data_blob_dxtex(DirectX::Blob&& blob) : data_blob_dxtex(std::move(blob), 0, blob.GetBufferSize()) {} ff::dxgi::data_blob_dxtex::data_blob_dxtex(DirectX::Blob&& blob, size_t offset, size_t size) : data_blob_dxtex(std::make_shared<DirectX::Blob>(std::move(blob)), offset, size) {} ff::dxgi::data_blob_dxtex::data_blob_dxtex(std::shared_ptr<DirectX::Blob> blob, size_t offset, size_t size) : blob(blob) , offset(offset) , size_(size) { assert(offset + size <= this->blob->GetBufferSize()); } size_t ff::dxgi::data_blob_dxtex::size() const { return this->size_; } const uint8_t* ff::dxgi::data_blob_dxtex::data() const { return reinterpret_cast<const uint8_t*>(this->blob->GetBufferPointer()) + this->offset; } std::shared_ptr<ff::data_base> ff::dxgi::data_blob_dxtex::subdata(size_t offset, size_t size) const { assert(offset + size <= this->size_); return std::make_shared<data_blob_dxtex>(this->blob, this->offset + offset, size); }
28.746032
107
0.696853
spadapet
2217863310194bc24097740123343683c502dd9a
3,863
hpp
C++
source/housys/include/hou/sys/display_mode.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/housys/include/hou/sys/display_mode.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/housys/include/hou/sys/display_mode.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #ifndef HOU_SYS_DISPLAY_MODE_HPP #define HOU_SYS_DISPLAY_MODE_HPP #include "hou/sys/display_format.hpp" #include "hou/sys/sys_config.hpp" #include "hou/mth/matrix.hpp" #include <ostream> #include <vector> namespace hou { /** * Represents a display mode: resolution, format, and refresh rate. */ class HOU_SYS_API display_mode { public: /** * Creates a display_mode object with all fields initialized to zero. */ display_mode(); /** * Creates a display_mode object. * * \param size the size. * * \param df the display format. * * \param refresh_rate the refresh_rate. */ display_mode(const vec2u& size, display_format df, uint refresh_rate) noexcept; /** * Gets the size. * * \return the size. */ const vec2u& get_size() const noexcept; /** * Sets the size. * * \param size the size. */ void set_size(const vec2u& size) noexcept; /** * Gets the pixel format. * * \return the pixel format. */ display_format get_format() const noexcept; /** * Sets the pixel format. * * \param df the pixel format. */ void set_format(display_format df) noexcept; /** * Gets the refresh rate in Hz. * * \return the refresh rate in Hz. */ uint get_refresh_rate() const noexcept; /** * Sets the refresh rate in Hz. * * \param refresh_rate the refresh rate in Hz. */ void set_refresh_rate(uint refresh_rate) noexcept; private: vec2u m_size; display_format m_format; uint m_refresh_rate; }; /** * Checks if two display_mode objects are equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator==( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if two display_mode objects are not equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator!=( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if lhs is less than rhs. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator<( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if lhs is greater than rhs. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator>( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if lhs is less or equal to rhs. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator<=( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if lhs is greater or equal to rhs. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator>=( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Writes a display_mode object into a stream. * * \param os the stream. * * \param vm the display_mode object. * * \return a reference to the stream. */ HOU_SYS_API std::ostream& operator<<(std::ostream& os, const display_mode& vm); namespace prv { /** * Converts an SDL_DisplayMode object into a display_mode object. * * \param mode_in the input object. * * \return the converted object. */ display_mode convert(const SDL_DisplayMode& mode_in); /** * Converts ad display_mode object into an SDL_DisplayMode object. * * \param mode_in the input object. * * \return the converted object. */ SDL_DisplayMode convert(const display_mode& mode_in); } // namespace prv } // namespace hou #endif
19.029557
81
0.676676
DavideCorradiDev
2218677dfcf3ba87190b9b29b2c9043a919cd5e5
531
cpp
C++
EventHandler/EventHandler_DemoSeek.cpp
chen0040/cpp-steering-behaviors
c73d2ae8037556d42440b54ba6eb6190e467fae9
[ "MIT" ]
2
2020-11-10T12:24:41.000Z
2021-09-25T08:24:06.000Z
EventHandler/EventHandler_DemoSeek.cpp
chen0040/cpp-steering-behaviors
c73d2ae8037556d42440b54ba6eb6190e467fae9
[ "MIT" ]
null
null
null
EventHandler/EventHandler_DemoSeek.cpp
chen0040/cpp-steering-behaviors
c73d2ae8037556d42440b54ba6eb6190e467fae9
[ "MIT" ]
1
2021-08-14T16:34:33.000Z
2021-08-14T16:34:33.000Z
#include "EventHandler_DemoSeek.h" #include "../GameWorld/GameWorld.h" #include "../GLStates/GLState_Seek.h" EventHandler_DemoSeek::EventHandler_DemoSeek(GLUIObj* pSubject) : GLActionListener(pSubject) , m_pWorld(NULL) { } EventHandler_DemoSeek::~EventHandler_DemoSeek() { } void EventHandler_DemoSeek::SetWorld(GameWorld* pWorld) { m_pWorld=pWorld; } void EventHandler_DemoSeek::MouseButtonDown(const int &iButton, const int &iX, const int &iY, const int &iXRel, const int &iYRel) { m_pWorld->ChangeState(&glState_Seek); }
21.24
129
0.775895
chen0040
221d6faa32e8595da0b1bd6ff086a65a8110a646
3,555
cpp
C++
tests/test-hdr/ordered_list/hdr_lazy_kv_rcu_shb.cpp
TatyanaBerlenko/libcds
3f4dfab2aea72d70ce44e7fbc02da9a6908f0781
[ "BSD-2-Clause" ]
2
2016-12-03T22:09:50.000Z
2021-08-31T12:44:24.000Z
tests/test-hdr/ordered_list/hdr_lazy_kv_rcu_shb.cpp
TatyanaBerlenko/libcds
3f4dfab2aea72d70ce44e7fbc02da9a6908f0781
[ "BSD-2-Clause" ]
null
null
null
tests/test-hdr/ordered_list/hdr_lazy_kv_rcu_shb.cpp
TatyanaBerlenko/libcds
3f4dfab2aea72d70ce44e7fbc02da9a6908f0781
[ "BSD-2-Clause" ]
2
2018-05-26T19:27:12.000Z
2021-08-31T12:44:28.000Z
//$$CDS-header$$ #include "ordered_list/hdr_lazy_kv.h" #include <cds/urcu/signal_buffered.h> #include <cds/container/lazy_kvlist_rcu.h> namespace ordlist { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED namespace { typedef cds::urcu::gc< cds::urcu::signal_buffered<> > rcu_type; struct RCU_SHB_cmp_traits : public cc::lazy_list::traits { typedef LazyKVListTestHeader::cmp<LazyKVListTestHeader::key_type> compare; }; } #endif void LazyKVListTestHeader::RCU_SHB_cmp() { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED // traits-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, RCU_SHB_cmp_traits > list; test_rcu< list >(); // option-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, cc::lazy_list::make_traits< cc::opt::compare< cmp<key_type> > >::type > opt_list; test_rcu< opt_list >(); #endif } #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED namespace { struct RCU_SHB_less_traits: public cc::lazy_list::traits { typedef LazyKVListTestHeader::lt<LazyKVListTestHeader::key_type> less; }; } #endif void LazyKVListTestHeader::RCU_SHB_less() { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED // traits-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, RCU_SHB_less_traits > list; test_rcu< list >(); // option-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, cc::lazy_list::make_traits< cc::opt::less< lt<key_type> > >::type > opt_list; test_rcu< opt_list >(); #endif } #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED namespace { struct RCU_SHB_cmpmix_traits: public cc::lazy_list::traits { typedef LazyKVListTestHeader::cmp<LazyKVListTestHeader::key_type> compare; typedef LazyKVListTestHeader::lt<LazyKVListTestHeader::key_type> less; }; } #endif void LazyKVListTestHeader::RCU_SHB_cmpmix() { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED // traits-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, RCU_SHB_cmpmix_traits > list; test_rcu< list >(); // option-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, cc::lazy_list::make_traits< cc::opt::compare< cmp<key_type> > ,cc::opt::less< lt<key_type> > >::type > opt_list; test_rcu< opt_list >(); #endif } #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED namespace { struct RCU_SHB_ic_traits: public cc::lazy_list::traits { typedef LazyKVListTestHeader::lt<LazyKVListTestHeader::key_type> less; typedef cds::atomicity::item_counter item_counter; }; } #endif void LazyKVListTestHeader::RCU_SHB_ic() { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED // traits-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, RCU_SHB_ic_traits > list; test_rcu< list >(); // option-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, cc::lazy_list::make_traits< cc::opt::less< lt<key_type> > ,cc::opt::item_counter< cds::atomicity::item_counter > >::type > opt_list; test_rcu< opt_list >(); #endif } } // namespace ordlist
28.902439
93
0.627848
TatyanaBerlenko
2221d8c3f785527fe82e4b088a483f0a12017919
7,967
cc
C++
talk/p2p/base/p2ptransport.cc
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
5
2015-09-16T06:10:59.000Z
2019-12-25T05:30:00.000Z
talk/p2p/base/p2ptransport.cc
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
null
null
null
talk/p2p/base/p2ptransport.cc
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
3
2015-08-01T11:38:08.000Z
2019-11-01T05:16:09.000Z
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/p2p/base/p2ptransport.h" #include "talk/base/common.h" #include "talk/p2p/base/candidate.h" #include "talk/p2p/base/constants.h" #include "talk/base/helpers.h" #include "talk/p2p/base/p2ptransportchannel.h" #include "talk/p2p/base/sessionmanager.h" #include "talk/xmllite/qname.h" #include "talk/xmllite/xmlelement.h" #include "talk/xmpp/constants.h" namespace { // We only allow usernames to be this many characters or fewer. const size_t kMaxUsernameSize = 16; } // namespace namespace cricket { const std::string kNsP2pTransport("http://www.google.com/transport/p2p"); const buzz::QName kQnP2pTransport(true, kNsP2pTransport, "transport"); const buzz::QName kQnP2pCandidate(true, kNsP2pTransport, "candidate"); const buzz::QName kQnP2pUnknownChannelName(true, kNsP2pTransport, "unknown-channel-name"); P2PTransport::P2PTransport(SessionManager* session_manager) : Transport(session_manager, kNsP2pTransport) { } P2PTransport::~P2PTransport() { DestroyAllChannels(); } buzz::XmlElement* P2PTransport::CreateTransportOffer() { return new buzz::XmlElement(kQnP2pTransport, true); } buzz::XmlElement* P2PTransport::CreateTransportAnswer() { return new buzz::XmlElement(kQnP2pTransport, true); } bool P2PTransport::OnTransportOffer(const buzz::XmlElement* elem) { ASSERT(elem->Name() == kQnP2pTransport); // We don't support any options, so we ignore them. return true; } bool P2PTransport::OnTransportAnswer(const buzz::XmlElement* elem) { ASSERT(elem->Name() == kQnP2pTransport); // We don't support any options. We fail if any are given. The other side // should know from our request that we expected an empty response. return elem->FirstChild() == NULL; } bool P2PTransport::OnTransportMessage(const buzz::XmlElement* msg, const buzz::XmlElement* stanza) { ASSERT(msg->Name() == kQnP2pTransport); for (const buzz::XmlElement* elem = msg->FirstElement(); elem != NULL; elem = elem->NextElement()) { if (elem->Name() == kQnP2pCandidate) { // Make sure this candidate is valid. Candidate candidate; if (!ParseCandidate(stanza, elem, &candidate)) return false; ForwardChannelMessage(elem->Attr(buzz::QN_NAME), new buzz::XmlElement(*elem)); } } return true; } bool P2PTransport::OnTransportError(const buzz::XmlElement* session_msg, const buzz::XmlElement* error) { ASSERT(error->Name().Namespace() == kNsP2pTransport); if ((error->Name() == kQnP2pUnknownChannelName) && error->HasAttr(buzz::QN_NAME)) { std::string channel_name = error->Attr(buzz::QN_NAME); if (HasChannel(channel_name)) { SignalChannelGone(this, channel_name); } } return true; } void P2PTransport::OnTransportChannelMessages( const std::vector<buzz::XmlElement*>& candidates) { buzz::XmlElement* transport = new buzz::XmlElement(kQnP2pTransport, true); for (size_t i = 0; i < candidates.size(); ++i) transport->AddElement(candidates[i]); std::vector<buzz::XmlElement*> elems; elems.push_back(transport); SignalTransportMessage(this, elems); } bool P2PTransport::ParseCandidate(const buzz::XmlElement* stanza, const buzz::XmlElement* elem, Candidate* candidate) { // Check for all of the required attributes. if (!elem->HasAttr(buzz::QN_NAME) || !elem->HasAttr(QN_ADDRESS) || !elem->HasAttr(QN_PORT) || !elem->HasAttr(QN_USERNAME) || !elem->HasAttr(QN_PREFERENCE) || !elem->HasAttr(QN_PROTOCOL) || !elem->HasAttr(QN_GENERATION)) { return BadRequest(stanza, "candidate missing required attribute", NULL); } // Make sure the channel named actually exists. if (!HasChannel(elem->Attr(buzz::QN_NAME))) { scoped_ptr<buzz::XmlElement> extra_info(new buzz::XmlElement(kQnP2pUnknownChannelName)); extra_info->AddAttr(buzz::QN_NAME, elem->Attr(buzz::QN_NAME)); return BadRequest(stanza, "channel named in candidate does not exist", extra_info.get()); } // Parse the address given. talk_base::SocketAddress address; if (!ParseAddress(stanza, elem, &address)) return false; candidate->set_name(elem->Attr(buzz::QN_NAME)); candidate->set_address(address); candidate->set_username(elem->Attr(QN_USERNAME)); candidate->set_preference_str(elem->Attr(QN_PREFERENCE)); candidate->set_protocol(elem->Attr(QN_PROTOCOL)); candidate->set_generation_str(elem->Attr(QN_GENERATION)); // Check that the username is not too long and does not use any bad chars. if (candidate->username().size() > kMaxUsernameSize) return BadRequest(stanza, "candidate username is too long", NULL); if (!IsBase64Encoded(candidate->username())) return BadRequest(stanza, "candidate username has non-base64 encoded characters", NULL); // Look for the non-required attributes. if (elem->HasAttr(QN_PASSWORD)) candidate->set_password(elem->Attr(QN_PASSWORD)); if (elem->HasAttr(buzz::QN_TYPE)) candidate->set_type(elem->Attr(buzz::QN_TYPE)); if (elem->HasAttr(QN_NETWORK)) candidate->set_network_name(elem->Attr(QN_NETWORK)); return true; } buzz::XmlElement* P2PTransport::TranslateCandidate(const Candidate& c) { buzz::XmlElement* candidate = new buzz::XmlElement(kQnP2pCandidate); candidate->SetAttr(buzz::QN_NAME, c.name()); candidate->SetAttr(QN_ADDRESS, c.address().IPAsString()); candidate->SetAttr(QN_PORT, c.address().PortAsString()); candidate->SetAttr(QN_PREFERENCE, c.preference_str()); candidate->SetAttr(QN_USERNAME, c.username()); candidate->SetAttr(QN_PROTOCOL, c.protocol()); candidate->SetAttr(QN_GENERATION, c.generation_str()); if (c.password().size() > 0) candidate->SetAttr(QN_PASSWORD, c.password()); if (c.type().size() > 0) candidate->SetAttr(buzz::QN_TYPE, c.type()); if (c.network_name().size() > 0) candidate->SetAttr(QN_NETWORK, c.network_name()); return candidate; } TransportChannelImpl* P2PTransport::CreateTransportChannel( const std::string& name, const std::string &session_type) { return new P2PTransportChannel( name, session_type, this, session_manager()->port_allocator()); } void P2PTransport::DestroyTransportChannel(TransportChannelImpl* channel) { delete channel; } } // namespace cricket
37.938095
80
0.702648
udit043
22283dbfb773142e676b11005e62a63f25061cbf
4,747
cpp
C++
check/core/matrix/dense/dense_matrix/test/get_col_segment.cpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
check/core/matrix/dense/dense_matrix/test/get_col_segment.cpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
check/core/matrix/dense/dense_matrix/test/get_col_segment.cpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
#include "../test.hpp" #include <queue> TYPED_TEST(DenseMatrixTest_ColMajor_Size8x5_Pitch8, GetColSegment) { const auto pitch = this->pitch_; const auto capacity = this->capacity_; const auto offset = this->offset_; const auto mat = this->mat_; const auto valptr0 = this->valptr0_; const mcnla::index_t colidx = 2; const mcnla::index_t row0 = 3, rows = 5; auto segment = mat({row0, row0+rows}, colidx); EXPECT_EQ(segment.len(), rows); EXPECT_EQ(segment.nelem(), rows); EXPECT_EQ(segment.stride(), 1); EXPECT_TRUE(segment.isShrunk()); EXPECT_EQ(segment.capacity(), capacity - (row0 + colidx*pitch)); EXPECT_EQ(segment.offset(), offset + row0 + colidx*pitch); EXPECT_EQ(segment.valPtr(), &(mat(row0, colidx))); for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), mat(i+row0, colidx)); } for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), valptr0[offset + (i+row0) + colidx*pitch]); } std::queue<TypeParam> tmp; for ( auto i = 0; i < rows; ++i ) { tmp.push(valptr0[offset + (i+row0) + colidx*pitch]); } for ( auto value : segment ) { EXPECT_EQ(value, tmp.front()); tmp.pop(); } EXPECT_EQ(tmp.size(), 0); } TYPED_TEST(DenseMatrixTest_ColMajor_Size8x5_Pitch10, GetColSegment) { const auto pitch = this->pitch_; const auto capacity = this->capacity_; const auto offset = this->offset_; const auto mat = this->mat_; const auto valptr0 = this->valptr0_; const mcnla::index_t colidx = 2; const mcnla::index_t row0 = 3, rows = 5; auto segment = mat({row0, row0+rows}, colidx); EXPECT_EQ(segment.len(), rows); EXPECT_EQ(segment.nelem(), rows); EXPECT_EQ(segment.stride(), 1); EXPECT_TRUE(segment.isShrunk()); EXPECT_EQ(segment.capacity(), capacity - (row0 + colidx*pitch)); EXPECT_EQ(segment.offset(), offset + row0 + colidx*pitch); EXPECT_EQ(segment.valPtr(), &(mat(row0, colidx))); for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), mat(i+row0, colidx)); } for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), valptr0[offset + (i+row0) + colidx*pitch]); } std::queue<TypeParam> tmp; for ( auto i = 0; i < rows; ++i ) { tmp.push(valptr0[offset + (i+row0) + colidx*pitch]); } for ( auto value : segment ) { EXPECT_EQ(value, tmp.front()); tmp.pop(); } EXPECT_EQ(tmp.size(), 0); } TYPED_TEST(DenseMatrixTest_RowMajor_Size8x5_Pitch5, GetColSegment) { const auto pitch = this->pitch_; const auto capacity = this->capacity_; const auto offset = this->offset_; const auto mat = this->mat_; const auto valptr0 = this->valptr0_; const mcnla::index_t colidx = 2; const mcnla::index_t row0 = 3, rows = 5; auto segment = mat({row0, row0+rows}, colidx); EXPECT_EQ(segment.len(), rows); EXPECT_EQ(segment.nelem(), rows); EXPECT_EQ(segment.stride(), pitch); EXPECT_FALSE(segment.isShrunk()); EXPECT_EQ(segment.capacity(), capacity - (row0*pitch + colidx)); EXPECT_EQ(segment.offset(), offset + row0*pitch + colidx); EXPECT_EQ(segment.valPtr(), &(mat(row0, colidx))); for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), mat(i+row0, colidx)); } for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), valptr0[offset + (i+row0)*pitch + colidx]); } std::queue<TypeParam> tmp; for ( auto i = 0; i < rows; ++i ) { tmp.push(valptr0[offset + (i+row0)*pitch + colidx]); } for ( auto value : segment ) { EXPECT_EQ(value, tmp.front()); tmp.pop(); } EXPECT_EQ(tmp.size(), 0); } TYPED_TEST(DenseMatrixTest_RowMajor_Size8x5_Pitch10, GetColSegment) { const auto pitch = this->pitch_; const auto capacity = this->capacity_; const auto offset = this->offset_; const auto mat = this->mat_; const auto valptr0 = this->valptr0_; const mcnla::index_t colidx = 2; const mcnla::index_t row0 = 3, rows = 5; auto segment = mat({row0, row0+rows}, colidx); EXPECT_EQ(segment.len(), rows); EXPECT_EQ(segment.nelem(), rows); EXPECT_EQ(segment.stride(), pitch); EXPECT_FALSE(segment.isShrunk()); EXPECT_EQ(segment.capacity(), capacity - (row0*pitch + colidx)); EXPECT_EQ(segment.offset(), offset + row0*pitch + colidx); EXPECT_EQ(segment.valPtr(), &(mat(row0, colidx))); for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), mat(i+row0, colidx)); } for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), valptr0[offset + (i+row0)*pitch + colidx]); } std::queue<TypeParam> tmp; for ( auto i = 0; i < rows; ++i ) { tmp.push(valptr0[offset + (i+row0)*pitch + colidx]); } for ( auto value : segment ) { EXPECT_EQ(value, tmp.front()); tmp.pop(); } EXPECT_EQ(tmp.size(), 0); }
27.281609
69
0.629029
emfomy
222a85381650c07b7396b04dae5f5179d22a6412
4,445
cc
C++
smallest-string-with-swaps.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
smallest-string-with-swaps.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
smallest-string-with-swaps.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <unordered_map> #include <unordered_set> #include <deque> #include <algorithm> class Solution { public: std::string smallestStringWithSwaps(std::string s, const std::vector<std::vector<int>> &pairs) { return smallestStringWithSwapsUnionFind(s, pairs); } std::string smallestStringWithSwapsBFS(std::string &s, const std::vector<std::vector<int>> &pairs) { std::unordered_map<int, std::unordered_set<int>> graph; for (const auto &pair : pairs) { graph[pair[0]].insert(pair[1]); graph[pair[1]].insert(pair[0]); } std::vector<std::vector<int>> con_comps; std::unordered_set<int> visit; std::deque<int> q; for (const auto &[ind, nexts] : graph) { if (!visit.count(ind)) visit.insert(ind); q.push_back(ind); con_comps.emplace_back(); while (!q.empty()) { int cur_ind = q.front(); q.pop_front(); con_comps.back().push_back(cur_ind); for (const auto next : graph[cur_ind]) if (!visit.count(next)) { q.push_back(next); visit.insert(next); } } } for (auto &con_comp : con_comps) std::sort(con_comp.begin(), con_comp.end()); std::string temp; for (const auto &con_comp : con_comps) { temp.clear(); for (const auto con_ind : con_comp) temp.push_back(s[con_ind]); std::sort(temp.begin(), temp.end()); for (int i = 0; i < temp.size(); i++) s[con_comp[i]] = temp[i]; } return s; } std::string smallestStringWithSwapsUnionFind(std::string &s, const std::vector<std::vector<int>> &pairs) { class UnionFind { private: std::unordered_map<int, int> parent; public: void add(int num) { if (auto iter = parent.find(num); iter == parent.end()) parent.insert(iter, {num, -1}); } void merge(int a, int b) { int root_a = find(a); int root_b = find(b); if (root_a != root_b) { // cout << "merge: root_a = " << root_a << ", root_b = " << root_b << endl; parent.at(root_a) = root_b; } } int find(int num) { int root = num; while (parent.at(root) != -1) root = parent.at(root); // cout << "find " << num << ", root = " << root << endl; while (num != root) { int num_parent = parent.at(num); parent.at(num) = root; // cout << "update num = " << num << ", root = " << root << endl; num = num_parent; } return root; } bool is_connected(int a, int b) { return find(a) == find(b); } }; UnionFind union_find; for (const auto &pair : pairs) { union_find.add(pair[0]); union_find.add(pair[1]); union_find.merge(pair[0], pair[1]); } std::unordered_map<int, std::vector<int>> con_comps; std::unordered_set<int> visit; for (const auto &pair : pairs) for (const auto num : pair) if (visit.insert(num).second) con_comps[union_find.find(num)].push_back(num); std::string temp; for (auto &[root, con_comp] : con_comps) { temp.clear(); std::sort(con_comp.begin(), con_comp.end()); for (const auto ind : con_comp) { // cout << ind << ", "; temp.push_back(s[ind]); } // cout << endl; std::sort(temp.begin(), temp.end()); for (int i = 0; i < temp.size(); i++) s[con_comp[i]] = temp[i]; } return s; } };
27.608696
108
0.434196
ArCan314
222abc64ceb4057739ba03d319b4da15a1daac47
258
cpp
C++
beep/main.cpp
ImprobabilityCast/Small-Projects
febfa7090dd6ec78888b2068f6d62b28216330bd
[ "MIT" ]
1
2022-02-13T01:43:40.000Z
2022-02-13T01:43:40.000Z
beep/main.cpp
ImprobabilityCast/Small-Projects
febfa7090dd6ec78888b2068f6d62b28216330bd
[ "MIT" ]
null
null
null
beep/main.cpp
ImprobabilityCast/Small-Projects
febfa7090dd6ec78888b2068f6d62b28216330bd
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #if _WIN32_WINNT < 0x0500 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #include <windows.h> int WinMain(HINSTANCE h, HINSTANCE h2, LPSTR whoKnows, int it) { Beep(0x320, 200); return 0; }
18.428571
62
0.686047
ImprobabilityCast
2232382c030235114b881763c556723d34a8d7e6
11,876
cxx
C++
StRoot/StEmcPool/StBarrelCalib2008/StBarrelMonitorMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StEmcPool/StBarrelCalib2008/StBarrelMonitorMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StEmcPool/StBarrelCalib2008/StBarrelMonitorMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
// *-- Author : Jan Balewski // // $Id: StBarrelMonitorMaker.cxx,v 1.5 2012/12/12 22:05:09 fisyak Exp $ #ifdef __APPLE__ #include <sys/types.h> #endif #include <TFile.h> #include <TH1.h> #include <TH2.h> #include <TH3.h> #include <StMessMgr.h> #include "StBarrelMonitorMaker.h" #include "StJanBarrelDbMaker.h" #include "JanBprsEveA.h" #include "BprsCapPolygraph.h" #include "BarrelMipCalib.h" #include "StMuDSTMaker/COMMON/StMuEvent.h" #include "StMuDSTMaker/COMMON/StMuDst.h" #include "StMuDSTMaker/COMMON/StMuDstMaker.h" #include "StEmcRawMaker/defines.h" #include "StEmcUtil/geometry/StEmcGeom.h" #include "StDetectorDbMaker/St_tpcGasC.h" #include "St_db_Maker/St_db_Maker.h" #include "StEmcUtil/database/StEmcDecoder.h" #include "StEventTypes.h" #include "StMcEventTypes.hh" #include "StMcEvent.hh" ClassImp(StBarrelMonitorMaker) //________________________________________________ //________________________________________________ StBarrelMonitorMaker::StBarrelMonitorMaker( const char* self ): StMaker(self){ cTile[0]='T'; cTile[1]='P'; cTile4[0]="BTOW"; cTile4[1]="BPRS"; nInpEve=nAcceptEve=nTrigEve=nCorrEve= mGeantEveInp=0; setHList(0); setTrigIdFilter(0); setMC(0); mMappB=0; hBprs3D=0;// special very large 3D histo for BPRS cap monitoring setBprsHisto(1); setCalibPass(0); } //________________________________________________ //________________________________________________ Int_t StBarrelMonitorMaker::Init(){ assert(HList); initHistos(); mBtowGeom = StEmcGeom::instance("bemc"); mBprsGeom = StEmcGeom::instance("bprs"); mSmdEGeom = StEmcGeom::instance("bsmde"); mSmdPGeom = StEmcGeom::instance("bsmdp"); // needed only to map m-s-e --> softID mMuDstMaker = (StMuDstMaker*)GetMaker("MuDst"); assert(mMuDstMaker); mJanDbMaker = (StJanBarrelDbMaker*)GetMaker("janBarrelDb"); assert(mJanDbMaker); bprsPolygraph=new BprsCapPolygraph(HList, mJanDbMaker) ; bprsPolygraph->setCut(50, 0.98,1,0.1); bprsPolygraph->print(); mipCalib=new BarrelMipCalib(HList, mJanDbMaker, mMuDstMaker) ; mipCalib->setCut(60.,0.35,1.3,0.51, 3.3, 1.0, 180); // zV, pT, eta, nFit, dedx, zMargin, Rxy mipCalib->print(); LOG_INFO<<Form("::Init() filter trigID=%d done", trigID)<<endm; return StMaker::Init(); } //________________________________________________ //________________________________________________ Int_t StBarrelMonitorMaker::InitRun(int runNo){ LOG_INFO<<Form("::InitRun(%d) start",runNo)<<endm; St_db_Maker* mydb = (St_db_Maker*) StMaker::GetChain()->GetMaker("StarDb"); assert(mydb); // this is how BTOW mapping is accesible mMappB = new StEmcDecoder(mydb->GetDateTime().GetDate(),mydb->GetDateTime().GetTime()); float airPres=St_tpcGasC::instance()-> barometricPressure(); LOG_INFO<<Form("::InitRun(%d) AirPressure=%.2f",runNo, airPres)<<endm; if(runNo==1000000) { LOG_WARN<<Form("::InitRun(%d) ??? , it is OK for M-C ",runNo)<<endm; } LOG_INFO<<Form("::InitRun() algo params: bprsHisto=%d calibPass=%d (bits)", par_bprsHisto,par_calibPass )<<endm; return kStOK; } //________________________________________________ //________________________________________________ Int_t StBarrelMonitorMaker::Finish(){ gMessMgr->Message("","I") <<GetName()<<"::Finish()\n inputEve="<<nInpEve<<" trigFilterEve="<<nTrigEve<<" nCorrEve="<<nCorrEve<<" nAcceptEve="<<nAcceptEve<<endm; return kStOK; } //________________________________________________ //________________________________________________ void StBarrelMonitorMaker::Clear(const Option_t*){ eventID=-999; janEve.clear(); for( int icr=0; icr <mxBprsCrate;icr++) janBprsEveA[icr].clear(); } //________________________________________________ //________________________________________________ //________________________________________________ Int_t StBarrelMonitorMaker::Make(){ nInpEve++; StMuEvent* muEve = mMuDstMaker->muDst()->event(); eventID=muEve->eventId(); janEve.id=eventID; int nPrimV=mMuDstMaker->muDst()->numberOfPrimaryVertices(); LOG_INFO <<GetName()<<"\n\n::Make()================ isMC="<<isMC<<" eveID="<<eventID<<" nInpEve="<<nInpEve<<" nPrimV="<<nPrimV<<endm; vector<unsigned int> trgL=mMuDstMaker->muDst()->event()->triggerIdCollection().nominal().triggerIds(); printf("trigL len=%d\n",int(trgL.size())); uint ii; for( ii=0;ii<trgL.size();ii++) printf("ii=%d trigID=%d\n",ii,trgL[ii]); if (mMuDstMaker->muDst()->event()->triggerIdCollection().nominal().isTrigger(19)) return kStOK; // drop bbc-fast events // printf("trigOK\n"); // nTrigEve++; unpackStTiles(kBTow); unpackStTiles(kBPrs); populateBprsEveA(); // ...... check for BPRS capID corruption ..... for(int bprsCrateID=0; bprsCrateID<mxBprsCrate; bprsCrateID++) // int bprsCrateID=2; { JanBprsEveA &bprsEve=janBprsEveA[bprsCrateID]; bprsPolygraph->doBaseline(bprsEve,janEve); bprsPolygraph->findBestCap(bprsEve,janEve); bprsPolygraph->doPedResidua(bprsEve); if(par_calibPass & kPassCapFix) // do correct capID corruption janEve.bprsCap[bprsCrateID]=bprsEve.getBestCapID(); } //if(nInpEve<3) janEve.print(2); calibrateTiles(kBPrs); calibrateTiles(kBTow); // mipCalib->search(janEve); // full analysis // mipCalib->searchEtaBin20(janEve); // just last eta bin location return kStOK; } //___________________ _____________________________ //________________________________________________ StBarrelMonitorMaker::~StBarrelMonitorMaker(){ } //___________________ _____________________________ //________________________________________________ void StBarrelMonitorMaker::saveHisto(TString fname){ TString outName=fname+".hist.root"; TFile f( outName,"recreate"); assert(f.IsOpen()); printf("HHH %d histos are written to '%s' ...\n",HList->GetEntries(),outName.Data()); HList->Write(); f.Close(); } //________________________________________________ //________________________________________________ void StBarrelMonitorMaker::unpackStTiles(int ibp){ StEvent *mEvent = (StEvent*)StMaker::GetChain()-> GetInputDS("StEvent"); assert(mEvent); //......................... BTOW or BPRS .................... //use StEvent as default to get simulation right in BEMC StEmcCollection *emc = mEvent->emcCollection(); assert (emc); int jBP=BTOW; StEmcDetector* detector=emc->detector(kBarrelEmcTowerId); StEmcGeom *geomB=mBtowGeom; if( ibp==kBPrs) {// change pointers for preshower jBP=BPRS; geomB=mBprsGeom; detector=emc->detector(kBarrelEmcPreShowerId); } if(!detector) { printf("no %s data, nInpEve=%d\n",cTile4[ibp],nInpEve); return; } // for BPRS unpack caps and store locally if(ibp==kBPrs ) { for(int icr=0;icr<mxBprsCrate;icr++) { StEmcModule* module = detector->module(2+icr*30);assert(module); StSPtrVecEmcRawHit& rawHit=module->hits(); if(rawHit.size()<=0) { printf("ss icr=%d n=%dL, ABORT BpRS for this event\n",icr,int(rawHit.size())); return ; } assert(rawHit.size()>0); janEve.bprsCap[icr]= rawHit[10]->calibrationType(); // tmp if(icr==3) janEve.bprsCap[icr]= rawHit[32]->calibrationType(); } } // unpack raw data and store it locally in an array for(Int_t m = 1; m <= 120; ++m) { StEmcModule* module = detector->module(m); //printf("MMM %s m=%p mod=%d\n",cTile4[ibp],module,m); if(!module) continue; StSPtrVecEmcRawHit& rawHit=module->hits(); // printf("HHH n=%d\n",rawHit.size()); for(UInt_t k = 0; k < rawHit.size(); ++k){ int id; Int_t m=rawHit[k]->module(); Int_t e=rawHit[k]->eta(); Int_t s=abs(rawHit[k]->sub()); float rawAdc=rawHit[k]->adc()+0.5;// return middle of the bin //Get software tower id to get DaqID geomB->getId(m,e,s,id); #if 0 // tmp for Matt, to QA new mapping if(ibp==kBPrs ){ int id1=(int)mJanDbMaker->bprsReMap()->GetBinContent(id); printf("BPRSX %d %d %d %d\n",nInpEve-1,id1,rawHit[k]->adc(),rawHit[k]->calibrationType()); } // end tmp #endif assert(id>=1); assert(id<=mxBtow); janEve.rawAdcTile[ibp][id-1]=rawAdc; // if(id%20==7) // if(ibp==kBPrs && (id>650 && id<710)) printf("unpack %s hit=%d softid=%d, m=%d rawADC=%.1f\n",cTile4[ibp],k,id,m,rawAdc); } }// end of module loop janEve.tileIn[ibp]=1; // tag data block as delivered assert(!isMC); // verify peds for MC } //________________________________________________ //________________________________________________ void StBarrelMonitorMaker::calibrateTiles(int ibp){ // printf("ZZ %d %d\n",ibp, janEve.tileIn[ibp]); if(janEve.tileIn[ibp]==0) return; // no data in this event for(int id0=0; id0<mxBtow; id0++) { int id=id0+1; int crateID=0; int capID=0; int stat =mJanDbMaker->statTile(ibp,id); if(ibp==kBPrs ) { crateID= mJanDbMaker->bprsCrate(id); capID=janEve.bprsCap[crateID]; //fix capID corruption in 2008 } float ped =mJanDbMaker->pedTile(ibp,id,capID); float rawAdc =janEve.rawAdcTile[ibp][id0]; // if(ibp==kBPrs) printf("ss id=%d stat=%d rawAdc=%.1f\n", id,stat,rawAdc); if(ibp==kBPrs && rawAdc>100 && rawAdc<300){ //accumulate pedestals vs. capID similat to Tonko's on-line approach hTonko0->Fill(id,capID,1.); hTonko1->Fill(id,capID,rawAdc); hTonko2->Fill(id,capID,rawAdc*rawAdc); } if(!(par_calibPass & kPassPedSub)) { hTile[ibp]->Fill(id,rawAdc); if(par_bprsHisto==2) hBprs3D->Fill(id,rawAdc,capID); } if(par_calibPass==0) continue; // no swap info loaded in this mode //------ TMP ----- apply BPRS & BTOW swap only for ped-corrected ADC data if(ibp==kBTow) { id=(int)mJanDbMaker->btowReMap()->GetBinContent(id); } else if(ibp==kBPrs) { id=(int)mJanDbMaker->bprsReMap()->GetBinContent(id); } else assert(1==2); // below use only 'id' for indexing to pick up this swaping if(stat) { janEve.statTile[ibp][id-1]=stat; // is bad continue; } else { janEve.statTile[ibp][id-1]=0; // is good } float adc=rawAdc-ped; janEve.adcTile[ibp][id-1]= adc; if(par_calibPass & kPassPedSub){ hTile[ibp]->Fill(id,adc); if(ibp==kBPrs){ // later add alos BTOW histos per crate, fix it hBprsA[crateID]->Fill(adc); if(par_bprsHisto==2) hBprs3D->Fill(id,adc,capID); } } //..... energy calibration goes here, later //... } // end of data loop } //________________________________________________ //________________________________________________ void StBarrelMonitorMaker::populateBprsEveA(){ if(janEve.tileIn[kBPrs]==0) return; // no data in this event for( int icr=0; icr <mxBprsCrate;icr++) { int capID=janEve.bprsCap[icr]; janBprsEveA[icr].set(capID,icr,eventID); } int ibp=kBPrs; for(int id0=0; id0<mxBtow; id0++) { int id=id0+1; int icr=mJanDbMaker->bprsCrate(id); float rawAdc =janEve.rawAdcTile[ibp][id0]; janBprsEveA[icr].addRawValue(id,rawAdc); //printf("id=%d, icr=%d \n",id,icr); } } //--------------------------------------------------- // $Log: StBarrelMonitorMaker.cxx,v $ // Revision 1.5 2012/12/12 22:05:09 fisyak // add sys/types.h include for APPLE // // Revision 1.4 2009/08/25 16:17:48 fine // fix the compilation issues under SL5_64_bits gcc 4.3.2 // // Revision 1.3 2009/08/25 16:08:04 fine // fix the compilation issues under SL5_64_bits gcc 4.3.2 // // Revision 1.2 2009/02/04 20:33:32 ogrebeny // Moved the EEMC database functionality from StEEmcDbMaker to StEEmcUtil/database. See ticket http://www.star.bnl.gov/rt2/Ticket/Display.html?id=1388 // // Revision 1.1 2008/11/24 23:06:35 balewski // start //
29.542289
165
0.674133
xiaohaijin
2232c20a6c1a4c2a04f3a89074d07b5007312040
2,608
cpp
C++
storage/src/Storage.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
storage/src/Storage.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
storage/src/Storage.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
#include "storage/Storage.h" #include <yaml-cpp/yaml.h> #include <filesystem> #include <fstream> #include <string> namespace storage::key { const std::string row = "row"; const std::string col = "col"; const std::string pos = "pos"; const std::string value = "value"; } // namespace storage::key namespace YAML { template <> struct convert<common::Position> { static Node encode(const common::Position& pos) { Node node; node[storage::key::row] = pos.row; node[storage::key::col] = pos.col; return node; } static bool decode(const Node& node, common::Position& pos) { pos.row = node[storage::key::row].as<common::Index>(); pos.col = node[storage::key::col].as<common::Index>(); return true; } }; template <> struct convert<common::NewAction> { static Node encode(const common::NewAction& action) { Node node; node[storage::key::pos] = action.pos; node[storage::key::value] = action.value; return node; } static bool decode(const Node& node, common::NewAction& action) { action.pos = node[storage::key::pos].as<common::Position>(); action.value = node[storage::key::value].as<common::Value>(); return true; } }; } // namespace YAML namespace storage { const std::string fileName = "game.yaml"; namespace key { const std::string bestScore = "bestScore"; const std::string score = "score"; const std::string isGameOver = "isGameOver"; const std::string rows = "rows"; const std::string cols = "cols"; const std::string newActions = "newActions"; } // namespace key use_case_interface::GameData Storage::loadGame() { try { YAML::Node node = YAML::LoadFile(fileName); use_case_interface::GameData gameData; gameData.bestScore = node[key::bestScore].as<int>(); gameData.score = node[key::score].as<int>(); gameData.isGameOver = node[key::isGameOver].as<bool>(); gameData.rows = node[key::rows].as<common::Index>(); gameData.cols = node[key::cols].as<common::Index>(); gameData.newActions = node[key::newActions].as<common::NewActions>(); return gameData; } catch (const std::exception& e) { return {}; } } void Storage::saveGame(const use_case_interface::GameData& gameData) { YAML::Node node; node[key::bestScore] = gameData.bestScore; node[key::score] = gameData.score; node[key::isGameOver] = gameData.isGameOver; node[key::rows] = gameData.rows; node[key::cols] = gameData.cols; node[key::newActions] = gameData.newActions; std::ofstream ofs{fileName}; ofs << node; } void Storage::clear() { std::filesystem::remove(fileName); } } // namespace storage
26.612245
73
0.671779
codingpotato
2233a4028f66fb1b036dfb41e64e412943cd57cc
6,278
cpp
C++
ace/ace/RMCast/RMCast_Fragment.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/ace/RMCast/RMCast_Fragment.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/ace/RMCast/RMCast_Fragment.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// RMCast_Fragment.cpp,v 1.4 2000/10/11 00:57:08 coryan Exp #include "RMCast_Fragment.h" #include "ace/Message_Block.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #if !defined (__ACE_INLINE__) #include "RMCast_Fragment.i" #endif /* __ACE_INLINE__ */ ACE_RCSID(ace, RMCast_Fragment, "RMCast_Fragment.cpp,v 1.4 2000/10/11 00:57:08 coryan Exp") ACE_RMCast_Fragment:: ACE_RMCast_Fragment (void) : ACE_RMCast_Module () , max_fragment_size_ (ACE_RMCAST_DEFAULT_FRAGMENT_SIZE) { } ACE_RMCast_Fragment::~ACE_RMCast_Fragment (void) { } int ACE_RMCast_Fragment::data (ACE_RMCast::Data &received_data) { if (this->next () == 0) return 0; // The Data object sent downstream ACE_RMCast::Data data = received_data; ACE_Message_Block *mb = data.payload; // @@ We should keep the total size precomputed data.total_size = mb->total_length (); // We must leave room for the header #if defined (ACE_HAS_BROKEN_DGRAM_SENDV) const int ACE_RMCAST_WRITEV_MAX = IOV_MAX - 2; #else const int ACE_RMCAST_WRITEV_MAX = IOV_MAX - 1; #endif /* ACE_HAS_BROKEN_DGRAM_SENDV */ // Assume the header will be included on each fragment, so readuce // the maximum amount of memory allowed on each fragment.... const size_t fragment_header_size = 1 + 3 * sizeof(ACE_UINT32); const size_t max_fragment_payload = this->max_fragment_size_ - fragment_header_size; // Iterate over all the message blocks in the chain. If there is // enough data to send an MTU then it is sent immediately. // The last fragment is sent with whatever data remains. // A single fragment can expand multiple message blocks, put // together in an <iovec> array, it is also possible that a single // message block requires multiple fragments... so the code below is // as simple as possible, but not any simpler ;-) // The first piece of each fragment is a header that contains: // - A sequence number for reassembly, this is unrelated to // the sequence number for re-transmission. // NOTE: yes, this increases the bandwidth requires by 4 bytes on // each message, I don't think this is a big deal. // - A fragment offset for reassembly. // - The total size of the message, so the reassembly layer knows // when a complete message has been received. // Complete the initialization of the <data> structure data.fragment_offset = 0; // The underlying transport layer can only tolerate so many elements // in a chain, so we must count them and send a fragment if we are // going over the limit. ACE_Message_Block blocks[ACE_RMCAST_WRITEV_MAX]; // How many elements of the <blocks> array are in use... int iovcnt = 0; // The size of the current message, adding the size of all its // message blocks. size_t fragment_size = 0; for (ACE_Message_Block* b = mb; b != 0; b = b->cont ()) { ACE_Message_Block *current_block = &blocks[iovcnt]; // Add the block to the vector... current_block->data_block (b->data_block ()->duplicate ()); current_block->rd_ptr (b->rd_ptr ()); current_block->wr_ptr (b->wr_ptr ()); current_block->cont (0); // Set the continuation field if (iovcnt != 0) blocks[iovcnt-1].cont (current_block); size_t current_block_length = current_block->length (); // Recompute the state of the fragment fragment_size += current_block_length; iovcnt++; while (fragment_size >= max_fragment_payload) { // We have filled a fragment. It is possible that we need // to split the last message block in multiple fragments, // thus the loop above... // First adjust the last message block to exactly fit in the // fragment: size_t last_sent_mb_len = max_fragment_payload - (fragment_size - current_block_length); // Send only enough data of the last message block to fill // the fragment... current_block->wr_ptr (current_block->rd_ptr () + last_sent_mb_len); data.payload = blocks; if (this->next ()->data (data) == -1) return -1; // adjust the offset data.fragment_offset += max_fragment_payload; // Now compute how much data is left in the last message // block, to check if we should continue sending it... current_block_length -= last_sent_mb_len; if (current_block_length == 0) { // No more data from this message block, just continue // the outer loop... iovcnt = 0; fragment_size = 0; blocks[0].cont (0); break; // while } // There is some data left, we try to send it in a single // fragment, if it is still too big the beginning of this // loop will adjust things. // We must put the data in the right place in the array.. char *rd_ptr = current_block->rd_ptr () + last_sent_mb_len; char *wr_ptr = rd_ptr + current_block_length; blocks[0].data_block (current_block->replace_data_block (0)); // And determine what segment of the data will be sent.. blocks[0].rd_ptr (rd_ptr); blocks[0].wr_ptr (wr_ptr); blocks[0].cont (0); // Adjust the state of the fragment fragment_size = current_block_length; iovcnt = 1; // Notice that if <fragment_size> is too big the start of // this loop will continue the fragmentation. } // It is also possible to fill up the iovec array before the // fragment is completed, in this case we must send whatever we // have: if (iovcnt == ACE_RMCAST_WRITEV_MAX) { if (this->next ()->data (data) == -1) return -1; iovcnt = 0; fragment_size = 0; blocks[0].cont (0); } } if (iovcnt == 0) return 0; return this->next ()->data (data); }
33.216931
92
0.620739
tharindusathis
2239226ca034a82757bfc7fe66f872245acb1fd5
631
cpp
C++
src/Callback-v11.cpp
Alfheim/node-julia
72c202e149912ba09d3aea8c006aba83ae447b64
[ "MIT" ]
71
2015-01-17T12:35:43.000Z
2021-12-01T06:04:22.000Z
src/Callback-v11.cpp
Alfheim/node-julia
72c202e149912ba09d3aea8c006aba83ae447b64
[ "MIT" ]
33
2015-02-24T00:21:53.000Z
2018-01-18T01:12:23.000Z
src/Callback-v11.cpp
Alfheim/node-julia
72c202e149912ba09d3aea8c006aba83ae447b64
[ "MIT" ]
15
2015-04-24T06:48:03.000Z
2021-12-07T20:39:38.000Z
#include <node_version.h> #include "Callback.h" using namespace v8; nj::Callback::Callback(const Local<Function> &cb,const Local<Object> &recv):callback_persist(),recv_persist() { Isolate *I = Isolate::GetCurrent(); callback_persist.Reset(I,cb); recv_persist.Reset(I,recv); } Local<Function> nj::Callback::cb() { Isolate *I = Isolate::GetCurrent(); return Local<Function>::New(I,callback_persist); } Local<Object> nj::Callback::recv() { Isolate *I = Isolate::GetCurrent(); return Local<Object>::New(I,recv_persist); } nj::Callback::~Callback() { callback_persist.Reset(); recv_persist.Reset(); }
19.121212
109
0.692552
Alfheim
223b72eb05b17f7e523649297589f8da0aa2f026
3,041
cpp
C++
GameServer/Battle_ProcDead_APet.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/Battle_ProcDead_APet.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/Battle_ProcDead_APet.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
1
2022-01-17T09:34:39.000Z
2022-01-17T09:34:39.000Z
#include "stdhdrs.h" #include "Server.h" #include "Battle.h" #include "WarCastle.h" #include "CmdMsg.h" #include "Exp.h" #include "Log.h" #include "doFunc.h" void ProcDead(CAPet* df, CCharacter* of) { CPC* opc = NULL; CNPC* onpc = NULL; CPet* opet = NULL; CElemental* oelemental = NULL; CAPet* oapet = NULL; if( IS_NPC(of) && TO_NPC(of)->Check_MobFlag(STATE_MONSTER_MERCENARY) && TO_NPC(of)->GetOwner() ) { TO_NPC(of)->GetOwner()->SetSummonOwners_target(NULL); } switch (of->m_type) { case MSG_CHAR_PC: opc = TO_PC(of); break; case MSG_CHAR_NPC: onpc = TO_NPC(of); break; case MSG_CHAR_PET: opet = TO_PET(of); opc = opet->GetOwner(); break; case MSG_CHAR_ELEMENTAL: oelemental = TO_ELEMENTAL(of); opc = oelemental->GetOwner(); break; case MSG_CHAR_APET: oapet = TO_APET( of ); opc = oapet->GetOwner(); break; default: return ; } if( opc ) opc->SetSummonOwners_target(NULL); bool bPKPenalty = false; if (df->GetOwner()) { bPKPenalty = (opc) ? IsPK(opc, df) : false; if (bPKPenalty) CalcPKPoint(opc, df->GetOwner(), true); } if( !bPKPenalty && !(df->GetOwner()->GetMapAttr() & MATT_FREEPKZONE) ) { if( df->m_level >= 10 ) { df->m_exp = (LONGLONG) ( df->m_exp - ( df->GetNeedExp() * 0.02) ) ; if( df->m_exp < 0 ) df->m_exp=0; } df->AddFaith(-10); } DelAttackList(df); CPC* owner = df->GetOwner(); const char* ownerName = "NO OWNER"; const char* ownerNick = "NO OWNER"; const char* ownerID = "NO OWNER"; if (owner) { ownerNick = (owner->IsNick()) ? owner->GetName() : ownerNick; ownerName = owner->m_name; ownerID = owner->m_desc->m_idname; } // TODO : petlog GAMELOG << init("PET DEAD") << "APET" << delim << "INDEX" << delim << df->m_index << delim << "LEVEL" << delim << df->m_level << delim << "OWNER" << delim << ownerName << delim << ownerNick << delim << ownerID << delim << "ATTACKER" << delim << "TYPE" << delim; switch (of->m_type) { case MSG_CHAR_NPC: GAMELOG << "NPC" << delim << onpc->m_name << end; break; case MSG_CHAR_PC: case MSG_CHAR_PET: case MSG_CHAR_ELEMENTAL: case MSG_CHAR_APET: default: if (opc) { GAMELOG << "PC" << delim << opc->m_index << delim << opc->GetName() << end; } else { GAMELOG << "UNKNOWN" << delim << of->m_index << delim << of->m_name << end; } break; } if (owner) { // Item şŔŔÎ CItem* apet_item = owner->m_wearInventory.wearItemInfo[WEARING_PET]; if( !apet_item ) return; apet_item->setFlag(apet_item->getFlag() | FLAG_ITEM_SEALED); { owner->m_wearInventory.sendOneItemInfo(WEARING_PET); } df->m_bMount = false; // Á׾úŔ»¶§´Â ÂřżëÇŘÁ¦żˇĽ­ Disappear ¸¦ ş¸ł»Áö ľĘ±â¶«ą®żˇ ż©±âĽ­ ĽżżˇĽ­ »©ÁŘ´Ů. df->m_bSummon = false; DelAttackList(df); if( df->m_pZone && df->m_pArea ) df->m_pArea->CharFromCell(df, true); { // Ćę »óĹ ş¸łż CNetMsg::SP rmsg(new CNetMsg); ExAPetStatusMsg(rmsg, df); SEND_Q(rmsg, owner->m_desc); } } }
19.125786
97
0.604078
openlastchaos
223b9fda2af0acf14e3a5a4bdef518657a439af0
3,753
cc
C++
base/test/quaternion_test.cc
rkb-1/quad
66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e
[ "Apache-2.0" ]
64
2017-01-18T15:12:05.000Z
2022-02-16T08:28:11.000Z
base/test/quaternion_test.cc
rkb-1/quad
66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e
[ "Apache-2.0" ]
2
2021-02-11T14:39:38.000Z
2021-10-03T16:49:57.000Z
base/test/quaternion_test.cc
rkb-1/quad
66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e
[ "Apache-2.0" ]
14
2021-01-11T09:48:34.000Z
2021-12-16T16:20:35.000Z
// Copyright 2014-2015 Josh Pieper, jjp@pobox.com. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "base/quaternion.h" #include <fmt/format.h> #include <boost/test/auto_unit_test.hpp> #include "base/euler.h" namespace { using namespace mjmech; typedef base::Euler Euler; typedef base::Quaternion Quaternion; typedef base::Point3D Point3D; void CheckVectorClose(const Point3D& lhs, double x, double y, double z) { BOOST_CHECK_SMALL(lhs.x() - x, 1e-2); BOOST_CHECK_SMALL(lhs.y() - y, 1e-2); BOOST_CHECK_SMALL(lhs.z() - z, 1e-2); } } BOOST_AUTO_TEST_CASE(BasicQuaternion) { Point3D v(10., 0., 0); v = Quaternion::FromEuler(0, 0, M_PI_2).Rotate(v); CheckVectorClose(v, 0, 10, 0); v = Quaternion::FromEuler(0, 0, -M_PI_2).Rotate(v); CheckVectorClose(v, 10, 0, 0); v = Quaternion::FromEuler(0, M_PI_2, 0).Rotate(v); CheckVectorClose(v, 0, 0, -10); v = Quaternion::FromEuler(M_PI_2, 0, 0).Rotate(v); CheckVectorClose(v, 0, 10, 0); v = Quaternion::FromEuler(0, 0, M_PI_2).Rotate(v); CheckVectorClose(v, -10, 0, 0); v = Quaternion::FromEuler(0, M_PI_2, 0).Rotate(v); CheckVectorClose(v, 0, 0, 10); v = Quaternion::FromEuler(M_PI_2, 0, 0).Rotate(v); CheckVectorClose(v, 0, -10, 0); v = Quaternion::FromEuler(0, 0, M_PI_2).Rotate(v); CheckVectorClose(v, 10, 0, 0); } namespace { void CheckEuler(Euler euler_rad, double roll_rad, double pitch_rad, double yaw_rad) { BOOST_CHECK_SMALL(euler_rad.roll - roll_rad, 1e-5); BOOST_CHECK_SMALL(euler_rad.pitch - pitch_rad, 1e-5); BOOST_CHECK_SMALL(euler_rad.yaw - yaw_rad, 1e-5); } } BOOST_AUTO_TEST_CASE(QuaternionEulerAndBack) { struct TestCase { double roll_deg; double pitch_deg; double yaw_deg; }; TestCase tests[] = { {45, 0, 0}, {0, 45, 0}, {0, 0, 45}, {0, 90, 0}, {0, 90, 20}, {0, -90, 0}, {0, -90, -10}, {0, -90, 30}, {10, 20, 30}, {-30, 10, 20}, }; for (const auto& x: tests) { BOOST_TEST_CONTEXT(fmt::format("{} {} {}", x.roll_deg, x.pitch_deg, x.yaw_deg)) { Euler result_rad = Quaternion::FromEuler( x.roll_deg / 180 * M_PI, x.pitch_deg / 180 * M_PI, x.yaw_deg / 180 * M_PI).euler_rad(); CheckEuler(result_rad, x.roll_deg / 180 * M_PI, x.pitch_deg / 180 *M_PI, x.yaw_deg / 180 * M_PI); } } } BOOST_AUTO_TEST_CASE(QuaternionMultiply1) { Quaternion x90 = Quaternion::FromEuler(0, M_PI_2, 0); Quaternion xn90 = Quaternion::FromEuler(0, -M_PI_2, 0); Quaternion y90 = Quaternion::FromEuler(M_PI_2, 0, 0); Quaternion result = xn90 * y90 * x90; Point3D vector(0, 1, 0); vector = result.Rotate(vector); CheckVectorClose(vector, -1, 0, 0); Quaternion initial = Quaternion::FromEuler(0, 0, 0.5 * M_PI_2); initial = Quaternion::FromEuler(0, 0, 0.5 * M_PI_2) * initial; CheckEuler(initial.euler_rad(), 0, 0, M_PI_2); initial = Quaternion::FromEuler(10 / 180. * M_PI, 0, 0) * initial; vector = initial.Rotate(vector); CheckVectorClose(vector, 0, -0.9848078, -0.17364818); CheckEuler(initial.euler_rad(), 0, -10 / 180.0 * M_PI, M_PI_2); }
28.869231
75
0.637357
rkb-1
2241d810412d9325c504a0a757283b15dcae67c9
3,000
cpp
C++
src/verify/main_verify.cpp
velidurmuscan/VDSProject_Group6
74ad2e315ffe271a66d744078bc16fe002d33874
[ "Unlicense", "MIT" ]
null
null
null
src/verify/main_verify.cpp
velidurmuscan/VDSProject_Group6
74ad2e315ffe271a66d744078bc16fe002d33874
[ "Unlicense", "MIT" ]
null
null
null
src/verify/main_verify.cpp
velidurmuscan/VDSProject_Group6
74ad2e315ffe271a66d744078bc16fe002d33874
[ "Unlicense", "MIT" ]
null
null
null
/*============================================================================= Written by Mohammad R Fadiheh (2017) =============================================================================*/ #include<iostream> #include<fstream> #include<string> #include<sstream> #include<map> struct node { std::string var_name; int low; int high; }; typedef std::map<int, node> uniqueTable; bool isEquivalent(uniqueTable BDD1, uniqueTable BDD2, int root1, int root2) { if(BDD1.find(root1) == BDD1.end() || BDD2.find(root2) == BDD2.end()) return false; if(root1 == 1 && root2 == 1) return true; if(root1 == 0 && root2 == 0) return true; if(root1 != root2 && ( (root1 == 0 || root1 == 1) || (root2 == 0 || root2 == 1) ) ) return false; if(BDD1[root1].var_name != BDD2[root2].var_name) return false; return isEquivalent(BDD1, BDD2, BDD1[root1].low, BDD2[root2].low) and isEquivalent(BDD1, BDD2, BDD1[root1].high, BDD2[root2].high); } int main(int argc, char* argv[]) { /* Number of arguments validation */ if (3 > argc) { std::cout << "Must specify a filename!" << std::endl; return -1; } uniqueTable BDD1, BDD2; std::string BDD1_file = argv[1]; std::string BDD2_file = argv[2]; std::ifstream BDD1_if(BDD1_file.c_str()); std::ifstream BDD2_if(BDD2_file.c_str()); if(!BDD1_if.is_open() || !BDD2_if.is_open()) { std::cout << "invalid file!" << std::endl; return -1; } std::stringstream ss; std::string temp; std::string var_name; int id, top_var; while(!BDD1_if.eof()) { node n; temp.clear(); std::getline(BDD1_if, temp,'\n'); if(temp.find("Terminal Node: 1") != std::string::npos) { n.var_name = ""; n.low = 1; n.high = 1; BDD1.insert(std::pair<int,node>(1,n)); } else if(temp.find("Terminal Node: 0") != std::string::npos) { n.var_name = ""; n.low = 0; n.high = 0; BDD1.insert(std::pair<int,node>(0,n)); } else if(temp.find("Variable Node:") != std::string::npos) { ss.clear(); ss.str(temp); ss>>temp>>temp>>id>>temp>>temp>>temp>>top_var>>temp>>temp>>temp>>n.var_name>>temp>>n.low>>temp>>n.high; BDD1.insert(std::pair<int,node>(id,n)); } } while(!BDD2_if.eof()) { node n; temp.clear(); std::getline(BDD2_if, temp,'\n'); if(temp.find("Terminal Node: 1") != std::string::npos) { n.var_name = ""; n.low = 1; n.high = 1; BDD2.insert(std::pair<int,node>(1,n)); } else if(temp.find("Terminal Node: 0") != std::string::npos) { n.var_name = ""; n.low = 0; n.high = 0; BDD2.insert(std::pair<int,node>(0,n)); } else if(temp.find("Variable Node:") != std::string::npos) { ss.clear(); ss.str(temp); ss>>temp>>temp>>id>>temp>>temp>>temp>>top_var>>temp>>temp>>temp>>n.var_name>>temp>>n.low>>temp>>n.high; BDD2.insert(std::pair<int,node>(id,n)); } } if( isEquivalent(BDD1, BDD2, BDD1.rbegin()->first, BDD2.rbegin()->first) ) std::cout<<"Equivalent!"<<std::endl; else std::cout<<"Not Equivalent!"<<std::endl; return 0; }
22.900763
132
0.574333
velidurmuscan
22479d2daedc168c0f739920d2e729da195d6ce8
189
hpp
C++
src/components/allcomponents.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
src/components/allcomponents.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
src/components/allcomponents.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
#ifndef INCLUDE_BALLCOMPONENTS #define INCLUDE_BALLCOMPONENTS #include "../components.hpp" #include "primitives.hpp" #include "drawingcomponents.hpp" #include "gamecomponents.hpp" #endif
18.9
32
0.804233
wareya
22481376becb28333dc86377cfd200f030a63ac2
14,430
cpp
C++
OREData/ored/marketdata/inflationcurve.cpp
nvolfango/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
1
2021-03-30T17:24:17.000Z
2021-03-30T17:24:17.000Z
OREData/ored/marketdata/inflationcurve.cpp
zhangjiayin/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
null
null
null
OREData/ored/marketdata/inflationcurve.cpp
zhangjiayin/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ored/marketdata/inflationcurve.hpp> #include <ored/utilities/log.hpp> #include <qle/indexes/inflationindexwrapper.hpp> #include <ql/cashflows/couponpricer.hpp> #include <ql/cashflows/yoyinflationcoupon.hpp> #include <ql/pricingengines/swap/discountingswapengine.hpp> #include <ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp> #include <ql/termstructures/inflation/piecewisezeroinflationcurve.hpp> #include <ql/time/daycounters/actual365fixed.hpp> #include <algorithm> using namespace QuantLib; using namespace std; using namespace ore::data; namespace ore { namespace data { InflationCurve::InflationCurve(Date asof, InflationCurveSpec spec, const Loader& loader, const CurveConfigurations& curveConfigs, const Conventions& conventions, map<string, boost::shared_ptr<YieldCurve>>& yieldCurves) { try { const boost::shared_ptr<InflationCurveConfig>& config = curveConfigs.inflationCurveConfig(spec.curveConfigID()); boost::shared_ptr<InflationSwapConvention> conv = boost::dynamic_pointer_cast<InflationSwapConvention>(conventions.get(config->conventions())); QL_REQUIRE(conv != nullptr, "convention " << config->conventions() << " could not be found."); Handle<YieldTermStructure> nominalTs; auto it = yieldCurves.find(config->nominalTermStructure()); if (it != yieldCurves.end()) { nominalTs = it->second->handle(); } else { QL_FAIL("The nominal term structure, " << config->nominalTermStructure() << ", required in the building " "of the curve, " << spec.name() << ", was not found."); } // We loop over all market data, looking for quotes that match the configuration const std::vector<string> strQuotes = config->swapQuotes(); std::vector<Handle<Quote>> quotes(strQuotes.size(), Handle<Quote>()); std::vector<Period> terms(strQuotes.size()); std::vector<bool> isZc(strQuotes.size(), true); for (auto& md : loader.loadQuotes(asof)) { if (md->asofDate() == asof && (md->instrumentType() == MarketDatum::InstrumentType::ZC_INFLATIONSWAP || (md->instrumentType() == MarketDatum::InstrumentType::YY_INFLATIONSWAP && config->type() == InflationCurveConfig::Type::YY))) { boost::shared_ptr<ZcInflationSwapQuote> q = boost::dynamic_pointer_cast<ZcInflationSwapQuote>(md); if (q != NULL && q->index() == spec.index()) { auto it = std::find(strQuotes.begin(), strQuotes.end(), q->name()); if (it != strQuotes.end()) { QL_REQUIRE(quotes[it - strQuotes.begin()].empty(), "duplicate quote " << q->name()); quotes[it - strQuotes.begin()] = q->quote(); terms[it - strQuotes.begin()] = q->term(); isZc[it - strQuotes.begin()] = true; } } boost::shared_ptr<YoYInflationSwapQuote> q2 = boost::dynamic_pointer_cast<YoYInflationSwapQuote>(md); if (q2 != NULL && q2->index() == spec.index()) { auto it = std::find(strQuotes.begin(), strQuotes.end(), q2->name()); if (it != strQuotes.end()) { QL_REQUIRE(quotes[it - strQuotes.begin()].empty(), "duplicate quote " << q2->name()); quotes[it - strQuotes.begin()] = q2->quote(); terms[it - strQuotes.begin()] = q2->term(); isZc[it - strQuotes.begin()] = false; } } } } // do we have all quotes and do we derive yoy quotes from zc ? for (Size i = 0; i < strQuotes.size(); ++i) { QL_REQUIRE(!quotes[i].empty(), "quote " << strQuotes[i] << " not found in market data."); QL_REQUIRE(isZc[i] == isZc[0], "mixed zc and yoy quotes"); } bool derive_yoy_from_zc = (config->type() == InflationCurveConfig::Type::YY && isZc[0]); // construct seasonality boost::shared_ptr<Seasonality> seasonality; if (config->seasonalityBaseDate() != Null<Date>()) { std::vector<string> strFactorIDs = config->seasonalityFactors(); std::vector<double> factors(strFactorIDs.size()); for (Size i = 0; i < strFactorIDs.size(); i++) { boost::shared_ptr<MarketDatum> marketQuote = loader.get(strFactorIDs[i], asof); // Check that we have a valid seasonality factor if (marketQuote) { QL_REQUIRE(marketQuote->instrumentType() == MarketDatum::InstrumentType::SEASONALITY, "Market quote (" << marketQuote->name() << ") not of type seasonality."); // Currently only monthly seasonality with 12 multiplicative factors os allowed QL_REQUIRE(config->seasonalityFrequency() == Monthly && strFactorIDs.size() == 12, "Only monthly seasonality with 12 factors is allowed. Provided " << config->seasonalityFrequency() << " with " << strFactorIDs.size() << " factors."); boost::shared_ptr<SeasonalityQuote> sq = boost::dynamic_pointer_cast<SeasonalityQuote>(marketQuote); QL_REQUIRE(sq->type() == "MULT", "Market quote (" << sq->name() << ") not of multiplicative type."); Size seasBaseDateMonth = ((Size)config->seasonalityBaseDate().month()); int findex = sq->applyMonth() - seasBaseDateMonth; if (findex < 0) findex += 12; QL_REQUIRE(findex >= 0 && findex < 12, "Unexpected seasonality index " << findex); factors[findex] = sq->quote()->value(); } else { QL_FAIL("Could not find quote for ID " << strFactorIDs[i] << " with as of date " << io::iso_date(asof) << "."); } } QL_REQUIRE(!factors.empty(), "no seasonality factors found"); seasonality = boost::make_shared<MultiplicativePriceSeasonality>(config->seasonalityBaseDate(), config->seasonalityFrequency(), factors); } // construct curve (ZC or YY depending on configuration) // base zero / yoy rate: if given, take it, otherwise set it to first quote Real baseRate = config->baseRate() != Null<Real>() ? config->baseRate() : quotes[0]->value(); interpolatedIndex_ = conv->interpolated(); boost::shared_ptr<YoYInflationIndex> zc_to_yoy_conversion_index; if (config->type() == InflationCurveConfig::Type::ZC || derive_yoy_from_zc) { // ZC Curve std::vector<boost::shared_ptr<ZeroInflationTraits::helper>> instruments; boost::shared_ptr<ZeroInflationIndex> index = conv->index(); for (Size i = 0; i < strQuotes.size(); ++i) { // QL conventions do not incorporate settlement delay => patch here once QL is patched Date maturity = asof + terms[i]; boost::shared_ptr<ZeroInflationTraits::helper> instrument = boost::make_shared<ZeroCouponInflationSwapHelper>(quotes[i], conv->observationLag(), maturity, conv->fixCalendar(), conv->fixConvention(), conv->dayCounter(), index, nominalTs); // The instrument gets registered to update on change of evaluation date. This triggers a // rebootstrapping of the curve. In order to avoid this during simulation we unregister from the // evaluationDate. instrument->unregisterWith(Settings::instance().evaluationDate()); instruments.push_back(instrument); } curve_ = boost::shared_ptr<PiecewiseZeroInflationCurve<Linear>>(new PiecewiseZeroInflationCurve<Linear>( asof, config->calendar(), config->dayCounter(), config->lag(), config->frequency(), interpolatedIndex_, baseRate, nominalTs, instruments, config->tolerance())); // force bootstrap so that errors are thrown during the build, not later boost::static_pointer_cast<PiecewiseZeroInflationCurve<Linear>>(curve_)->zeroRate(QL_EPSILON); if (derive_yoy_from_zc) { // set up yoy wrapper with empty ts, so that zero index is used to forecast fixings // for this link the appropriate curve to the zero index zc_to_yoy_conversion_index = boost::make_shared<QuantExt::YoYInflationIndexWrapper>( index->clone(Handle<ZeroInflationTermStructure>( boost::dynamic_pointer_cast<ZeroInflationTermStructure>(curve_))), interpolatedIndex_); } } if (config->type() == InflationCurveConfig::Type::YY) { // YOY Curve std::vector<boost::shared_ptr<YoYInflationTraits::helper>> instruments; boost::shared_ptr<ZeroInflationIndex> zcindex = conv->index(); boost::shared_ptr<YoYInflationIndex> index = boost::make_shared<QuantExt::YoYInflationIndexWrapper>(zcindex, interpolatedIndex_); boost::shared_ptr<InflationCouponPricer> yoyCpnPricer = boost::make_shared<QuantExt::YoYInflationCouponPricer2>(nominalTs); for (Size i = 0; i < strQuotes.size(); ++i) { Date maturity = asof + terms[i]; Real effectiveQuote = quotes[i]->value(); if (derive_yoy_from_zc) { // contruct a yoy swap just as it is done in the yoy inflation helper Schedule schedule = MakeSchedule() .from(Settings::instance().evaluationDate()) .to(maturity) .withTenor(1 * Years) .withConvention(Unadjusted) .withCalendar(conv->fixCalendar()) .backwards(); YearOnYearInflationSwap tmp(YearOnYearInflationSwap::Payer, 1000000.0, schedule, 0.02, conv->dayCounter(), schedule, zc_to_yoy_conversion_index, conv->observationLag(), 0.0, conv->dayCounter(), conv->fixCalendar(), conv->fixConvention()); for (auto& c : tmp.yoyLeg()) { auto cpn = boost::dynamic_pointer_cast<YoYInflationCoupon>(c); QL_REQUIRE(cpn, "yoy inflation coupon expected, could not cast"); cpn->setPricer(yoyCpnPricer); } boost::shared_ptr<PricingEngine> engine = boost::make_shared<QuantLib::DiscountingSwapEngine>(nominalTs); tmp.setPricingEngine(engine); effectiveQuote = tmp.fairRate(); DLOG("Derive " << terms[i] << " yoy quote " << effectiveQuote << " from zc quote " << quotes[i]->value()); } // QL conventions do not incorporate settlement delay => patch here once QL is patched boost::shared_ptr<YoYInflationTraits::helper> instrument = boost::make_shared<YearOnYearInflationSwapHelper>( Handle<Quote>(boost::make_shared<SimpleQuote>(effectiveQuote)), conv->observationLag(), maturity, conv->fixCalendar(), conv->fixConvention(), conv->dayCounter(), index, nominalTs); instrument->unregisterWith(Settings::instance().evaluationDate()); instruments.push_back(instrument); } // base zero rate: if given, take it, otherwise set it to first quote Real baseRate = config->baseRate() != Null<Real>() ? config->baseRate() : quotes[0]->value(); curve_ = boost::shared_ptr<PiecewiseYoYInflationCurve<Linear>>(new PiecewiseYoYInflationCurve<Linear>( asof, config->calendar(), config->dayCounter(), config->lag(), config->frequency(), interpolatedIndex_, baseRate, nominalTs, instruments, config->tolerance())); // force bootstrap so that errors are thrown during the build, not later boost::static_pointer_cast<PiecewiseYoYInflationCurve<Linear>>(curve_)->yoyRate(QL_EPSILON); } if (seasonality != nullptr) { curve_->setSeasonality(seasonality); } curve_->enableExtrapolation(config->extrapolate()); curve_->unregisterWith(Settings::instance().evaluationDate()); } catch (std::exception& e) { QL_FAIL("inflation curve building failed: " << e.what()); } catch (...) { QL_FAIL("inflation curve building failed: unknown error"); } } } // namespace data } // namespace ore
59.139344
120
0.570132
nvolfango
22493a49d2e35d060825b9b6db2a8badc554f516
7,609
cpp
C++
src/xtd.core.native.unix/src/xtd/native/unix/directory.cpp
BaderEddineOuaich/xtd
6f28634c7949a541d183879d2de18d824ec3c8b1
[ "MIT" ]
1
2022-02-25T16:53:06.000Z
2022-02-25T16:53:06.000Z
src/xtd.core.native.unix/src/xtd/native/unix/directory.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
src/xtd.core.native.unix/src/xtd/native/unix/directory.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
#define __XTD_CORE_NATIVE_LIBRARY__ #include <xtd/native/directory.h> #include <xtd/native/file_system.h> #undef __XTD_CORE_NATIVE_LIBRARY__ #include <dirent.h> #include <unistd.h> #include <sys/param.h> #include <sys/stat.h> using namespace std; using namespace xtd::native; namespace { bool pattern_compare(const string& file_name, const string& pattern) { if (pattern.empty()) return file_name.empty(); if (file_name.empty()) return false; if (pattern == "*" || pattern == "*.*") return true; if (pattern[0] == '*') return pattern_compare(file_name, pattern.substr(1)) || pattern_compare(file_name.substr(1), pattern); return ((pattern[0] == '?') || (file_name[0] == pattern[0])) && pattern_compare(file_name.substr(1), pattern.substr(1)); } } struct directory::directory_iterator::data { data() = default; data(const std::string& path, const std::string& pattern) : path_(path), pattern_(pattern) {} std::string path_; std::string pattern_; DIR* handle_ = nullptr; mutable string current_; }; directory::directory_iterator::directory_iterator(const std::string& path, const std::string& pattern) { data_ = make_shared<data>(path, pattern); data_->handle_ = opendir(data_->path_.c_str()); ++(*this); } directory::directory_iterator::directory_iterator() { data_ = make_shared<data>(); } directory::directory_iterator::~directory_iterator() { if (data_.use_count() == 1 && data_->handle_) { closedir(data_->handle_); data_->handle_ = nullptr; } } directory::directory_iterator& directory::directory_iterator::operator++() { dirent* item; int32_t attributes; do { if ((item = readdir(data_->handle_)) != nullptr) native::file_system::get_attributes(data_->path_ + '/' + item->d_name, attributes); } while (item != nullptr && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY || string(item->d_name) == "." || string(item->d_name) == ".." || !pattern_compare(item->d_name, data_->pattern_))); if (item == nullptr) data_->current_ = ""; else data_->current_ = data_->path_ + (data_->path_.rfind('/') == data_->path_.size() - 1 ? "" : "/") + item->d_name; return *this; } directory::directory_iterator directory::directory_iterator::operator++(int) { directory_iterator result = *this; ++(*this); return result; } bool directory::directory_iterator::operator==(directory::directory_iterator other) const { return data_->current_ == other.data_->current_; } directory::directory_iterator::value_type directory::directory_iterator::operator*() const { if (data_ == nullptr) return ""; return data_->current_; } struct directory::file_iterator::data { data() = default; data(const std::string& path, const std::string& pattern) : path_(path), pattern_(pattern) {} std::string path_; std::string pattern_; DIR* handle_ = nullptr; mutable string current_; }; directory::file_iterator::file_iterator(const std::string& path, const std::string& pattern) { data_ = make_shared<data>(path, pattern); data_->handle_ = opendir(data_->path_.c_str()); ++(*this); } directory::file_iterator::file_iterator() { data_ = make_shared<data>(); } directory::file_iterator::~file_iterator() { if (data_.use_count() == 1 && data_->handle_) { closedir(data_->handle_); data_->handle_ = nullptr; } } directory::file_iterator& directory::file_iterator::operator++() { dirent* item; int32_t attributes; do { if ((item = readdir(data_->handle_)) != nullptr) native::file_system::get_attributes(data_->path_ + '/' + item->d_name, attributes); } while (item != nullptr && ((attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY || string(item->d_name) == "." || string(item->d_name) == ".." || !pattern_compare(item->d_name, data_->pattern_))); if (item == nullptr) data_->current_ = ""; else data_->current_ = data_->path_ + (data_->path_.rfind('/') == data_->path_.size() - 1 ? "" : "/") + item->d_name; return *this; } directory::file_iterator directory::file_iterator::operator++(int) { file_iterator result = *this; ++(*this); return result; } bool directory::file_iterator::operator==(directory::file_iterator other) const { return data_->current_ == other.data_->current_; } directory::file_iterator::value_type directory::file_iterator::operator*() const { if (data_ == nullptr) return ""; return data_->current_; } struct directory::file_and_directory_iterator::data { data() = default; data(const std::string& path, const std::string& pattern) : path_(path), pattern_(pattern) {} std::string path_; std::string pattern_; DIR* handle_ = nullptr; mutable string current_; }; directory::file_and_directory_iterator::file_and_directory_iterator(const std::string& path, const std::string& pattern) { data_ = make_shared<data>(path, pattern); data_->handle_ = opendir(data_->path_.c_str()); ++(*this); } directory::file_and_directory_iterator::file_and_directory_iterator() { data_ = make_shared<data>(); } directory::file_and_directory_iterator::~file_and_directory_iterator() { if (data_.use_count() == 1 && data_->handle_) { closedir(data_->handle_); data_->handle_ = nullptr; } } directory::file_and_directory_iterator& directory::file_and_directory_iterator::operator++() { dirent* item; int32_t attributes; do { if ((item = readdir(data_->handle_)) != nullptr) native::file_system::get_attributes(data_->path_ + '/' + item->d_name, attributes); } while (item != nullptr && (string(item->d_name) == "." || string(item->d_name) == ".." || !pattern_compare(item->d_name, data_->pattern_))); if (item == nullptr) data_->current_ = ""; else data_->current_ = data_->path_ + (data_->path_.rfind('/') == data_->path_.size() - 1 ? "" : "/") + item->d_name; return *this; } directory::file_and_directory_iterator directory::file_and_directory_iterator::operator++(int) { file_and_directory_iterator result = *this; ++(*this); return result; } bool directory::file_and_directory_iterator::operator==(directory::file_and_directory_iterator other) const { return data_->current_ == other.data_->current_; } directory::file_and_directory_iterator::value_type directory::file_and_directory_iterator::operator*() const { if (data_ == nullptr) return ""; return data_->current_; } int32_t directory::create(const std::string& directory_name) { return mkdir(directory_name.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); } directory::directory_iterator directory::enumerate_directories(const std::string& path, const std::string& pattern) { return directory_iterator(path, pattern); } directory::file_iterator directory::enumerate_files(const std::string& path, const std::string& pattern) { return file_iterator(path, pattern); } directory::file_and_directory_iterator directory::enumerate_files_and_directories(const std::string& path, const std::string& pattern) { return file_and_directory_iterator(path, pattern); } bool directory::exists(const std::string& path) { int32_t attributes = 0; return file_system::get_attributes(path, attributes) == 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; } string directory::get_current_directory() { char path[MAXPATHLEN + 1]; return getcwd(path, MAXPATHLEN) ? path : ""; } int32_t directory::remove(const std::string& directory_name) { return rmdir(directory_name.c_str()); } int32_t directory::set_current_directory(const std::string& directory_name) { return chdir(directory_name.c_str()); }
34.90367
217
0.705086
BaderEddineOuaich
224cacc2e25eeabbac146d8cba9489c2bb5fe900
20,449
cpp
C++
libs/hmtslam/src/CHMTSLAM_main.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
libs/hmtslam/src/CHMTSLAM_main.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
null
null
null
libs/hmtslam/src/CHMTSLAM_main.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
1
2021-08-16T11:50:47.000Z
2021-08-16T11:50:47.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ /** An implementation of Hybrid Metric Topological SLAM (HMT-SLAM). * * The main entry points for a user are pushAction() and pushObservations(). Several parameters can be modified * through m_options. * * The mathematical models of this approach have been reported in: * - Blanco J.L., Fernandez-Madrigal J.A., and Gonzalez J., * "Towards a Unified Bayesian Approach to Hybrid Metric-Topological SLAM", * in IEEE Transactions on Robotics (TRO), Vol. 24, No. 2, April 2008. * - ... * * More information in the wiki page: http://www.mrpt.org/HMT-SLAM * */ #include "hmtslam-precomp.h" // Precomp header #include <mrpt/utils/CFileStream.h> #include <mrpt/utils/CConfigFile.h> #include <mrpt/utils/stl_serialization.h> #include <mrpt/system/filesystem.h> #include <mrpt/synch/CCriticalSection.h> #include <mrpt/utils/CMemoryStream.h> #include <mrpt/system/os.h> using namespace mrpt::slam; using namespace mrpt::hmtslam; using namespace mrpt::utils; using namespace mrpt::synch; using namespace mrpt::obs; using namespace mrpt::maps; using namespace mrpt::opengl; using namespace std; IMPLEMENTS_SERIALIZABLE(CHMTSLAM, CSerializable,mrpt::hmtslam) // Initialization of static members: int64_t CHMTSLAM::m_nextAreaLabel = 0; TPoseID CHMTSLAM::m_nextPoseID = 0; THypothesisID CHMTSLAM::m_nextHypID = COMMON_TOPOLOG_HYP + 1; /*--------------------------------------------------------------- Constructor ---------------------------------------------------------------*/ CHMTSLAM::CHMTSLAM( ) : m_inputQueue_cs("inputQueue_cs"), m_map_cs("map_cs"), m_LMHs_cs("LMHs_cs") // m_semaphoreInputQueueHasData (0 /*Init state*/ ,1 /*Max*/ ), // m_eventNewObservationInserted(0 /*Init state*/ ,10000 /*Max*/ ) { // Initialize data structures: // ---------------------------- m_terminateThreads = false; m_terminationFlag_LSLAM = m_terminationFlag_TBI = m_terminationFlag_3D_viewer = false; // Create threads: // ----------------------- m_hThread_LSLAM = mrpt::system::createThreadFromObjectMethod( this, &CHMTSLAM::thread_LSLAM ); m_hThread_TBI = mrpt::system::createThreadFromObjectMethod( this, &CHMTSLAM::thread_TBI ); m_hThread_3D_viewer = mrpt::system::createThreadFromObjectMethod( this, &CHMTSLAM::thread_3D_viewer ); // Other variables: m_LSLAM_method = NULL; // Register default LC detectors: // -------------------------------- registerLoopClosureDetector("gridmaps", & CTopLCDetector_GridMatching::createNewInstance ); registerLoopClosureDetector("fabmap", & CTopLCDetector_FabMap::createNewInstance ); // Prepare an empty map: initializeEmptyMap(); } /*--------------------------------------------------------------- Destructor ---------------------------------------------------------------*/ CHMTSLAM::~CHMTSLAM() { // Signal to threads that we are closing: // ------------------------------------------- m_terminateThreads = true; // Wait for threads: // ---------------------------------- MRPT_LOG_DEBUG("[CHMTSLAM::destructor] Waiting for threads end...\n"); mrpt::system::joinThread( m_hThread_3D_viewer ); mrpt::system::joinThread( m_hThread_LSLAM ); mrpt::system::joinThread( m_hThread_TBI ); MRPT_LOG_DEBUG("[CHMTSLAM::destructor] All threads finished.\n"); // Save the resulting H.Map if logging // -------------------------------------- if (!m_options.LOG_OUTPUT_DIR.empty()) { try { /* // Update the last area(s) in the HMAP: updateHierarchicalMapFromRBPF(); // Save: os::sprintf(auxFil,1000,"%s/hierarchicalMap.hmap",m_options.logOutputDirectory.c_str()); CFileStream f(auxFil,fomWrite); f << m_knownAreas; */ } catch(std::exception &e) { MRPT_LOG_WARN(mrpt::format("Ignoring exception at ~CHMTSLAM():\n%s",e.what())); } catch(...) { MRPT_LOG_WARN("Ignoring untyped exception at ~CHMTSLAM()"); } } // Delete data structures: // ---------------------------------- clearInputQueue(); // Others: if (m_LSLAM_method) { delete m_LSLAM_method; m_LSLAM_method = NULL; } // Delete TLC-detectors { synch::CCriticalSectionLocker lock( &m_topLCdets_cs ); // Clear old list: for (std::deque<CTopLCDetectorBase*>::iterator it=m_topLCdets.begin();it!=m_topLCdets.end();++it) delete *it; m_topLCdets.clear(); } } /*--------------------------------------------------------------- clearInputQueue ---------------------------------------------------------------*/ void CHMTSLAM::clearInputQueue() { // Wait for critical section { CCriticalSectionLocker locker( &m_inputQueue_cs); while (!m_inputQueue.empty()) { //delete m_inputQueue.front(); m_inputQueue.pop(); }; } } /*--------------------------------------------------------------- pushAction ---------------------------------------------------------------*/ void CHMTSLAM::pushAction( const CActionCollectionPtr &acts ) { if (m_terminateThreads) { // Discard it: //delete acts; return; } { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); m_inputQueue.push( acts ); } } /*--------------------------------------------------------------- pushObservations ---------------------------------------------------------------*/ void CHMTSLAM::pushObservations( const CSensoryFramePtr &sf ) { if (m_terminateThreads) { // Discard it: //delete sf; return; } { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); m_inputQueue.push( sf ); } } /*--------------------------------------------------------------- pushObservation ---------------------------------------------------------------*/ void CHMTSLAM::pushObservation( const CObservationPtr &obs ) { if (m_terminateThreads) { // Discard it: //delete obs; return; } // Add a CSensoryFrame with the obs: CSensoryFramePtr sf = CSensoryFrame::Create(); sf->insert(obs); // memory will be freed when deleting the SF in other thread { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); m_inputQueue.push( sf ); } } /*--------------------------------------------------------------- loadOptions ---------------------------------------------------------------*/ void CHMTSLAM::loadOptions( const mrpt::utils::CConfigFileBase &cfg ) { m_options.loadFromConfigFile(cfg,"HMT-SLAM"); m_options.defaultMapsInitializers.loadFromConfigFile(cfg,"MetricMaps"); m_options.pf_options.loadFromConfigFile(cfg,"PARTICLE_FILTER"); m_options.KLD_params.loadFromConfigFile(cfg,"KLD"); m_options.AA_options.loadFromConfigFile(cfg,"GRAPH_CUT"); // Topological Loop Closure detector options: m_options.TLC_grid_options.loadFromConfigFile(cfg,"TLC_GRIDMATCHING"); m_options.TLC_fabmap_options.loadFromConfigFile(cfg,"TLC_FABMAP"); m_options.dumpToConsole(); } /*--------------------------------------------------------------- loadOptions ---------------------------------------------------------------*/ void CHMTSLAM::loadOptions( const std::string &configFile ) { ASSERT_( mrpt::system::fileExists(configFile) ); CConfigFile cfg(configFile); loadOptions(cfg); } /*--------------------------------------------------------------- TOptions ---------------------------------------------------------------*/ CHMTSLAM::TOptions::TOptions() { LOG_OUTPUT_DIR = ""; LOG_FREQUENCY = 1; SLAM_METHOD = lsmRBPF_2DLASER; SLAM_MIN_DIST_BETWEEN_OBS = 1.0f; SLAM_MIN_HEADING_BETWEEN_OBS = DEG2RAD(25.0f); MIN_ODOMETRY_STD_XY = 0; MIN_ODOMETRY_STD_PHI = 0; VIEW3D_AREA_SPHERES_HEIGHT = 10.0f; VIEW3D_AREA_SPHERES_RADIUS = 1.0f; random_seed = 1234; TLC_detectors.clear(); stds_Q_no_odo.resize(3); stds_Q_no_odo[0] = stds_Q_no_odo[1] = 0.10f; stds_Q_no_odo[2] = DEG2RAD(4.0f); } /*--------------------------------------------------------------- loadFromConfigFile ---------------------------------------------------------------*/ void CHMTSLAM::TOptions::loadFromConfigFile( const mrpt::utils::CConfigFileBase &source, const std::string &section) { MRPT_LOAD_CONFIG_VAR( LOG_OUTPUT_DIR, string, source, section); MRPT_LOAD_CONFIG_VAR( LOG_FREQUENCY, int, source, section); MRPT_LOAD_CONFIG_VAR_CAST_NO_DEFAULT(SLAM_METHOD, int, TLSlamMethod, source, section); MRPT_LOAD_CONFIG_VAR( SLAM_MIN_DIST_BETWEEN_OBS, float, source, section); MRPT_LOAD_CONFIG_VAR_DEGREES( SLAM_MIN_HEADING_BETWEEN_OBS, source, section); MRPT_LOAD_CONFIG_VAR(MIN_ODOMETRY_STD_XY,float, source,section); MRPT_LOAD_CONFIG_VAR_DEGREES( MIN_ODOMETRY_STD_PHI, source,section); MRPT_LOAD_CONFIG_VAR( VIEW3D_AREA_SPHERES_HEIGHT, float, source, section); MRPT_LOAD_CONFIG_VAR( VIEW3D_AREA_SPHERES_RADIUS, float, source, section); MRPT_LOAD_CONFIG_VAR( random_seed, int, source,section); stds_Q_no_odo[2] = RAD2DEG(stds_Q_no_odo[2]); source.read_vector(section,"stds_Q_no_odo", stds_Q_no_odo, stds_Q_no_odo ); ASSERT_(stds_Q_no_odo.size()==3) stds_Q_no_odo[2] = DEG2RAD(stds_Q_no_odo[2]); std::string sTLC_detectors = source.read_string(section,"TLC_detectors", "", true ); mrpt::system::tokenize(sTLC_detectors,", ",TLC_detectors); std::cout << "TLC_detectors: " << TLC_detectors.size() << std::endl; // load other sub-classes: AA_options.loadFromConfigFile(source,section); } /*--------------------------------------------------------------- dumpToTextStream ---------------------------------------------------------------*/ void CHMTSLAM::TOptions::dumpToTextStream(mrpt::utils::CStream &out) const { out.printf("\n----------- [CHMTSLAM::TOptions] ------------ \n\n"); LOADABLEOPTS_DUMP_VAR( LOG_OUTPUT_DIR, string ); LOADABLEOPTS_DUMP_VAR( LOG_FREQUENCY, int); LOADABLEOPTS_DUMP_VAR( SLAM_METHOD, int); LOADABLEOPTS_DUMP_VAR( SLAM_MIN_DIST_BETWEEN_OBS, float ); LOADABLEOPTS_DUMP_VAR_DEG( SLAM_MIN_HEADING_BETWEEN_OBS ); LOADABLEOPTS_DUMP_VAR( MIN_ODOMETRY_STD_XY, float ); LOADABLEOPTS_DUMP_VAR_DEG( MIN_ODOMETRY_STD_PHI ); LOADABLEOPTS_DUMP_VAR( random_seed, int ); AA_options.dumpToTextStream(out); pf_options.dumpToTextStream(out); KLD_params.dumpToTextStream(out); defaultMapsInitializers.dumpToTextStream(out); TLC_grid_options.dumpToTextStream(out); TLC_fabmap_options.dumpToTextStream(out); } /*--------------------------------------------------------------- isInputQueueEmpty ---------------------------------------------------------------*/ bool CHMTSLAM::isInputQueueEmpty() { bool res; { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); res = m_inputQueue.empty(); } return res; } /*--------------------------------------------------------------- inputQueueSize ---------------------------------------------------------------*/ size_t CHMTSLAM::inputQueueSize() { size_t res; { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); res = m_inputQueue.size(); } return res; } /*--------------------------------------------------------------- getNextObjectFromInputQueue ---------------------------------------------------------------*/ CSerializablePtr CHMTSLAM::getNextObjectFromInputQueue() { CSerializablePtr obj; { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); if (!m_inputQueue.empty()) { obj = m_inputQueue.front(); m_inputQueue.pop(); } } return obj; } /*--------------------------------------------------------------- initializeEmptyMap ---------------------------------------------------------------*/ void CHMTSLAM::initializeEmptyMap() { THypothesisIDSet LMH_hyps; THypothesisID newHypothID = generateHypothesisID(); LMH_hyps.insert( COMMON_TOPOLOG_HYP ); LMH_hyps.insert( newHypothID ); // ------------------------------------ // CLEAR HIERARCHICAL MAP // ------------------------------------ CHMHMapNode::TNodeID firstAreaID; { synch::CCriticalSectionLocker locker( &m_map_cs ); // Initialize hierarchical structures: // ----------------------------------------------------- m_map.clear(); // Create a single node for the starting area: CHMHMapNodePtr firstArea = CHMHMapNode::Create( &m_map ); firstAreaID = firstArea->getID(); firstArea->m_hypotheses = LMH_hyps; CMultiMetricMapPtr emptyMap = CMultiMetricMapPtr(new CMultiMetricMap(&m_options.defaultMapsInitializers) ); firstArea->m_nodeType.setType( "Area" ); firstArea->m_label = generateUniqueAreaLabel(); firstArea->m_annotations.set( NODE_ANNOTATION_METRIC_MAPS, emptyMap, newHypothID ); firstArea->m_annotations.setElemental( NODE_ANNOTATION_REF_POSEID, POSEID_INVALID , newHypothID ); } // end of lock m_map_cs // ------------------------------------ // CLEAR LIST OF HYPOTHESES // ------------------------------------ { synch::CCriticalSectionLocker lock( &m_LMHs_cs ); // Add to the list: m_LMHs.clear(); CLocalMetricHypothesis &newLMH = m_LMHs[newHypothID]; newLMH.m_parent = this; newLMH.m_currentRobotPose = POSEID_INVALID ; // Special case: map is empty newLMH.m_log_w = 0; newLMH.m_ID = newHypothID; newLMH.m_neighbors.clear(); newLMH.m_neighbors.insert( firstAreaID ); newLMH.clearRobotPoses(); } // end of cs // ------------------------------------------ // Create the local SLAM algorithm object // ----------------------------------------- switch( m_options.SLAM_METHOD ) { case lsmRBPF_2DLASER: { if (m_LSLAM_method) delete m_LSLAM_method; m_LSLAM_method = new CLSLAM_RBPF_2DLASER(this); } break; default: THROW_EXCEPTION_FMT("Invalid selection for LSLAM method: %i",(int)m_options.SLAM_METHOD ); }; // ------------------------------------ // Topological LC detectors: // ------------------------------------ { synch::CCriticalSectionLocker lock( &m_topLCdets_cs ); // Clear old list: for (std::deque<CTopLCDetectorBase*>::iterator it=m_topLCdets.begin();it!=m_topLCdets.end();++it) delete *it; m_topLCdets.clear(); // Create new list: // 1: Occupancy Grid matching. // 2: Cummins' image matching. for (vector_string::const_iterator d=m_options.TLC_detectors.begin();d!=m_options.TLC_detectors.end();++d) m_topLCdets.push_back( loopClosureDetector_factory(*d) ); } // ------------------------------------ // Other variables: // ------------------------------------ m_LSLAM_queue.clear(); // ------------------------------------ // Delete log files: // ------------------------------------ if (!m_options.LOG_OUTPUT_DIR.empty()) { mrpt::system::deleteFilesInDirectory( m_options.LOG_OUTPUT_DIR ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/HMAP_txt" ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/HMAP_3D" ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/LSLAM_3D" ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/ASSO" ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/HMTSLAM_state" ); } } /*--------------------------------------------------------------- generateUniqueAreaLabel ---------------------------------------------------------------*/ std::string CHMTSLAM::generateUniqueAreaLabel() { return format( "%li", (long int)(m_nextAreaLabel++) ); } /*--------------------------------------------------------------- generatePoseID ---------------------------------------------------------------*/ TPoseID CHMTSLAM::generatePoseID() { return m_nextPoseID++; } /*--------------------------------------------------------------- generateHypothesisID ---------------------------------------------------------------*/ THypothesisID CHMTSLAM::generateHypothesisID() { return m_nextHypID++; } /*--------------------------------------------------------------- getAs3DScene ---------------------------------------------------------------*/ void CHMTSLAM::getAs3DScene( COpenGLScene &scene3D ) { MRPT_UNUSED_PARAM(scene3D); } /*--------------------------------------------------------------- abortedDueToErrors ---------------------------------------------------------------*/ bool CHMTSLAM::abortedDueToErrors() { return m_terminationFlag_LSLAM || m_terminationFlag_TBI || m_terminationFlag_3D_viewer; } /*--------------------------------------------------------------- registerLoopClosureDetector ---------------------------------------------------------------*/ void CHMTSLAM::registerLoopClosureDetector( const std::string &name, CTopLCDetectorBase* (*ptrCreateObject)(CHMTSLAM*) ) { m_registeredLCDetectors[name] = ptrCreateObject; } /*--------------------------------------------------------------- loopClosureDetector_factory ---------------------------------------------------------------*/ CTopLCDetectorBase* CHMTSLAM::loopClosureDetector_factory(const std::string &name) { MRPT_START std::map<std::string,TLopLCDetectorFactory>::const_iterator it=m_registeredLCDetectors.find( name ); if (it==m_registeredLCDetectors.end()) THROW_EXCEPTION_FMT("Invalid value for TLC_detectors: %s", name.c_str() ); return it->second(this); MRPT_END } /*--------------------------------------------------------------- saveState ---------------------------------------------------------------*/ bool CHMTSLAM::saveState( CStream &out ) const { try { out << *this; return true; } catch (...) { return false; } } /*--------------------------------------------------------------- loadState ---------------------------------------------------------------*/ bool CHMTSLAM::loadState( CStream &in ) { try { in >> *this; return true; } catch (...) { return false; } } /*--------------------------------------------------------------- readFromStream ---------------------------------------------------------------*/ void CHMTSLAM::readFromStream(mrpt::utils::CStream &in,int version) { switch(version) { case 0: { // Acquire all critical sections before! // ------------------------------------------- //std::map< THypothesisID, CLocalMetricHypothesis >::const_iterator it; //CCriticalSectionLocker LMHs( & m_LMHs_cs ); //for (it=m_LMHs.begin();it!=m_LMHs.end();it++) it->second.m_lock.enter(); CCriticalSectionLocker lock_map( &m_map_cs ); // Data: in >> m_nextAreaLabel >> m_nextPoseID >> m_nextHypID; // The HMT-MAP: in >> m_map; // The LMHs: in >> m_LMHs; // Save options??? Better allow changing them... // Release all critical sections: //for (it=m_LMHs.begin();it!=m_LMHs.end();it++) it->second.m_lock.enter(); } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version) }; } /*--------------------------------------------------------------- writeToStream Implements the writing to a CStream capability of CSerializable objects ---------------------------------------------------------------*/ void CHMTSLAM::writeToStream(mrpt::utils::CStream &out, int *version) const { if (version) *version = 0; else { // Acquire all critical sections before! // ------------------------------------------- //std::map< THypothesisID, CLocalMetricHypothesis >::const_iterator it; //CCriticalSectionLocker LMHs( & m_LMHs_cs ); //for (it=m_LMHs.begin();it!=m_LMHs.end();it++) it->second.m_lock.enter(); CCriticalSectionLocker lock_map( &m_map_cs ); // Data: out << m_nextAreaLabel << m_nextPoseID << m_nextHypID; // The HMT-MAP: out << m_map; // The LMHs: out << m_LMHs; // Save options??? Better allow changing them... // Release all critical sections: //for (it=m_LMHs.begin();it!=m_LMHs.end();it++) it->second.m_lock.enter(); } }
29.088193
113
0.554942
yhexie
224e0aaf3aae9fb677217087f4feeb5acfc8da0b
678
hpp
C++
utilities/autoware_launcher_rviz/src/module_panel.hpp
alanjclark/autoware.ai
ba97edbbffb6f22e78912bf96400a59ef6a13daf
[ "Apache-2.0" ]
20
2019-05-21T06:14:17.000Z
2021-11-03T04:36:09.000Z
ros/src/util/packages/autoware_rviz_plugins/autoware_launcher_rviz/src/module_panel.hpp
anhnv3991/autoware
d5b2ed9dc309193c8a2a7c77a2b6c88104c28328
[ "Apache-2.0" ]
40
2019-06-24T16:56:15.000Z
2022-02-28T13:41:58.000Z
ros/src/util/packages/autoware_rviz_plugins/autoware_launcher_rviz/src/module_panel.hpp
anhnv3991/autoware
d5b2ed9dc309193c8a2a7c77a2b6c88104c28328
[ "Apache-2.0" ]
31
2020-05-29T07:51:58.000Z
2022-03-26T05:46:33.000Z
#ifndef AUTOWARE_LAUNCHER_RVIZ_CONTROLLER_HPP #define AUTOWARE_LAUNCHER_RVIZ_CONTROLLER_HPP #include <unordered_map> #include <rviz/panel.h> #include <QWidget> #include <QPushButton> #include <QTcpSocket> namespace autoware_launcher_rviz { class ModulePanel : public rviz::Panel { Q_OBJECT public: ModulePanel(QWidget* parent = 0); protected: void paintEvent(QPaintEvent* event) override; private Q_SLOTS: void launch_button_toggled(bool checked); void server_connected(); void server_disconnected(); void server_error(); void server_ready_read(); private: QTcpSocket* socket; std::unordered_map<QPushButton*, std::string> buttons; }; } #endif
18.324324
56
0.768437
alanjclark
225116285d24ca6e60ba3efca6ba3cd68e515985
6,441
cpp
C++
cppillr/parser.cpp
dacap/cppillr
4b67403aab09c24d70c417e85567b48478f5aab0
[ "MIT" ]
4
2021-08-02T22:57:17.000Z
2021-12-26T16:45:17.000Z
cppillr/parser.cpp
dacap/cppillr
4b67403aab09c24d70c417e85567b48478f5aab0
[ "MIT" ]
null
null
null
cppillr/parser.cpp
dacap/cppillr
4b67403aab09c24d70c417e85567b48478f5aab0
[ "MIT" ]
null
null
null
// Copyright (C) 2019-2021 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #include "cppillr/parser.h" #include <memory> void Parser::parse(const LexData& lex) { data.fn = lex.fn; lex_data = &lex; goto_token(-1); dcl_seq(); } // Converts a function body that was "fast parsed" (only tokens) into // AST nodes. void Parser::parse_function_body(const LexData& lex, FunctionNode* f) { data.fn = lex.fn; lex_data = &lex; goto_token(f->body->beg_tok); f->body->block = compound_statement(); } bool Parser::dcl_seq() { while (next_token().kind != TokenKind::Eof) { if (!dcl()) return false; } return true; } bool Parser::dcl() { if (is_builtin_type()) { FunctionNode* f = function_definition(); if (f) { data.functions.push_back(f); return true; } } return false; } FunctionNode* Parser::function_definition() { if (is_builtin_type()) { auto f = std::make_unique<FunctionNode>(); f->builtin_type = (Keyword)tok->i; expect(TokenKind::Identifier, "expecting identifier for function"); f->name = lex_data->id_text(*tok); f->params = function_params(); if (!f->params) return nullptr; f->body = function_body_fast(); if (!f->body) return nullptr; return f.release(); } return nullptr; } ParamsNode* Parser::function_params() { auto ps = std::make_unique<ParamsNode>(); expect('('); while (next_token().kind != TokenKind::Eof) { if (is_punctuator(')')) { return ps.release(); } else if (is_builtin_type()) { auto p = std::make_unique<ParamNode>(); p->builtin_type = (Keyword)tok->i; next_token(); // Pointers while (is_punctuator('*')) // TODO add this info to param type next_token(); if (is(TokenKind::Identifier)) { // Param with name p->name = lex_data->id_text(*tok); next_token(); if (is_punctuator(')')) { ps->params.push_back(p.get()); p.release(); return ps.release(); } else if (!is_punctuator(',')) error("expecting ',' or ')' after param name"); } // Param without name else if (is_punctuator(')')) { ps->params.push_back(p.get()); p.release(); return ps.release(); } else if (!is_punctuator(',')) error("expecting ',', ')', or param name after param type"); ps->params.push_back(p.get()); p.release(); } else { error("expecting ')' or type"); } } return nullptr; } BodyNode* Parser::function_body_fast() { auto b = std::make_unique<BodyNode>(); int scope = 0; expect('{'); b->lex_i = lex_i; b->beg_tok = tok_i; while (next_token().kind != TokenKind::Eof) { if (is_punctuator('}')) { if (scope == 0) { b->end_tok = tok_i; return b.release(); } else --scope; } else if (is_punctuator('{')) { ++scope; } } error("expecting '}' before EOF"); return nullptr; } CompoundStmt* Parser::compound_statement() { auto b = std::make_unique<CompoundStmt>(); if (!is_punctuator('{')) error("expecting '{' to start a block"); next_token(); // Skip '{' while (tok->kind != TokenKind::Eof) { if (is_punctuator('}')) { return b.release(); } else { auto s = statement(); if (s) b->stmts.push_back(s); else return nullptr; } } error("expecting '}' before EOF"); return nullptr; } Stmt* Parser::statement() { if (is_punctuator(';')) { next_token(); // Skip ';', empty expression return nullptr; } else if (tok->kind == TokenKind::Keyword) { // Return statement switch (tok->i) { case key_return: return return_stmt(); default: error("not supported keyword %s", keywords_id[tok->i].c_str()); break; } } error("expecting '}' or statement"); return nullptr; } Return* Parser::return_stmt() { auto r = std::make_unique<Return>(); bool err = false; if (next_token().kind != TokenKind::Eof) { if (!is_punctuator(';')) { r->expr = expression(); if (!r->expr) err = true; } if (is_punctuator(';')) { next_token(); // Skip ';', return with expression } } else err = true; if (err) error("expecting ';' or expression for return statement"); return r.release(); } Expr* Parser::expression() { return additive_expression(); } // [expr.add] Expr* Parser::additive_expression() { std::unique_ptr<Expr> e(multiplicative_expression()); if (!e) return nullptr; while (is_punctuator('+') || is_punctuator('-')) { auto be = std::make_unique<BinExpr>(); be->op = tok->i; be->lhs = e.release(); next_token(); be->rhs = multiplicative_expression(); e = std::move(be); } return e.release(); } // [expr.mul] Expr* Parser::multiplicative_expression() { std::unique_ptr<Expr> e(primary_expression()); if (!e) return nullptr; while (is_punctuator('*') || is_punctuator('/') || is_punctuator('%')) { auto be = std::make_unique<BinExpr>(); be->op = tok->i; be->lhs = e.release(); next_token(); be->rhs = primary_expression(); if (!be->rhs) error("expecting expression after %c", be->op); e = std::move(be); } return e.release(); } // [expr.prim] Expr* Parser::primary_expression() { if (is_punctuator('(')) { next_token(); // Skip '(' std::unique_ptr<Expr> e(expression()); if (!is_punctuator(')')) error("expected ')' to finish expression"); next_token(); return e.release(); } else if (is_punctuator('*') || is_punctuator('&') || is_punctuator('+') || is_punctuator('-') || is_punctuator('!') || is_punctuator('~')) { auto be = std::make_unique<UnaryExpr>(); be->op = tok->i; next_token(); be->operand = primary_expression(); if (!be->operand) error("expected primary expression after '-'"); return be.release(); } else if (is(TokenKind::NumericConstant)) { auto l = std::make_unique<Literal>(); l->value = std::strtol(lex_data->id_text(*tok).c_str(), nullptr, 0); next_token(); return l.release(); } return nullptr; }
20.912338
72
0.567148
dacap
2252afa57cc8ec9b2d19325148cd3720d7dd5c34
7,530
cc
C++
cvmfs/receiver/payload_processor.cc
amadio/cvmfs
2cc5dc22c6c163e8515229006a0c6f8fbad9c23d
[ "BSD-3-Clause" ]
null
null
null
cvmfs/receiver/payload_processor.cc
amadio/cvmfs
2cc5dc22c6c163e8515229006a0c6f8fbad9c23d
[ "BSD-3-Clause" ]
2
2018-05-04T13:43:45.000Z
2018-08-27T13:53:45.000Z
cvmfs/receiver/payload_processor.cc
amadio/cvmfs
2cc5dc22c6c163e8515229006a0c6f8fbad9c23d
[ "BSD-3-Clause" ]
null
null
null
/** * This file is part of the CernVM File System. */ #include "payload_processor.h" #include <fcntl.h> #include <unistd.h> #include <vector> #include "logging.h" #include "params.h" #include "util/posix.h" #include "util/string.h" namespace { const size_t kConsumerBuffer = 10 * 1024 * 1024; // 10 MB } namespace receiver { FileInfo::FileInfo() : handle(NULL), total_size(0), current_size(0), hash_context(), hash_buffer() {} FileInfo::FileInfo(const ObjectPackBuild::Event& event) : handle(NULL), total_size(event.size), current_size(0), hash_context(shash::ContextPtr(event.id.algorithm)), hash_buffer(hash_context.size, 0) { hash_context.buffer = &hash_buffer[0]; shash::Init(hash_context); } FileInfo::FileInfo(const FileInfo& other) : handle(other.handle), total_size(other.total_size), current_size(other.current_size), hash_context(other.hash_context), hash_buffer(other.hash_buffer) { hash_context.buffer = &hash_buffer[0]; } FileInfo& FileInfo::operator=(const FileInfo& other) { handle = other.handle; total_size = other.total_size; current_size = other.current_size; hash_context = other.hash_context; hash_buffer = other.hash_buffer; hash_context.buffer = &hash_buffer[0]; return *this; } PayloadProcessor::PayloadProcessor() : pending_files_(), current_repo_(), uploader_(), temp_dir_(), num_errors_(0), statistics_(NULL) {} PayloadProcessor::~PayloadProcessor() {} PayloadProcessor::Result PayloadProcessor::Process( int fdin, const std::string& header_digest, const std::string& path, uint64_t header_size) { LogCvmfs(kLogReceiver, kLogSyslog, "PayloadProcessor - lease_path: %s, header digest: %s, header " "size: %ld", path.c_str(), header_digest.c_str(), header_size); const size_t first_slash_idx = path.find('/', 0); current_repo_ = path.substr(0, first_slash_idx); Result init_result = Initialize(); if (init_result != kSuccess) { return init_result; } // Set up object pack deserialization shash::Any digest = shash::MkFromHexPtr(shash::HexPtr(header_digest)); ObjectPackConsumer deserializer(digest, header_size); deserializer.RegisterListener(&PayloadProcessor::ConsumerEventCallback, this); int nb = 0; ObjectPackBuild::State consumer_state = ObjectPackBuild::kStateContinue; std::vector<unsigned char> buffer(kConsumerBuffer, 0); do { nb = read(fdin, &buffer[0], buffer.size()); consumer_state = deserializer.ConsumeNext(nb, &buffer[0]); if (consumer_state != ObjectPackBuild::kStateContinue && consumer_state != ObjectPackBuild::kStateDone) { LogCvmfs(kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: %d encountered when consuming object " "pack.", consumer_state); break; } } while (nb > 0 && consumer_state != ObjectPackBuild::kStateDone); assert(pending_files_.empty()); Result res = Finalize(); deserializer.UnregisterListeners(); return res; } void PayloadProcessor::ConsumerEventCallback( const ObjectPackBuild::Event& event) { std::string path(""); if (event.object_type == ObjectPack::kCas) { path = event.id.MakePath(); } else if (event.object_type == ObjectPack::kNamed) { path = event.object_name; } else { // kEmpty - this is an error. LogCvmfs(kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: Event received with unknown object."); num_errors_++; return; } FileIterator it = pending_files_.find(event.id); if (it == pending_files_.end()) { // Schedule file upload if it's not being uploaded yet. // Uploaders later check if the file is already present // in the upstream storage and will not upload it twice. FileInfo info(event); // info.handle is later deleted by FinalizeStreamedUpload info.handle = uploader_->InitStreamedUpload(NULL); pending_files_[event.id] = info; } FileInfo& info = pending_files_[event.id]; void *buf_copied = smalloc(event.buf_size); memcpy(buf_copied, event.buf, event.buf_size); upload::AbstractUploader::UploadBuffer buf(event.buf_size, buf_copied); uploader_->ScheduleUpload(info.handle, buf, upload::AbstractUploader::MakeClosure( &PayloadProcessor::OnUploadJobComplete, this, buf_copied)); shash::Update(static_cast<const unsigned char*>(event.buf), event.buf_size, info.hash_context); info.current_size += event.buf_size; if (info.current_size == info.total_size) { shash::Any file_hash(event.id.algorithm); shash::Final(info.hash_context, &file_hash); if (file_hash != event.id) { LogCvmfs( kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: Hash mismatch for unpacked file: event " "size: %ld, file size: %ld, event hash: %s, file hash: %s", event.size, info.current_size, event.id.ToString(true).c_str(), file_hash.ToString(true).c_str()); num_errors_++; return; } // override final remote path if not CAS object if (event.object_type == ObjectPack::kNamed) { info.handle->remote_path = path; } uploader_->ScheduleCommit(info.handle, event.id); pending_files_.erase(event.id); } } void PayloadProcessor::OnUploadJobComplete( const upload::UploaderResults &results, void *buffer) { free(buffer); } void PayloadProcessor::SetStatistics(perf::Statistics *st) { statistics_ = new perf::StatisticsTemplate("Publish", st); } PayloadProcessor::Result PayloadProcessor::Initialize() { Params params; if (!GetParamsFromFile(current_repo_, &params)) { LogCvmfs( kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: Could not get configuration parameters."); return kOtherError; } const std::string spooler_temp_dir = GetSpoolerTempDir(params.spooler_configuration); assert(!spooler_temp_dir.empty()); assert(MkdirDeep(spooler_temp_dir + "/receiver", 0770, true)); temp_dir_ = RaiiTempDir::Create(spooler_temp_dir + "/receiver/payload_processor"); upload::SpoolerDefinition definition( params.spooler_configuration, params.hash_alg, params.compression_alg, params.generate_legacy_bulk_chunks, params.use_file_chunking, params.min_chunk_size, params.avg_chunk_size, params.max_chunk_size, "dummy_token", "dummy_key"); uploader_.Destroy(); // configure the uploader environment uploader_ = upload::AbstractUploader::Construct(definition); if (!uploader_) { LogCvmfs(kLogSpooler, kLogWarning, "Failed to initialize backend upload " "facility in PayloadProcessor."); return kUploaderError; } if (statistics_.IsValid()) { uploader_->InitCounters(statistics_); } return kSuccess; } PayloadProcessor::Result PayloadProcessor::Finalize() { uploader_->WaitForUpload(); temp_dir_.Destroy(); const unsigned num_uploader_errors = uploader_->GetNumberOfErrors(); uploader_->TearDown(); if (num_uploader_errors > 0) { LogCvmfs(kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: Uploader - %d upload(s) failed.", num_uploader_errors); return kUploaderError; } if (GetNumErrors() > 0) { LogCvmfs(kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: % unpacking error(s).", GetNumErrors()); return kOtherError; } return kSuccess; } } // namespace receiver
28.740458
80
0.691368
amadio
225477a8424205cd4b10ab8b0b74bb3ccbf35960
8,294
cpp
C++
stdmap-speedup/stdmap-speedup.cpp
demonMOE-s/Toys
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
[ "BSD-2-Clause" ]
null
null
null
stdmap-speedup/stdmap-speedup.cpp
demonMOE-s/Toys
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
[ "BSD-2-Clause" ]
null
null
null
stdmap-speedup/stdmap-speedup.cpp
demonMOE-s/Toys
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
[ "BSD-2-Clause" ]
null
null
null
/* Author: Wojciech Muła e-mail: wojciech_mula@poczta.onet.pl www: http://wm.ite.pl/ License: public domain initial release 3-04-2010 */ #include <iostream> #include <vector> #include <map> #include <string> #include <sys/time.h> unsigned gettime() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000000 + tv.tv_usec)/1000; } //--------------------------------------------------------------------------- template <class TValue> class size_char_map_t { private: typedef std::map<std::string, TValue> map_t; typedef std::vector<map_t> vector_map_t; typedef std::vector<vector_map_t> vector_t; vector_t table; public: size_char_map_t(size_t max_length); int count(const std::string& key) const; size_t size() const; void insert(const std::string& key, TValue val); }; template <class TValue> size_char_map_t<TValue>::size_char_map_t(size_t max_length) { for (size_t k=0; k < max_length; k++) { vector_map_t subtable; map_t map; for (int i=0; i < 256; i++) subtable.push_back(map); table.push_back(subtable); } } //--------------------------------------------------------------------------- template <class TValue> int size_char_map_t<TValue>::count(const std::string& key) const { const vector_map_t& subtable = table[key.size()]; const unsigned idx = (unsigned char)(key[0]); const map_t& map = subtable[idx]; return map.count(key); } //--------------------------------------------------------------------------- template <class TValue> size_t size_char_map_t<TValue>::size() const { unsigned i, j, n; size_t k = 0; n = table.size(); for (i=0; i < n; i++) { const vector_map_t& subtable = table[i]; // std::cout << "length=" << i << std::endl; for (j=0; j < 256; j++) { // std::cout << '\t' << "count[" << j << "]=" << subtable[j].size() << std::endl; k += subtable[j].size(); } } return k; } //--------------------------------------------------------------------------- template <class TValue> void size_char_map_t<TValue>::insert(const std::string& key, TValue val) { vector_map_t& subtable = table[key.size()]; const unsigned idx = (unsigned char)(key[0]); subtable[idx][key] = val; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- template <class TValue> class size_map_t { private: typedef std::map<std::string, TValue> map_t; typedef std::vector<map_t> vector_t; vector_t table; public: size_map_t(size_t max_length); int count(const std::string& key) const; size_t size() const; void insert(const std::string& key, TValue val); }; template <class TValue> size_map_t<TValue>::size_map_t(size_t max_length) { for (size_t k=0; k < max_length; k++) { map_t map; table.push_back(map); } } //--------------------------------------------------------------------------- template <class TValue> int size_map_t<TValue>::count(const std::string& key) const { const map_t& map = table[key.size()]; return map.count(key); } //--------------------------------------------------------------------------- template <class TValue> size_t size_map_t<TValue>::size() const { unsigned i, j, n; size_t k = 0; n = table.size(); for (i=0; i < n; i++) { // std::cout << "length=" << i << " count=" << table[i].size() << std::endl; k += table[i].size(); } return k; } //--------------------------------------------------------------------------- template <class TValue> void size_map_t<TValue>::insert(const std::string& key, TValue val) { table[key.size()][key] = val; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- template <class TValue> class char_map_t { private: typedef std::map<std::string, TValue> map_t; typedef std::vector<map_t> vector_t; vector_t table; public: char_map_t(); int count(const std::string& key) const; size_t size() const; void insert(const std::string& key, TValue val); }; template <class TValue> char_map_t<TValue>::char_map_t() { map_t map; for (int i=0; i < 256; i++) table.push_back(map); } //--------------------------------------------------------------------------- template <class TValue> int char_map_t<TValue>::count(const std::string& key) const { const unsigned idx = (unsigned char)(key[0]); const map_t& map = table[idx]; return map.count(key); } //--------------------------------------------------------------------------- template <class TValue> size_t char_map_t<TValue>::size() const { unsigned i, j, n; size_t k = 0; for (j=0; j < 256; j++) { // std::cout << '\t' << "count[" << j << "]=" << table[j].size() << std::endl; k += table[j].size(); } return k; } //--------------------------------------------------------------------------- template <class TValue> void char_map_t<TValue>::insert(const std::string& key, TValue val) { const unsigned idx = (unsigned char)(key[0]); map_t& map = table[idx]; map[key] = val; } //--------------------------------------------------------------------------- int main(int argc, char* argv[]) { using namespace std; size_char_map_t<int> map1(1024); size_map_t<int> map2(1024); char_map_t<int> map3; map<string, int> map4; vector<string> words; string s; unsigned t1, t2; //-------------------------------------------------- t1 = gettime(); cout << "loading words..." << endl; while (not cin.eof()) { cin >> s; if (not s.empty()) words.push_back(s); } t2 = gettime(); cout << t2 - t1 << " ms" << " words=" << words.size() << endl; //-------------------------------------------------- t1 = gettime(); cout << "inserting into maps grouped by size & first char" << endl; unsigned i, n = words.size(); for (i=0; i < n; i++) { //cout << '#' << i << " '" << words[i] << '\'' << endl; map1.insert(words[i], i); } t2 = gettime(); cout << t2 - t1 << " ms" << endl; //-------------------------------------------------- t1 = gettime(); cout << "inserting into maps grouped by size" << endl; for (i=0; i < n; i++) //cout << '#' << i << " '" << words[i] << '\'' << endl; map2.insert(words[i], i); t2 = gettime(); cout << t2 - t1 << " ms" << endl; //-------------------------------------------------- t1 = gettime(); cout << "inserting into maps grouped by first char" << endl; for (i=0; i < n; i++) //cout << '#' << i << " '" << words[i] << '\'' << endl; map3.insert(words[i], i); t2 = gettime(); cout << t2 - t1 << " ms" << endl; //-------------------------------------------------- t1 = gettime(); cout << "inserting into std::map" << endl; for (i=0; i < n; i++) map4[words[i]] = i; t2 = gettime(); cout << t2 - t1 << " ms" << endl; //-------------------------------------------------- cout << endl; cout << "size1=" << map1.size() << " size2=" << map2.size() << " size3=" << map3.size() << " size4=" << map4.size() << endl; //-------------------------------------------------- t1 = gettime(); cout << "reading from maps grouped by size & first char" << endl; for (i=0; i < n; i++) if (map1.count(words[i]) == 0) { cerr << "error1 at #" << i; return 1; } t2 = gettime(); cout << t2 - t1 << " ms" << endl; //-------------------------------------------------- t1 = gettime(); cout << "reading from maps grouped by size" << endl; for (i=0; i < n; i++) if (map2.count(words[i]) == 0) { cerr << "error2 at #" << i; return 1; } t2 = gettime(); cout << t2 - t1 << " ms" << endl; //-------------------------------------------------- t1 = gettime(); cout << "reading from maps grouped by first char" << endl; for (i=0; i < n; i++) if (map3.count(words[i]) == 0) { cerr << "error3 at #" << i; return 1; } t2 = gettime(); cout << t2 - t1 << " ms" << endl; //-------------------------------------------------- t1 = gettime(); cout << "reading from std::map" << endl; for (i=0; i < n; i++) if (map4.count(words[i]) == 0) { cerr << "error4 at #" << i; return 1; } t2 = gettime(); cout << t2 - t1 << " ms" << endl; return 0; }
26
83
0.464673
demonMOE-s
2255c2bc0f12bbaf4f04a3925c00b7c81bee2a5c
557
cpp
C++
source/dataset/CameraMgr.cpp
xzrunner/easyeditor3
61c89c8534d1342fb2890d7e6218fd7614410861
[ "MIT" ]
null
null
null
source/dataset/CameraMgr.cpp
xzrunner/easyeditor3
61c89c8534d1342fb2890d7e6218fd7614410861
[ "MIT" ]
null
null
null
source/dataset/CameraMgr.cpp
xzrunner/easyeditor3
61c89c8534d1342fb2890d7e6218fd7614410861
[ "MIT" ]
null
null
null
#include "ee3/CameraMgr.h" #include <painting3/OrthoCam.h> namespace ee3 { CameraMgr::CameraMgr(bool only3d) : m_curr(CAM_3D) { assert(m_cams[CAM_3D] == nullptr); if (!only3d) { m_cams[CAM_XZ] = std::make_shared<pt3::OrthoCam>(pt3::OrthoCam::VP_XZ); m_cams[CAM_XY] = std::make_shared<pt3::OrthoCam>(pt3::OrthoCam::VP_XY); m_cams[CAM_ZY] = std::make_shared<pt3::OrthoCam>(pt3::OrthoCam::VP_ZY); } } const pt0::CameraPtr& CameraMgr::SwitchToNext() { m_curr = static_cast<CameraType>((m_curr + 1) % CAM_MAX_COUNT); return m_cams[m_curr]; } }
20.62963
73
0.70377
xzrunner
225c7fbc994b5d869f4c15e02ab60b461054f22b
16,491
cpp
C++
Sources/Elastos/LibCore/src/org/apache/harmony/security/x509/CDNParser.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/src/org/apache/harmony/security/x509/CDNParser.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/src/org/apache/harmony/security/x509/CDNParser.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "org/apache/harmony/security/x509/CDNParser.h" #include "org/apache/harmony/security/x501/CAttributeValue.h" #include "org/apache/harmony/security/x501/CAttributeTypeAndValue.h" #include "org/apache/harmony/security/asn1/ASN1Type.h" #include <elastos/core/CoreUtils.h> #include <elastos/core/StringBuilder.h> #include <elastos/utility/Arrays.h> #include "elastos/utility/CArrayList.h" #include "core/CArrayOf.h" #include "core/CByte.h" using Org::Apache::Harmony::Security::Asn1::ASN1Type; using Org::Apache::Harmony::Security::Asn1::IASN1Type; using Org::Apache::Harmony::Security::X501::IAttributeValue; using Org::Apache::Harmony::Security::X501::CAttributeValue; using Org::Apache::Harmony::Security::X501::IAttributeTypeAndValue; using Org::Apache::Harmony::Security::X501::CAttributeTypeAndValue; using Org::Apache::Harmony::Security::Utils::IObjectIdentifier; using Elastos::Core::IArrayOf; using Elastos::Core::CArrayOf; using Elastos::Core::IByte; using Elastos::Core::CByte; using Elastos::Core::CoreUtils; using Elastos::Core::StringBuilder; using Elastos::Utility::Arrays; using Elastos::Utility::CArrayList; namespace Org { namespace Apache { namespace Harmony { namespace Security { namespace X509 { CAR_OBJECT_IMPL(CDNParser) CAR_INTERFACE_IMPL(CDNParser, Object, IDNParser) ECode CDNParser::constructor( /* [in] */ const String& dn) { mChars = dn.GetChars(); return NOERROR; } ECode CDNParser::NextAT( /* [out] */ String* str) { VALIDATE_NOT_NULL(str); *str = NULL; mHasQE = FALSE; // reset // skip preceding space chars, they can present after // comma or semicolon (compatibility with RFC 1779) for (; mPos < mChars->GetLength() && (*mChars)[mPos] == ' '; mPos++) { } if (mPos == mChars->GetLength()) { *str = NULL; // reached the end of DN return NOERROR; } // mark the beginning of attribute type mBeg = mPos; // attribute type chars mPos++; for (; mPos < mChars->GetLength() && (*mChars)[mPos] != '=' && (*mChars)[mPos] != ' '; mPos++) { // we don't follow exact BNF syntax here: // accept any char except space and '=' } if (mPos >= mChars->GetLength()) { // unexpected end of DN //throw new IOException("Invalid distinguished name string"); *str = NULL; return E_IO_EXCEPTION; } // mark the end of attribute type mEnd = mPos; // skip trailing space chars between attribute type and '=' // (compatibility with RFC 1779) if ((*mChars)[mPos] == ' ') { for (; mPos < mChars->GetLength() && (*mChars)[mPos] != '=' && (*mChars)[mPos] == ' '; mPos++) { } if ((*mChars)[mPos] != '=' || mPos == mChars->GetLength()) { // unexpected end of DN //throw new IOException("Invalid distinguished name string"); *str = NULL; return E_IO_EXCEPTION; } } mPos++; //skip '=' char // skip space chars between '=' and attribute value // (compatibility with RFC 1779) for (; mPos < mChars->GetLength() && (*mChars)[mPos] == ' '; mPos++) { } // in case of oid attribute type skip its prefix: "oid." or "OID." // (compatibility with RFC 1779) if ((mEnd - mBeg > 4) && ((*mChars)[mBeg + 3] == '.') && ((*mChars)[mBeg] == 'O' || (*mChars)[mBeg] == 'o') && ((*mChars)[mBeg + 1] == 'I' || (*mChars)[mBeg + 1] == 'i') && ((*mChars)[mBeg + 2] == 'D' || (*mChars)[mBeg + 2] == 'd')) { mBeg += 4; } *str = String(*mChars, mBeg, mEnd - mBeg); return NOERROR; } ECode CDNParser::QuotedAV( /* [out] */ String* str) { VALIDATE_NOT_NULL(str); *str = NULL; mPos++; mBeg = mPos; mEnd = mBeg; while (TRUE) { if (mPos == mChars->GetLength()) { // unexpected end of DN //throw new IOException("Invalid distinguished name string"); *str = NULL; return E_IO_EXCEPTION; } if ((*mChars)[mPos] == '"') { // enclosing quotation was found mPos++; break; } else if ((*mChars)[mPos] == '\\') { Char32 c; FAIL_RETURN(GetEscaped(&c)) (*mChars)[mEnd] = c; } else { // shift char: required for string with escaped chars (*mChars)[mEnd] = (*mChars)[mPos]; } mPos++; mEnd++; } // skip trailing space chars before comma or semicolon. // (compatibility with RFC 1779) for (; mPos < mChars->GetLength() && (*mChars)[mPos] == ' '; mPos++) { } *str = String(*mChars, mBeg, mEnd - mBeg); return NOERROR; } ECode CDNParser::HexAV( /* [out] */ String* str) { VALIDATE_NOT_NULL(str); *str = NULL; if (mPos + 4 >= mChars->GetLength()) { // encoded byte array must be not less then 4 c //throw new IOException("Invalid distinguished name string"); *str = NULL; return E_IO_EXCEPTION; } mBeg = mPos; // store '#' position mPos++; while (TRUE) { // check for end of attribute value // looks for space and component separators if (mPos == mChars->GetLength() || (*mChars)[mPos] == '+' || (*mChars)[mPos] == ',' || (*mChars)[mPos] == ';') { mEnd = mPos; break; } if ((*mChars)[mPos] == ' ') { mEnd = mPos; mPos++; // skip trailing space chars before comma or semicolon. // (compatibility with RFC 1779) for (; mPos < mChars->GetLength() && (*mChars)[mPos] == ' '; mPos++) { } break; } else if ((*mChars)[mPos] >= 'A' && (*mChars)[mPos] <= 'F') { (*mChars)[mPos] += 32; //to low case } mPos++; } // verify length of hex string // encoded byte array must be not less then 4 and must be even number Int32 hexLen = mEnd - mBeg; // skip first '#' char if (hexLen < 5 || (hexLen & 1) == 0) { //throw new IOException("Invalid distinguished name string"); *str = NULL; return E_IO_EXCEPTION; } // get byte encoding from string representation mEncoded = ArrayOf<Byte>::Alloc(hexLen / 2); for (Int32 i = 0, p = mBeg + 1; i < mEncoded->GetLength(); p += 2, i++) { Int32 b; FAIL_RETURN(GetByte(p, &b)); (*mEncoded)[i] = (Byte)b; } *str = String(*mChars, mBeg, hexLen); return NOERROR; } ECode CDNParser::EscapedAV( /* [out] */ String* str) { VALIDATE_NOT_NULL(str); *str = NULL; mBeg = mPos; mEnd = mPos; while (TRUE) { if (mPos >= mChars->GetLength()) { // the end of DN has been found *str = String(*mChars, mBeg, mEnd - mBeg); return NOERROR; } switch ((*mChars)[mPos]) { case '+': case ',': case ';': { // separator char has been found *str = String(*mChars, mBeg, mEnd - mBeg); return NOERROR; } case '\\': { // escaped char Char32 c; FAIL_RETURN(GetEscaped(&c)) (*mChars)[mEnd++] = c; mPos++; break; } case ' ': { // need to figure out whether space defines // the end of attribute value or not Int32 cur = mEnd; mPos++; (*mChars)[mEnd++] = ' '; for (; mPos < mChars->GetLength() && (*mChars)[mPos] == ' '; mPos++) { (*mChars)[mEnd++] = ' '; } if (mPos == mChars->GetLength() || (*mChars)[mPos] == ',' || (*mChars)[mPos] == '+' || (*mChars)[mPos] == ';') { // separator char or the end of DN has been found *str = String(*mChars, mBeg, cur - mBeg); return NOERROR; } break; } default: (*mChars)[mEnd++] = (*mChars)[mPos]; mPos++; } } return NOERROR; } ECode CDNParser::GetEscaped( /* [out] */ Char32* c) { VALIDATE_NOT_NULL(c); mPos++; if (mPos == mChars->GetLength()) { //throw new IOException("Invalid distinguished name string"); *c = 0; return E_IO_EXCEPTION; } Char32 ch = (*mChars)[mPos]; switch (ch) { case '"': case '\\': mHasQE = TRUE; return ch; case ',': case '=': case '+': case '<': case '>': case '#': case ';': case ' ': case '*': case '%': case '_': //FIXME: escaping is allowed only for leading or trailing space char *c = ch; return NOERROR; default: // RFC doesn't explicitly say that escaped hex pair is // interpreted as UTF-8 char. It only contains an example of such DN. return GetUTF8(c); } return NOERROR; } ECode CDNParser::GetUTF8( /* [out] */ Char32* c) { VALIDATE_NOT_NULL(c); *c = 0; Int32 res; FAIL_RETURN(GetByte(mPos, &res)) mPos++; //FIXME tmp if (res < 128) { // one byte: 0-7F *c = (Char32)res; return NOERROR; } else if (res >= 192 && res <= 247) { Int32 count; if (res <= 223) { // two bytes: C0-DF count = 1; res = res & 0x1F; } else if (res <= 239) { // three bytes: E0-EF count = 2; res = res & 0x0F; } else { // four bytes: F0-F7 count = 3; res = res & 0x07; } Int32 b; for (Int32 i = 0; i < count; i++) { mPos++; if (mPos == mChars->GetLength() || (*mChars)[mPos] != '\\') { *c = 0x3F; //FIXME failed to decode UTF-8 char - return '?' return NOERROR; } mPos++; FAIL_RETURN(GetByte(mPos, &b)) mPos++; //FIXME tmp if ((b & 0xC0) != 0x80) { *c = 0x3F; //FIXME failed to decode UTF-8 char - return '?' return NOERROR; } res = (res << 6) + (b & 0x3F); } *c = (Char32)res; return NOERROR; } else { *c = 0x3F; //FIXME failed to decode UTF-8 char - return '?' return NOERROR; } return NOERROR; } ECode CDNParser::GetByte( /* [in] */ Int32 position, /* [out] */ Int32* b) { VALIDATE_NOT_NULL(b); *b = 0; if ((position + 1) >= mChars->GetLength()) { // to avoid ArrayIndexOutOfBoundsException //throw new IOException("Invalid distinguished name string"); return E_IO_EXCEPTION; } Int32 b1 = (*mChars)[position]; if (b1 >= '0' && b1 <= '9') { b1 = b1 - '0'; } else if (b1 >= 'a' && b1 <= 'f') { b1 = b1 - 87; // 87 = 'a' - 10 } else if (b1 >= 'A' && b1 <= 'F') { b1 = b1 - 55; // 55 = 'A' - 10 } else { //throw new IOException("Invalid distinguished name string"); return E_IO_EXCEPTION; } Int32 b2 = (*mChars)[position + 1]; if (b2 >= '0' && b2 <= '9') { b2 = b2 - '0'; } else if (b2 >= 'a' && b2 <= 'f') { b2 = b2 - 87; // 87 = 'a' - 10 } else if (b2 >= 'A' && b2 <= 'F') { b2 = b2 - 55; // 55 = 'A' - 10 } else { //throw new IOException("Invalid distinguished name string"); return E_IO_EXCEPTION; } *b = (b1 << 4) + b2; return NOERROR; } ECode CDNParser::Parse( /* [out] */ IList** ppList) { VALIDATE_NOT_NULL(ppList); *ppList = NULL; AutoPtr<IList> list; CArrayList::New((IList**)&list); String attType; FAIL_RETURN(NextAT(&attType)); if (attType.IsNull()) { *ppList = list; //empty list of RDNs REFCOUNT_ADD(*ppList); return NOERROR; } AutoPtr<IObjectIdentifier> oid; CAttributeTypeAndValue::GetObjectIdentifier(attType, (IObjectIdentifier**)&oid); AutoPtr<IList> atav; CArrayList::New((IList**)&atav); while (TRUE) { if (mPos == mChars->GetLength()) { //empty Attribute Value AutoPtr<IAttributeValue> av; CAttributeValue::New(String(""), FALSE, oid, (IAttributeValue**)&av); AutoPtr<IAttributeTypeAndValue> atv; CAttributeTypeAndValue::New(oid, av, (IAttributeTypeAndValue**)&atv); atav->Add(TO_IINTERFACE(atv)); list->Add(0, TO_IINTERFACE(atav)); *ppList = list; REFCOUNT_ADD(*ppList); return NOERROR; } switch ((*mChars)[mPos]) { case '"': { String str; FAIL_RETURN(QuotedAV(&str)) AutoPtr<IAttributeValue> av; CAttributeValue::New(str, mHasQE, oid, (IAttributeValue**)&av); AutoPtr<IAttributeTypeAndValue> atv; CAttributeTypeAndValue::New(oid, av, (IAttributeTypeAndValue**)&atv); atav->Add(TO_IINTERFACE(atv)); break; } case '#': { String str; FAIL_RETURN(HexAV(&str)) AutoPtr<IAttributeValue> av; CAttributeValue::New(str, mEncoded, (IAttributeValue**)&av); AutoPtr<IAttributeTypeAndValue> atv; CAttributeTypeAndValue::New(oid, av, (IAttributeTypeAndValue**)&atv); atav->Add(TO_IINTERFACE(atv)); break; } case '+': case ',': case ';': // compatibility with RFC 1779: semicolon can separate RDNs { //empty attribute value AutoPtr<IAttributeValue> av; CAttributeValue::New(String(""), FALSE, oid, (IAttributeValue**)&av); AutoPtr<IAttributeTypeAndValue> atv; CAttributeTypeAndValue::New(oid, av, (IAttributeTypeAndValue**)&atv); atav->Add(TO_IINTERFACE(atv)); break; } default: { String str; FAIL_RETURN(EscapedAV(&str)) AutoPtr<IAttributeValue> av; CAttributeValue::New(str, mHasQE, oid, (IAttributeValue**)&av); AutoPtr<IAttributeTypeAndValue> atv; CAttributeTypeAndValue::New(oid, av, (IAttributeTypeAndValue**)&atv); atav->Add(TO_IINTERFACE(atv)); } } if (mPos >= mChars->GetLength()) { list->Add(0, TO_IINTERFACE(atav)); *ppList = list; REFCOUNT_ADD(*ppList); return NOERROR; } if ((*mChars)[mPos] == ',' || (*mChars)[mPos] == ';') { list->Add(0, TO_IINTERFACE(atav)); CArrayList::New((IList**)&atav); } else if ((*mChars)[mPos] != '+') { //throw new IOException("Invalid distinguished name string"); return E_IO_EXCEPTION; } mPos++; FAIL_RETURN(NextAT(&attType)); if (attType.IsNull()) { //throw new IOException("Invalid distinguished name string"); return E_IO_EXCEPTION; } CAttributeTypeAndValue::GetObjectIdentifier(attType, (IObjectIdentifier**)&oid); } return NOERROR; } } // namespace X509 } // namespace Security } // namespace Harmony } // namespace Apache } // namespace Org
29.660072
104
0.510703
jingcao80