blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
78ce830aa4aaca857a008d330cae6f57386bbf6f
a3634de7800ae5fe8e68532d7c3a7570b9c61c5b
/schedule1.cpp
fb34f2f0d7740ec82a48ca98c2a50d35c20c7975
[]
no_license
MayankChaturvedi/competitive-coding
a737a2a36b8aa7aea1193f2db4b32b081f78e2ba
9e9bd21de669c7b7bd29a262b29965ecc80ad621
refs/heads/master
2020-03-18T01:39:29.447631
2018-02-19T15:04:32
2018-02-19T15:04:32
134,152,930
0
1
null
2018-05-20T13:27:35
2018-05-20T13:27:34
null
UTF-8
C++
false
false
1,043
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; ios_base::sync_with_stdio(false); cin.tie(NULL); cin>>t; while(t--) { int n, k; cin>>n>>k; string x; cin>>x; int i=0, j=0; while(k--) { int lenmax=0, imax=0; if(j==n) { i=0; j=0; } while(j<n) { if(x[i]==x[j]) j++; else { if(j-i>lenmax) { lenmax=j-i; imax=i; } i=j; } } if(j==n && x[j-1]==x[i] && j-i>lenmax) { lenmax=j-i; imax=i; } if(lenmax==1) break; if(x[imax+ (lenmax)/2]=='1') x[imax+ (lenmax)/2]='0'; else x[imax+ (lenmax)/2]='1'; //x[imax+ (lenmax)/2]=!x[imax+ (lenmax)/2]; //cout<<lenmax<<endl; } int ans=0; i=0; j=0; while(j<n) { if(x[i]==x[j]) j++; else { ans=max(ans,j-i); i=j; } } if(j==n && x[j-1]==x[i] ) { ans=max(ans,j-i); } cout<<ans<<'\n'; } return 0; }
[ "f20160006@goa.bits-pilani.ac.in" ]
f20160006@goa.bits-pilani.ac.in
f8f4c514069d4d30651a9860ede0833ebeedc38b
6dc5f480c3dcad8693726cbfa24cba66b6cb3184
/src/rtk_sub_node.cpp
fc931a90cf8ea5d766081fda6e7fc82e79e9268c
[]
no_license
climb0079climb0079/rtk_driver
a821be3ce2f1966a257475891897b1361160418d
be65b7e016648701049198c53be7cebfddca2743
refs/heads/master
2022-09-29T11:45:12.460687
2020-06-05T06:36:10
2020-06-05T06:36:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
864
cpp
#include "ros/ros.h" #include "std_msgs/String.h" #include "sensor_msgs/NavSatFix.h" #include <iostream> #include <iomanip> #include <fstream> using namespace std; void gpsCallback(const sensor_msgs::NavSatFix& gps_msgs) { //ROS_INFO("I heard time:[%ld], lat:[%lf], lng:[%lf], height[%lf]", gps_msgs.header.stamp, gps_msgs.longitude, gps_msgs.latitude, gps_msgs.altitude); cout << std::setprecision(15) << gps_msgs.latitude << " " << gps_msgs.longitude << " " << gps_msgs.altitude << endl; ofstream fs("/home/xl/rtk_pose_llh.txt", ios::app); fs << std::setprecision(15) << gps_msgs.latitude << " " << gps_msgs.longitude << " " << gps_msgs.altitude << endl; } int main(int argc,char **argv) { ros::init(argc, argv, "listener"); ros::NodeHandle n; ros::Subscriber my_sub = n.subscribe("gps_pub",50, gpsCallback); ros::spin(); return 0; }
[ "1393089237@qq.com" ]
1393089237@qq.com
d818a4ca10a6af7326eca39e600f92ff79e72490
5c34abe10630b23da8ba7d1cbce38bda53a4b6fa
/RootAnalysis/src/RootTreeAnalysis/MuonAnalysis.cxx
da98c2435a7dbe242431b80013ed178ce0d9061f
[]
no_license
fermi-lat/GlastRelease-scons-old
cde76202f706b1c8edbf47b52ff46fe6204ee608
95f1daa22299272314025a350f0c6ef66eceda08
refs/heads/master
2021-07-23T02:41:48.198247
2017-05-09T17:27:58
2017-05-09T17:27:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
54,771
cxx
#ifndef RootTreeAnalysis_cxx #define RootTreeAnalysis_cxx 1 #include "MuonAnalysis.h" #include <string> //TObjArray tkrLayerHistArr; UInt_t digiEventId, reconEventId, mcEventId; UInt_t digiRunNum, reconRunNum, mcRunNum; Short_t pdl_mpv[768]; Float_t pdl_width[768]; Float_t logPoverN_slope[96]; Float_t logPoverN_norm[192]; int range=0; Float_t cde_h= 21.35; Float_t cde_w= 27.35; Float_t cde_l= 326.0; Float_t cde_r= cde_w/cde_h; Float_t x_or= -724.76; Float_t y_or= -728.22; Float_t z_or= 57; TCanvas *canvas= new TCanvas("usefull_canvas", ""); TH2F *th2= new TH2F("usefull_th2", "", 8, 0, 7, 12, 0, 11 ); TObjArray *hist_array; // PDL= 0, CORR_PDL = 1, CORR_PDL_NOMUON=2, LOG_R_OVER_L = 3, GAIN = 4 // MUONS_VS_GAIN=5 //histdefine void RootTreeAnalysis::McHistDefine() { // Purpose and Method: Monte Carlo histogram definitions } void RootTreeAnalysis::DrawHist( TH2F* hist, char* Xname, char* Yname ){ } void RootTreeAnalysis::HistDefine() { // Purpose and Method: Setup Histograms gStyle->SetOptStat(1111); gStyle->SetOptFit(1111); switch (job_id){ case 0: //Pdl char name[]="Pdl00000"; histFile = new TFile(m_histFileName,"RECREATE"); histFile->cd(); hist_array = new TObjArray(768); for (int layer=0;layer <8;layer++) for(int col=0;col<12;col++) for(int fc=0;fc<2;fc++) for(int rg=0;rg<4;rg++){ int id =rg*192+layer*24+col*2+fc; sprintf( name, "Pdl%1d%1d%02d%1d",rg, layer,col, fc); hist_array->AddAt(new TH1F(name, "Pedestal in counts per ADC", 1001, 0, 1000), id); ((TH1F*) hist_array->At(id))->SetXTitle("ADC"); ((TH1F*) hist_array->At(id))->SetYTitle("Counts"); } break; case 1: //Correlated Pedestals char name[]="Pdl_L81_X000X"; histFile = new TFile(m_histFileName,"UPDATE"); Float_t mpv[4], width[4]; TNtuple *tree= (TNtuple *) histFile->Get("Pdl_tree"); if( !tree ){ printf( "ERROR: no Pdl_tree\n Run jobid=0 first\n"); return; }; tree->SetBranchStatus("*", 0); tree->SetBranchStatus("MPV_LEX8", 1); tree->SetBranchStatus("MPV_LEX1", 1); tree->SetBranchStatus("MPV_HEX8", 1); tree->SetBranchStatus("MPV_HEX1", 1); tree->SetBranchStatus("Width_LEX8", 1); tree->SetBranchStatus("Width_LEX1", 1); tree->SetBranchStatus("Width_HEX8", 1); tree->SetBranchStatus("Width_HEX1", 1); tree->SetBranchAddress("MPV_LEX8", mpv); tree->SetBranchAddress("MPV_LEX1", mpv+1); tree->SetBranchAddress("MPV_HEX8", mpv+2); tree->SetBranchAddress("MPV_HEX1", mpv+3); tree->SetBranchAddress("Width_LEX8", width); tree->SetBranchAddress("Width_LEX1", width+1); tree->SetBranchAddress("Width_HEX8", width+2); tree->SetBranchAddress("Width_HEX1", width+3); int axes[4]; histFile->cd(); hist_array = new TObjArray(384); for (int layer=0;layer <8;layer++) for(int col=0;col<12;col++) for(int fc=0;fc<2;fc++){ sprintf( name, "Pdl_L81_X%1d%02d%01d", layer, col, fc); int id= layer*24+col*2+fc; tree->GetEntry(id); axes[0]= mpv[0]-5*width[0]; axes[1]= mpv[0]+10*width[0]; axes[2]= mpv[1]-5*width[1]; axes[3]= mpv[1]+10*width[1]; hist_array->AddAt( new TH2F(name, "Pedestal LEX8 versus LEX1", axes[1]-axes[0], axes[0], axes[1], axes[3]-axes[2], axes[2], axes[3] ), id ); ((TH2F*)hist_array->At(id))->SetXTitle("LEX8 (ADC)"); ((TH2F*)hist_array->At(id))->SetYTitle("LEX1 (ADC)"); sprintf( name, "Pdl_H81_X%1d%02d%01d", layer, col, fc); axes[0]= mpv[2]-5*width[2]; axes[1]= mpv[2]+10*width[2]; axes[2]= mpv[3]-5*width[3]; axes[3]= mpv[3]+10*width[3]; id+=192; hist_array->AddAt( new TH2F(name, "Pedestal HEX8 versus HEX1", axes[1]-axes[0], axes[0], axes[1], axes[3]-axes[2], axes[2], axes[3] ), id ); ((TH2F*)hist_array->At(id))->SetXTitle("HEX8 (ADC)"); ((TH2F*)hist_array->At(id))->SetYTitle("HEX1 (ADC)"); } break; case 2: // Correlated Pedestals, // cut away from muon path(~random trigger) char name[]="CleanPdl_L81_X000X"; histFile = new TFile(m_histFileName,"UPDATE"); Float_t mpv[4], width[4]; TNtuple *tree= (TNtuple *) histFile->Get("Pdl_tree"); if( !tree ){ printf( "ERROR: no Pdl_tree\n Run jobid=0 first\n"); return; }; tree->SetBranchStatus("*", 0); tree->SetBranchStatus("MPV_LEX8", 1); tree->SetBranchStatus("MPV_LEX1", 1); tree->SetBranchStatus("MPV_HEX8", 1); tree->SetBranchStatus("MPV_HEX1", 1); tree->SetBranchStatus("Width_LEX8", 1); tree->SetBranchStatus("Width_LEX1", 1); tree->SetBranchStatus("Width_HEX8", 1); tree->SetBranchStatus("Width_HEX1", 1); tree->SetBranchAddress("MPV_LEX8", mpv); tree->SetBranchAddress("MPV_LEX1", mpv+1); tree->SetBranchAddress("MPV_HEX8", mpv+2); tree->SetBranchAddress("MPV_HEX1", mpv+3); tree->SetBranchAddress("Width_LEX8", width); tree->SetBranchAddress("Width_LEX1", width+1); tree->SetBranchAddress("Width_HEX8", width+2); tree->SetBranchAddress("Width_HEX1", width+3); int axes[4]; histFile->cd(); hist_array = new TObjArray(384); for (int layer=0;layer <8;layer++) for(int col=0;col<12;col++) for(int fc=0;fc<2;fc++){ sprintf( name, "CleanPdl_L81_X%1d%02d%01d", layer, col, fc); int id= layer*24+col*2+fc; tree->GetEntry(id); axes[0]= mpv[0]-5*width[0]; axes[1]= mpv[0]+5*width[0]; axes[2]= mpv[1]-5*width[1]; axes[3]= mpv[1]+5*width[1]; hist_array->AddAt( new TH2F(name, "Pedestal LEX8 versus LEX1, cut on muon path", axes[1]-axes[0], axes[0], axes[1], axes[3]-axes[2], axes[2], axes[3] ), id ); ((TH2F*)hist_array->At(id))->SetXTitle("LEX8 (ADC)"); ((TH2F*)hist_array->At(id))->SetYTitle("LEX1 (ADC)"); sprintf( name, "CleanPdl_H81_X%1d%02d%01d", layer, col, fc); axes[0]= mpv[2]-5*width[2]; axes[1]= mpv[2]+10*width[2]; axes[2]= mpv[3]-5*width[3]; axes[3]= mpv[3]+10*width[3]; id+=192; hist_array->AddAt( new TH2F(name, "Pedestal LEX8 versus LEX1, cut on muon path", axes[1]-axes[0], axes[0], axes[1], axes[3]-axes[2], axes[2], axes[3] ), id ); ((TH2F*)hist_array->At(id))->SetXTitle("LEX8 (ADC)"); ((TH2F*)hist_array->At(id))->SetYTitle("LEX1 (ADC)"); } break; case 3: //logPoverN char name[]="logPoverN0000X"; histFile = new TFile(m_histFileName,"UPDATE"); histFile->cd(); hist_array= new TObjArray(96); //for(int rg=0;range<4;range++) for(int col=0;col<12;col++) for (int layer=0;layer <8;layer++){ int id= layer*12+col; sprintf( name, "logPoverN%1d%1d%02dX", range, layer, col); hist_array->AddAt(new TProfile(name, "Log(#frac{POS}{NEG}) versus position in Cristal", 20, -cde_l*0.6, cde_l*0.6 ), id); ((TProfile*)hist_array->At(id))->SetXTitle("Position"); ((TProfile*)hist_array->At(id))->SetYTitle("Log(#frac{POS}{NEG})"); } break; case 4://Gain char name[]="Gain_00000"; char name2[]="non_lin00000"; histFile = new TFile(m_histFileName,"UPDATE"); histFile->cd(); hist_array = new TObjArray(384); //for(int range=0;range<4;range++) for (int layer=0;layer <8;layer++) for(int col=0;col<12;col++) for(int fc=0;fc<2;fc++){ int id= layer*24+col*2+fc; sprintf( name, "Gain_%1d%1d%02d%1d", range, layer, col, fc); sprintf( name2, "non_lin%1d%1d%02d%1d", range, layer, col, fc); hist_array->AddAt( new TH1F(name, "Muon Signal", 4096, 0, 4095), id ); ((TH1F*)hist_array->At(id))->SetXTitle("Muon (ADC)"); ((TH1F*)hist_array->At(id))->SetYTitle("Counts"); } break; case 5://muons vs position char name[]="muons_vs_pos00000"; histFile = new TFile(m_histFileName,"UPDATE"); histFile->cd(); hist_array = new TObjArray(192); //for(int range=0;range<4;range++) for (int layer=0;layer <8;layer++) for(int col=0;col<12;col++) for(int fc=0;fc<2;fc++){ int id= layer*24+col*2+fc; sprintf( name, "muons_vs_pos%1d%1d%02d%1d", range, layer, col, fc); hist_array->AddAt( new TH2F(name, "Muon Signal versus Position", 800, 0, 799, 40, -cde_l*0.5, cde_l*0.5 ), id); ((TH2F*)hist_array->At(id))->SetXTitle("Muon (ADC)"); ((TH2F*)hist_array->At(id))->SetYTitle("Position"); } break; default: histFile= new TFile( m_histFileName, "UPDATE"); } gROOT->cd(); } //get data void RootTreeAnalysis::Pdl( void ) { CalDigi *caldigi; short int lr, col, fc; Short_t rg; Int_t cde_nb; for( cde_nb=0; caldigi=(CalDigi*) evt->getCalDigiCol()->At(cde_nb); cde_nb++ ){ CalXtalId packedid= caldigi->getPackedId(); lr=packedid.getLayer(); col=packedid.getColumn(); for( fc=0; fc<2; fc++){ for( rg=0; rg<4; rg++){ Short_t value= caldigi->getAdcSelectedRange( rg, fc ); ((TH1F*)hist_array->At(rg*192+lr*24+col*2+fc))->Fill( value ); } } } } void RootTreeAnalysis::Pdl_Corr_NoMuon( void ){ Short_t *pdl; CalDigi *caldigi; short int lr, col, fc, rg, columns[9]={0,0,0,0,0,0,0,0,0}; Int_t cde_nb; Float_t *pdl_sigma; Int_t XtalAdc[4][8][12][2]; for(rg=0; rg<4; rg++) for(lr=0; lr<8; lr++) for(col=0; col<8; col++) for(fc=0; fc<2; fc++) XtalAdc[rg][lr][col][fc]=0; //cut: +- 1 on the sides of +5 sigma pulses for( cde_nb=0; caldigi=(CalDigi*) evt->getCalDigiCol()->At(cde_nb); cde_nb++ ){ CalXtalId packedid= caldigi->getPackedId(); lr= packedid.getLayer(); col= packedid.getColumn(); pdl= pdl_mpv + lr*24 + col*2; pdl_sigma= pdl_width + lr*24 + col*2; for( fc=0; fc<2; fc++ , pdl_sigma++, pdl++ ){ if( XtalAdc[0][lr][col][fc]==-1) continue; XtalAdc[0][lr][col][fc]= caldigi->getAdcSelectedRange( 0, fc); if ( XtalAdc[0][lr][col][0] - *(pdl) > (*pdl_sigma) *5){ //neigbours cut for( rg=(col==0)?0:col-1; rg<=col+1 && rg<12; rg++) XtalAdc[0][lr][rg][0]= -1; //8 hits cut columns[lr]++; columns[8]+=(columns[lr]==1); fc=2; } else for ( rg=1; rg<4; rg++, pdl_sigma+= 190, pdl+= 190 ) XtalAdc[rg][lr][col][fc]= caldigi->getAdcSelectedRange( rg ,fc); } } //8 hits cut if (columns[8]<8) return; //fill hists for(lr=0; lr<8; lr++) for(col=0; col<12; col++){ for(fc=0; fc<2 && XtalAdc[0][lr][col][fc]!=-1; fc++){ ((TH2F*)hist_array->At(lr*24+col*2+fc))->Fill( XtalAdc[0][lr][col][fc], XtalAdc[1][lr][col][fc] ); ((TH2F*)hist_array->At(192+lr*24+col*2+fc))->Fill( XtalAdc[2][lr][col][fc], XtalAdc[3][lr][col][fc] ); } } } void RootTreeAnalysis::Pdl_Correlated( void ){ CalDigi *caldigi; Float_t enem, enep; short int histid, fc, cur_col; Int_t cde_nb; for( cde_nb=0; caldigi=(CalDigi*) evt->getCalDigiCol()->At( cde_nb ); cde_nb++){ CalXtalId packedid= caldigi->getPackedId(); histid= packedid.getLayer()*24+packedid.getColumn()*2; for( short int fc=0; fc<2; fc++ ) for( short int rg=0; rg<4; rg+=2 ) ((TH2F*) hist_array->At(histid+fc+rg*96))->Fill( caldigi->getAdcSelectedRange(rg, fc), caldigi->getAdcSelectedRange(rg+1,fc) ); } } Bool_t RootTreeAnalysis::Make_Cut( Double_t *position, Int_t *XtalAdc, Short_t *col ) { //CalDigi: make cut Float_t *pdl_sigma; Short_t *pdl; CalDigi *caldigi; short int lr, fc, cur_col; Int_t cur_XtalAdc[2]; Short_t nhits=8; Int_t cde_nb; //cut for 1 hit for every layer and no more col[0]=col[1]=col[2]=col[3]=-1; col[4]=col[5]=col[6]=col[7]=-1; for( cde_nb=0; caldigi=(CalDigi*) evt->getCalDigiCol()->At( cde_nb ); cde_nb++){ //get Xtal charateristics CalXtalId packedid= caldigi->getPackedId(); lr= packedid.getLayer(); cur_col= packedid.getColumn(); pdl= pdl_mpv + range*192 + lr*24 + cur_col*2; pdl_sigma= pdl_width + range*192 + lr*24 + cur_col*2; //get cur_XtalAdc cur_XtalAdc[0]= caldigi->getAdcSelectedRange( range, 0) - pdl[0]; cur_XtalAdc[1]= caldigi->getAdcSelectedRange( range, 1) - pdl[1]; //fill XtalAdc and col if ( (cur_XtalAdc[0] < (pdl_sigma[0]*5)) || (cur_XtalAdc[1] < (pdl_sigma[1]*5)) ) continue; if ( col[lr]!=-1 ) return kFALSE;// 1 per layer cut XtalAdc[lr*2]= cur_XtalAdc[0]; XtalAdc[lr*2+1]= cur_XtalAdc[1]; col[lr]= cur_col; nhits--; } if ( nhits!=0 ) return kFALSE;//8 in all cut //Recon: if recon exists get direction given by tracker if (rec){ TkrRecon *tkrRec = rec->getTkrRecon(); if (!tkrRec) return; short int ii; Float_t added[2]; TVector3 tvect3; const TObjArray *vertexCol = tkrRec->getVertexCol(); TkrVertex *vert = (TkrVertex*)vertexCol->At(0); if(!vertexCol->GetEntries()) return kFALSE; tvect3= vert->getDirection(); added[0]= -tvect3.X()/tvect3.Z(); added[1]= -tvect3.Y()/tvect3.Z(); position[16]= -tvect3.CosTheta(); if( position[16]==0 ) return kFALSE; tvect3 = vert->getPosition(); position[0]= tvect3.X() + ( z_or+tvect3.Z())* added[0]; position[1]= tvect3.Y() + ( z_or+tvect3.Z())* added[1]; added[0]*= cde_h; added[1]*= cde_h; for( lr=1; lr<8; lr++){ fc= lr%2; position[ lr*2]= position[ lr*2-1] + added[(fc==0)]; position[ lr*2+1]= position[ lr*2-2] + added[fc]; } return kTRUE; } // otherwise get direction, position from cal Double_t trajectory[2][2]; TGraphErrors *tpos; TF1 *tline= new TF1( "tline", "[0]*x+[1]", 0, 8 ); canvas->cd(); th2->Draw(); //get direction for( fc=0, position[16]=0; fc<2; fc++){ // fill TGraphErrors tpos= new TGraphErrors(); for( lr=0; lr<8; lr+=2 ){ tpos->SetPoint( lr/2, lr, col[lr+fc]); tpos->SetPointError( lr/2, 2, 2*cde_r); } // get trajectory parameters tpos->Draw("*"); tpos->Fit( tline, "WNQ" ); trajectory[1-fc][0]= tline->GetParameter(0); trajectory[1-fc][1]= tline->GetParameter(1); position[16]+= (trajectory[1-fc][0])**2; tpos->~TGraphErrors(); } position[16]= 1/sqrt(1 + cde_r**2 * position[16] );// position[16]=cos(Theta) //get position position[0]= (trajectory[0][1]-5.5)*cde_w/12; position[1]= (trajectory[1][1]-5.5)*cde_w/12; if( position[0]<-cde_l/2 || position[0]>cde_l/2 ) trajectory[1][0]=-6; if( position[1]<-cde_l/2 || position[1]>cde_l/2) trajectory[0][0]=-6; for( lr=1; lr<8; lr++ ){ position[lr*2]= position[lr*2-1] + trajectory[lr%2][0]*cde_w/12; position[lr*2+1]= position[(lr-1)*2] + trajectory[lr%2==0][0]*cde_w/12; if( position[lr*2+1]<-cde_l/2 || position[lr*2]<-cde_l/2 ) break; if( position[lr*2+1]>cde_l/2 || position[lr*2]>cde_l/2 ) break; } tline->~TF1(); canvas->Clear("D"); caldigi=0; return (lr==8); // lr==8 if and only if positions have been correctly rebuilt } void RootTreeAnalysis::Make_Hist( Double_t *position, Int_t *XtalAdc, Short_t *col ){ short int lr, fc; int histid; Float_t Xtalval[2], value_raw; Float_t slcoef, value; //fill hists histFile->cd(); switch( job_id ){ case 3://fill logPoverN for( lr=0; lr<8; lr++){ value= XtalAdc[2*lr]; value/= XtalAdc[2*lr+1]; value= log(value); histid= lr*12 + col[lr]; ((TH2F*) hist_array->At(histid))->Fill( position[2*lr], value ); } break;; case 4://fill muon hist for( lr=0; lr<8; lr++ ){ histid= lr*12 + col[lr]; slcoef = logPoverN_slope[histid]*(position[2*lr]-5.5)/2; slcoef *= position[16]; //position[16]= cos(theta_direction) for( fc=0, histid *= 2; fc<2; fc++, histid++ ){ value= XtalAdc[lr*2+fc]; value+= (fc==0)? -value*slcoef : value*slcoef; ((TH1F*) hist_array->At(histid))->Fill( value ); } } break; case 5://fill muons vs position if ( (position[16]<0.98) && (position[16]>-0.98) ) return; for( lr=0; lr<8; lr++ ){ histid= lr*12 + col[lr]; for( fc=0, histid *= 2; fc<2; fc++, histid++){ value= XtalAdc[lr*2+fc]*position[16]; ((TH2F*) hist_array->At( histid ))->Fill( value, position[2*lr] ); } } break; } gROOT->cd(); } //treat data void RootTreeAnalysis::FitPdl( void ){ float value, mean, rms; Float_t results_values[12]; short int ii, col, lr, fc, rg; int length, iii; char name[]="Pdl00000"; TH1F* th; TF1* gaus; histFile = new TFile(m_histFileName, "UPDATE"); histFile->cd(); TNtuple *results= new TNtuple("Pdl_tree", "Uncorrelated pedestals", "cde_id:MPV_LEX8:MPV_LEX1:MPV_HEX8:MPV_HEX1:Width_LEX8:Width_LEX1:Width_HEX8:Width_HEX1"); gROOT->cd(); for( lr=0; lr<8; lr++ ) for( col=0; col<12; col++ ) for( fc=0; fc<2; fc++ ){ results_values[0]= lr*1000 + col*10 + fc; for( rg=0; rg<4; rg++ ){ //get th1 sprintf( name, "Pdl%1d%1d%02d%1d", rg, lr, col, fc); th= (TH1F*) (TH1F*)histFile->Get( name ); if (!th){ printf("ERROR NO TH\n cde_id:\n"); printf("layer: %d, column: %d, face: %d, range: %d\n", lr, col, fc, rg); return; } //fit th1 for ( ii=0; ii<3; ii++){ mean= th->GetMean(); rms= th->GetRMS(); th->SetAxisRange(mean-2.5*rms, mean+2.5*rms); } th->Fit("gaus", "", "", th->GetMean()-2.5*th->GetRMS(), th->GetMean()+ 2.5*th->GetRMS() ); gaus= (TF1*)(th->GetFunction("gaus")); results_values[rg+1]= gaus->GetParameter(1); results_values[rg+5]=gaus->GetParameter(2); } results->Fill(results_values); } histFile->Write( "", TObject::kOverwrite ); histFile->Close(); gROOT->cd(); } void RootTreeAnalysis::FitCorrPdl( char* option ){ int id; TF1 *fits= new TF1( "line_fit", "[0]+[1]*x", 0, 800); TProfile *axes; Double_t fit_ranges[4]; char name[]="CleanPdl_H81_X0000"; Float_t results[17]; TH2F* pdl; TF2 *gauss= new TF2("gauss", "[0]*exp( -0.5/([1]*[1])*((x-[4])*cos([3])+(y-[5])*sin([3]))**2 ) * exp( -0.5/([2]*[2])*((y-[5])*cos([3])-(x-[4])*sin([3]))**2)" ); gauss->SetParName( 0, "area" ); gauss->SetParName( 1, "sigma_X" ); gauss->SetParName( 2, "sigma_Y" ); gauss->SetParName( 3, "angle" ); gauss->SetParName( 4, "X_MPV" ); gauss->SetParName( 5, "Y_MPV" ); TH1D *proj; histFile= new TFile( m_histFileName, "UPDATE"); histFile->cd(); TNtuple *tree= new TNtuple("Pdl_tree", "Correlated Pedestal Characteristics", "cde_id:MPV_LEX8:MPV_LEX1:MPV_HEX8:MPV_HEX1:Width_LEX8:Width_LEX1:Width_HEX8:Width_HEX1:Std_Dev_LEX:Std_Dev_HEX:Orth_Dev_LEX:Orth_Dev_HEX:angle_LEX:angle_HEX:Gain_LEX:Gain_HEX"); gROOT->cd(); gStyle->SetOptFit(1111); for( short int lr=0; lr<8; lr++ ) for( short int col=0; col<12; col++ ) for( short int fc=0; fc<2; fc++ ){ results[0]= lr*1000+col*10+fc; for( short int rg=0; rg<4; rg++ ){ sprintf( name, "%sPdl_%c81_X%01d%02d%01d", option, (Char_t ) (76-4*rg), lr, col, fc ); pdl= (TH2F*) histFile->Get(name); if ( !pdl ) continue; axes= pdl->ProfileX( "prof", -1, -1); for( int jj=0; jj<3; jj++ ){ fit_ranges[0]= pdl->GetMean(2)-pdl->GetRMS(2)*3; fit_ranges[1]= pdl->GetMean(2)+pdl->GetRMS(2)*3; fit_ranges[2]= pdl->GetMean(1)-pdl->GetRMS(1)*3; fit_ranges[3]= pdl->GetMean(1)+pdl->GetRMS(1)*3; pdl->GetXaxis()->SetRangeUser( fit_ranges[2], fit_ranges[3] ); pdl->GetYaxis()->SetRangeUser( fit_ranges[0], fit_ranges[1] ); } fits->SetRange( fit_ranges[2], fit_ranges[3] ); axes->Fit( fits, "QR" ); //gausss gauss->SetParameter( "area", 1.5*pdl->Integral( fit_ranges[2], fit_ranges[3], fit_ranges[0], fit_ranges[1]) ); gauss->SetParameter( "sigma_X", pdl->GetRMS(1) ); gauss->SetParameter( "sigma_Y", pdl->GetRMS(2) ); gauss->SetParameter( "angle", atan(fits->GetParameter(1)) ); gauss->SetParameter( "X_MPV", pdl->GetMean(1) ); gauss->SetParameter( "Y_MPV", pdl->GetMean(2) ); gauss->SetRange( fit_ranges[2], fit_ranges[3], fit_ranges[0], fit_ranges[1] ); gauss->SetParLimits( 0, 1, pdl->GetEntries() ); gauss->SetParLimits( 1, gauss->GetParameter("sigma_X")/20, 3*(fit_ranges[3]-fit_ranges[2]) ); gauss->SetParLimits( 2, gauss->GetParameter("sigma_Y")/20, 3*(fit_ranges[1]-fit_ranges[0]) ); gauss->SetParLimits( 3, -acos(-1), acos(-1) ); gauss->SetParLimits( 4, fit_ranges[2], fit_ranges[3] ); gauss->SetParLimits( 5, fit_ranges[0], fit_ranges[1] ); pdl->Fit( gauss, "" ); //save results results[1+2*rg]= gauss->GetParameter("X_MPV"); results[2+2*rg]= gauss->GetParameter("Y_MPV"); results[9+rg]= gauss->GetParameter("sigma_X"); results[11+rg]= gauss->GetParameter("sigma_Y"); results[13+rg]= gauss->GetParameter("angle"); proj= pdl->ProjectionX("proj", -1, -1); proj->SetAxisRange(fit_ranges[2], fit_ranges[3]); proj->Fit("gaus", "Q"); results[5+2*rg]= ((TF1*) proj->GetFunction("gaus"))->GetParameter(2); proj->~TH1D(); proj= pdl->ProjectionY("proj", -1, -1); proj->SetAxisRange(fit_ranges[0], fit_ranges[1]); proj->Fit("gaus", "Q"); results[6+2*rg]= ((TF1*) proj->GetFunction("gaus"))->GetParameter(2); proj->~TH1D(); fits->SetRange( fit_ranges[3], 800 ); axes->Fit( fits, "QR" ); results[15+rg]= fits->GetParameter(1); if( results[9+rg]<results[11+rg]){ Float_t val= results[11+rg]; results[11+rg]= results[9+rg]; results[9+rg]= val; } for( ; results[13+rg]<0; results[13+rg]+=acos(-1)/2 ); for( ; results[13+rg]>acos(-1)/2; results[13+rg]-=acos(-1)/2 ); if( results[9+rg]==0 ) results[11+rg]= results[9+rg]= -1000; axes->~TProfile(); } tree->Fill(results); } histFile->Write("", TObject::kOverwrite ); histFile->Close(); return; } void RootTreeAnalysis::FitLogPoverN( void ){ int histid; short int lr, col; TProfile* tp; TF1 *func; Double_t logratio, slope; Float_t results_values[4]; char name[200]; histFile= new TFile( m_histFileName, "UPDATE" ); sprintf( name, "LogPoverN_tree" ); histFile->cd(); TNtuple *results= new TNtuple( name, "fit values of Log(Left/Rigth)", "cde_id:norm_POS:norm_NEG:slope"); gROOT->cd(); for( lr=0; lr<8; lr++) for( col=0;col<12;col++){ //get tprofile histid = lr*12+col; sprintf( name, "logPoverN%1d%1d%02dX", range, lr, col); tp= (TProfile*) histFile->Get( name ); if (!tp){ printf("ERROR NO TProfile\n cde_id:\n"); printf("layer: %d, column: %d, face: %d, range: %d\n", lr, col, fc, rg); return; } //fit tprofile tp->SetAxisRange(-cde_l*0.3,cde_l*0.3); tp->Fit("pol1","Q"); func= (TF1*) tp->GetFunction("pol1"); logratio= func->GetParameter( 0 ); slope= func->GetParameter( 1 ); //write results results_values[0]= lr*1000 + col*10; results_values[1]= exp(-logratio/2); results_values[2]= exp(logratio/2); results_values[3]= slope; results->Fill( results_values ); tp->SetAxisRange(-7, 7); } histFile->Write( "", TObject::kOverwrite ); gROOT->cd(); histFile->Close(); } void RootTreeAnalysis::FitGain( int rebinning ){ int histid; short int lr, col, fc, ii, ll; TH1 *th1; TF1 *landau, *convoluted; Double_t constant, sigma, mpv, range_val[2]; Float_t results_values[3]; char name[]="Gain_00000"; char newname[]="Gain_00000_fitted"; canvas->cd(); histFile= new TFile( m_histFileName, "UPDATE" ); histFile->cd(); hist_array= new TObjArray(193); hist_array->AddAt( new TNtuple("Gain_tree", "pedestal substracted, attenuation and path correct muon signal in ADC units", "cde_id:MPV_LEX8:Width_LEX8"), 0); gROOT->cd(); for( lr=0; lr<8; lr++) for( col=0;col<12;col++) for( fc=0;fc<2;fc++){ //get th1 histid = lr*12+col; sprintf( name, "Gain_%1d%1d%02d%1d", range, lr, col, fc); sprintf( newname, "Gain_%1d%1d%02d%1d_fitted", range, lr, col, fc); hist_array->AddAt((TH1F*) ((TH1F*) histFile->Get( name ))->Clone( newname ), lr*24+col*2+fc+1); th1= (TH1F*) hist_array->At( lr*24+col*2+fc+1); if (!th1){ printf("ERROR NO TH1\n cde_id:\n"); printf("layer: %d, column: %d, face: %d, range: %d\n", lr, col, fc, rg); return; } //fit th1 th1->Rebin( rebinning ); for( ll=0; ll<5; ll++ ) th1->SetAxisRange( th1->GetMean() - 2* th1->GetRMS(), th1->GetMean() + 3* th1->GetRMS() ); range_val[0]= th1->GetMean() - 2* th1->GetRMS(); range_val[1]= th1->GetMean() + 3* th1->GetRMS(); printf("Landau fit: \n");; // fit landau // set tf1 names sprintf( name, "muons_ldau%1d%1d%02d%1d", range, lr, col, fc); landau= new TF1( name, "landau", th1->GetMean()-2*th1->GetRMS(), th1->GetMean()+3*th1->GetRMS()); landau->SetParNames("Constant", "MPV", "Sigma"); // set tf1 start values th1->SetAxisRange( th1->GetMean()-th1->GetRMS()/2, th1->GetMean()); mpv= th1->GetMean(); constant= th1->GetEntries(); th1->SetAxisRange( 0, 4095 ); sigma= th1->GetRMS()/5; landau->SetParameter(0, constant ); landau->SetParameter( 1, mpv ); landau->SetParameter( 2, sigma ); landau->SetRange( range_val[0], range_val[1] ); // set tf1 parameter limits landau->SetParLimits( 2, sigma/10, range_val[1]-range_val[0] ); landau->SetParLimits( 1, range_val[0], range_val[1] ); landau->SetParLimits( 0, constant/100, constant ); // fit th1->Fit( landau, "R" ); landau= (TF1*) th1->GetFunction( name ); mpv= landau->GetParameter(1); sigma= landau->GetParameter(2); constant= 50* landau->GetParameter(0); printf("Gauss-convoluted Landau fit: \n");; // fit convoluted sprintf( name, "muons_LGau%1d%1d%02d%1d", range, lr, col, fc); // set tf1 names convoluted= new TF1( name, langaufun, th1->GetMean()-2*th1->GetRMS(), th1->GetMean()+3*th1->GetRMS(), 4); convoluted->SetParNames("Width","MPV","Area","GSigma"); convoluted->SetLineColor(2); // set tf1 start values convoluted->SetParameter( 0, sigma); convoluted->SetParameter( 1, mpv); convoluted->SetParameter( 2, constant ); convoluted->SetParameter( 3, 70 ); convoluted->SetRange( range_val[0], range_val[1] ); // set tf1 parameter limits convoluted->SetParLimits( 0, 1, 50 ); convoluted->SetParLimits( 1, range_val[0], range_val[1] ); convoluted->SetParLimits( 2, constant/5, constant *5 ); convoluted->SetParLimits( 3, 20, 150 ); // fit th1->Fit( convoluted,"R+"); convoluted= (TF1*) th1->GetFunction( name ); results_values[0]= lr*1000 + col*10 + fc; results_values[1]= (Float_t) get_MPV( convoluted, th1->GetMean()-th1->GetRMS()/2, th1->GetMean()+th1->GetRMS()/2, 0.000001 ); results_values[2]= th1->GetRMS(); ((TNtuple*) hist_array->At(0))->Fill( results_values ); } histFile->Write( "", TObject::kOverwrite ); gROOT->cd(); histFile->Close(); } void RootTreeAnalysis::FitTapering( void ){ short int lr, col, fc; char name[]="muons_vs_pos00000"; Double_t results[3]; TH1D *proj; TH2F *muons; TProfile *gr; TF1 *line= new TF1("line", "[0]+[1]/40*x", 0, 40 ); histFile= new TFile( m_histFileName, "UPDATE"); try_file->cd(); TProfile *pr[192]; TNtuple *tree= new TNtuple("Taper_tree", "", "cde_id:slope:norm"); for( lr=0; lr<8; lr++ ) for( col=0; col<12; col++ ) for( fc=0; fc<2; fc++ ){ sprintf( name, "taper0%01d%02d%01d", lr, col, fc); pr[xx*192+lr*24+col*2+fc]= new TProfile( name, name, 15, 0, 1 ); } gROOT->cd(); for( lr=0; lr<8; lr++ ) for( col=0; col<12; col++ ) for( fc=0; fc<2; fc++ ){ results[0]= lr*1000+ col*10+fc; sprintf( name, "taper0%01d%02d%01d", lr, col, fc); muons= (TH2F*) rec_file->Get( name ); gr= pr[lr*24+col*2+fc]; for( xx=0; xx<40; xx++ ){ proj= muons->ProjectionX( "proj", xx, xx ); if ( proj->GetEntries()<5 ) gr->Fill(xx/40., proj->GetMaximumBin()); else{ proj->Fit("landau", "Q"); gr->Fill(xx/40., ((TF1*) proj->GetFunction("landau"))->GetParameter(1)); } proj->~TH1D(); } gr->Fit("expo", "", "", .2, .8 ); results[1]= ((TF1*) gr->GetFunction("expo"))->GetParameter(0); results[2]= ((TF1*) gr->GetFunction("expo"))->GetParameter(1); tree->Fill(results); } histFile->Write("", TObject::kOverwrite ); histFile->Close(); } Double_t RootTreeAnalysis::get_MPV( TF1* function, Double_t min, Double_t max, Double_t precision ){ Double_t steps, step_interval, max_range, min_range, value, old_value; //init variables step_interval= (max_range -steps)/10; max_range= max; min_range= min; if (min_range<0) min_range=0; old_value= function->Eval( min_range ); //get peak for( step_interval= (max-min)/3; step_interval > precision/2; ){ old_value= function->Eval( min_range ); for( steps= min_range+step_interval; steps<= max_range+1; steps+= step_interval ){ value= function->Eval( steps ); if ( old_value>=value ) { max_range= steps; if (min_range < steps-2*step_interval) min_range= steps-2*step_interval; step_interval= (max_range-min_range)/3; break; } old_value= value; } } return (old_value>value)? steps-step_interval: steps; } Double_t langaufun(Double_t* x, Double_t *par){ //Fit parameters: //par[0]=Width (scale) parameter of Landau density //par[1]=Most Probable (MP, location) parameter of Landau density //par[2]=Total area (integral -inf to inf, normalization constant) //par[3]=Width (sigma) of convoluted Gaussian function // //In the Landau distribution (represented by the CERNLIB approximation), //the maximum is located at x=-0.22278298 with the location parameter=0. //This shift is corrected within this function, so that the actual //maximum is identical to the MP parameter. // variables // Numeric constants Double_t invsq2pi = 0.3989422804014; // (2 pi)^(-1/2) Double_t mpshift = -0.22278298; // Landau maximum location // Control constants Double_t np = 100.0; // number of convolution steps Double_t sc = 5.0; // convolution extends to +-sc Gaussian sigmas Double_t xx; Double_t mpc; Double_t fland; Double_t sum = 0.0; Double_t xlow,xupp; Double_t step; Double_t i; // MP shift correction mpc = par[1] - mpshift * par[0]; // Range of convolution integral xlow =*x - sc * par[3]; xupp = *x + sc * par[3]; step = (xupp-xlow) / np; // Convolution integral of Landau and Gaussian by sum for(i=1.0; i<=np/2; i++) { xx = xlow + (i-.5) * step; fland = TMath::Landau(xx, mpc,par[0]) / par[0]; sum += fland * TMath::Gaus(*x,xx,par[3]); xx = xupp - (i-.5) * step; fland = TMath::Landau(xx,mpc,par[0]) / par[0]; sum += fland * TMath::Gaus(*x,xx,par[3]); } return (par[2] * step * sum * invsq2pi / par[3]); } //retrieve data Bool_t RootTreeAnalysis::getPdl( Short_t *Pdlmpv, Float_t *Pdlsigma ){ TNtuple *tree= (TNtuple*) histFile->Get("Pdl_tree"); if (!tree){ printf("ERROR: no Pdl_tree in file:\n\t%s\n", m_histFileName ); return kFALSE; } Float_t mpv[4], width[4], cde_id; Short_t lr, col, rg, entry; Int_t fc; tree->SetBranchStatus("*", 0); tree->SetBranchStatus("MPV_LEX8", 1); tree->SetBranchStatus("MPV_LEX1", 1); tree->SetBranchStatus("MPV_HEX8", 1); tree->SetBranchStatus("MPV_HEX1", 1); tree->SetBranchStatus("Width_LEX8", 1); tree->SetBranchStatus("Width_LEX1", 1); tree->SetBranchStatus("Width_HEX8", 1); tree->SetBranchStatus("Width_HEX1", 1); tree->SetBranchStatus("cde_id", 1); tree->SetBranchAddress("MPV_LEX8", mpv); tree->SetBranchAddress("MPV_LEX1", mpv+1); tree->SetBranchAddress("MPV_HEX8", mpv+2); tree->SetBranchAddress("MPV_HEX1", mpv+3); tree->SetBranchAddress("Width_LEX8", width); tree->SetBranchAddress("Width_LEX1", width+1); tree->SetBranchAddress("Width_HEX8", width+2); tree->SetBranchAddress("Width_HEX1", width+3); tree->SetBranchAddress("cde_id", &cde_id); for ( entry=0; tree->GetEntry( entry ); entry++){ fc= cde_id; lr= fc/1000; fc-= lr*1000; col= fc/10; fc-= col*10; for(rg = 0; rg<4; rg++ ){ *(Pdlmpv + rg*192 + lr*24 + col*2 + fc)= ( Short_t )mpv[rg]; *(Pdlsigma + rg*192 + lr*24 + col*2 + fc )= width[rg]; } } return kTRUE; } Bool_t RootTreeAnalysis::getLogPoverN( Float_t *logPoverN_s ){ Float_t norm_POS, norm_NEG, slope, cde_id; Short_t lr, rg, entry; Int_t col; TNtuple *tree= (TNtuple*) histFile->Get("Taper_tree"); Bool_t taper=(tree==0); if (taper){ printf("no Taper_tree in file:\n\t%s\n", m_histFileName ); tree= (TNtuple*) histFile->Get("LogPoverN_tree"); if (!tree){ printf("ERROR: no LogPoverN_tree in file:\n\t%s\n", m_histFileName ); return kFALSE; } } tree->SetBranchStatus( "*", 0); tree->SetBranchStatus( "slope", 1); tree->SetBranchAddress( "slope", &slope ); tree->SetBranchStatus("cde_id", 1); tree->SetBranchAddress("cde_id", &cde_id); for( entry=0; tree->GetEntry(entry); entry++){ col= cde_id; rg= col/10000; col-= rg*10000; lr= col/1000; col-= lr*1000; col/= 10; logPoverN_s[rg*192 + lr*24 + col*2+0]= slope; if( !taper ) tree->GetEntry(entry); logPoverN_s[rg*192 + lr*24 + col*2+1]= slope; } return kTRUE; } //write to xml void RootTreeAnalysis::PdlToXml( char* filename ){ std::ofstream xml( filename ); histFile= new TFile( m_histFileName ); Float_t mpv[4], width[4]; TNtuple *tree; tree= (TNtuple*) histFile->Get("Pdl_tree"); if (!(tree)){ printf("ERROR:NO PEDESTALS TREE\n"); return; } tree->SetBranchStatus("*", 0); tree->SetBranchStatus("MPV_LEX8", 1); tree->SetBranchStatus("MPV_LEX1", 1); tree->SetBranchStatus("MPV_HEX8", 1); tree->SetBranchStatus("MPV_HEX1", 1); tree->SetBranchStatus("Width_LEX8", 1); tree->SetBranchStatus("Width_LEX1", 1); tree->SetBranchStatus("Width_HEX8", 1); tree->SetBranchStatus("Width_HEX1", 1); tree->SetBranchAddress("MPV_LEX8", mpv); tree->SetBranchAddress("MPV_LEX1", mpv+1); tree->SetBranchAddress("MPV_HEX8", mpv+2); tree->SetBranchAddress("MPV_HEX1", mpv+3); tree->SetBranchAddress("Width_LEX8", width); tree->SetBranchAddress("Width_LEX1", width+1); tree->SetBranchAddress("Width_HEX8", width+2); tree->SetBranchAddress("Width_HEX1", width+3); short int rg, layer, column, face; //header xml<<"<?xml version=\"1.0\" ?>"<<endl<<endl; xml<<"<!-- $Header: my Pdl-->"<<endl<<endl; xml<<"<!-- Approximately real CAL ped XML file for EM, according to calCalib.dtd -->"<<endl<<endl; xml<<"<!DOCTYPE calCalib SYSTEM \"../calCalib_v3.dtd\" [] >"<<endl<<endl; //calCalib xml<<"<calCalib>"<<endl; xml<<"\t<generic\tinstrument=\"EM\" timestamp=\"2003-11-2-12:56\""<<endl; xml<<"\t\t\t\tcalibType=\"CAL_Ped\" fmtVersion=\"v2r0\">"<<endl<<endl; xml<<"\t\t<inputSample\tstartTime=\"2003-2-21-05:49:12\" stopTime=\"2003-2-24-07:07:02\""<<endl; xml<<"\t\t\t\t\ttriggers=\"random\" mode=\"normal\" source=\"stuff\" >"<<endl<<endl; xml<<"\t\tTimes are start and stop time of calibration run."<<endl; xml<<"\t\tOther attributes are just made up for code testing."<<endl; xml<<"\t\t</inputSample>"<<endl; xml<<"\t</generic>"<<endl<<endl<<endl; xml<<"<!-- EM instrument: 8 layers, 12 columns -->"<<endl<<endl; xml<<"\t<dimension nRow=\"1\" nCol=\"1\" nLayer=\"8\" nXtal=\"12\" nFace=\"2\" />"<<endl<<endl; xml<<"\t<tower iRow=\"0\" iCol=\"0\">"<<endl; for( layer=0; layer<8; layer++ ){ xml<<"\t\t<layer iLayer=\""<<layer<<"\">"<<endl; for( column=0; column<12; column++ ){ xml<<"\t\t\t<xtal iXtal=\""<<column<<"\">"<<endl; for( face=1; face>-1; face-- ){ xml<<"\t\t\t\t<face end=\""<<((face==0)?"POS":"NEG")<<"\">"<<endl; tree->GetEntry( layer*24 + column*2 + face ); for( rg=0; rg<4; rg++ ){ xml<<"\t\t\t\t\t<calPed avg=\""<<mpv[rg] <<"\" sig=\""<<width<<"\" range=\"" <<((rg<2)?"L":"H")<<"EX"<<((rg%2==0)?"8":"1")<<"\" />"<<endl; } xml<<"\t\t\t\t</face>"<<endl; } xml<<"\t\t\t</xtal>"<<endl; } xml<<"\t\t</layer>"<<endl; } //end file xml<<"\t</tower>"<<endl; xml<<"</calCalib>"<<endl; tree->SetBranchStatus("*", 1); histFile->Close(); } void RootTreeAnalysis::CorrelatedPdlToXml( char* filename ){ std::ofstream xml( filename ); histFile= new TFile( m_histFileName ); short int diode, layer, column, face; Float_t mpv[4], sigma[2], angle[2], ratio[2]; TNtuple *tree; tree= (TNtuple*) histFile->Get("Pdl_tree"); if (!(tree)){ printf("ERROR:NO PEDESTALS TREE\n"); return; } tree->SetBranchAddress("*", 0); tree->SetBranchAddress("MPV_LEX8", 1); tree->SetBranchAddress("MPV_LEX1", 1); tree->SetBranchAddress("MPV_HEX8", 1); tree->SetBranchAddress("MPV_HEX1", 1); tree->SetBranchAddress("angle_LEX", 1); tree->SetBranchAddress("angle_HEX", 1); tree->SetBranchAddress("Std_Dev_LEX", 1); tree->SetBranchAddress("Std_Dev_HEX", 1); tree->SetBranchAddress("Orth_Dev_LEX", 1); tree->SetBranchAddress("Orth_Dev_HEX", 1); tree->SetBranchAddress("MPV_LEX8", mpv); tree->SetBranchAddress("MPV_LEX1", mpv+1); tree->SetBranchAddress("MPV_HEX8", mpv+2); tree->SetBranchAddress("MPV_HEX1", mpv+3); tree->SetBranchAddress("angle_LEX", angle); tree->SetBranchAddress("angle_HEX", angle+1); tree->SetBranchAddress("Std_Dev_LEX", sigma); tree->SetBranchAddress("Std_Dev_HEX", sigma+1); tree->SetBranchAddress("Orth_Dev_LEX", ratio); tree->SetBranchAddress("Orth_Dev_HEX", ratio+1); xml<<"<?xml version=\"1.0\" ?>"<<endl<<endl <<"<!-- $Header: my Pdl-->"<<endl<<endl <<"<!-- Approximately real CAL ped XML file for EM," <<"according to calCalib.dtd -->"<<endl<<endl <<"<!DOCTYPE calCalib SYSTEM \"../calCalib_v3.dtd\" [] >"<<endl<<endl; xml<<"<calCalib>"<<endl <<"\t<generic\tinstrument=\"EM\" timestamp=\"2003-11-2-12:56\""<<endl <<"\t\t\t\tcalibType=\"CAL_Ped\" fmtVersion=\"v2r0\">"<<endl<<endl <<"\t\t<inputSample\tstartTime=\"2003-2-21-05:49:12\" " <<"stopTime=\"2003-2-24-07:07:02\""<<endl <<"\t\t\t\t\ttriggers=\"random\" mode=\"normal\" source=\"stuff\" >"<<endl <<endl; xml<<"\t\tTimes are start and stop time of calibration run."<<endl <<"\t\tOther attributes are just made up for code testing."<<endl <<"\t\t</inputSample>"<<endl <<"\t</generic>"<<endl<<endl<<endl; xml<<"<!-- EM instrument: 8 layers, 12 columns -->"<<endl<<endl <<"\t<dimension nRow=\"1\" nCol=\"1\" nLayer=\"8\" " <<"nXtal=\"12\" nFace=\"2\" />"<<endl<<endl <<"\t<tower iRow=\"0\" iCol=\"0\">"<<endl; for( layer=0; layer<8; layer++ ){ xml<<"\t\t<layer iLayer=\""<<layer<<"\">"<<endl; for( column=0; column<12; column++ ){ xml<<"\t\t\t<xtal iXtal=\""<<column<<"\">"<<endl; for( face=1; face>-1; face-- ){ xml<<"\t\t\t\t<face end=\""<<((face==0)?"POS":"NEG")<<"\">"<<endl; tree->GetEntry( layer*24 + column*2 + face ); for( diode=0; diode<2; diode++ ){ xml<<"\t\t\t\t\t<calPed avg=\""<<mpv[2*diode] <<"\" sig=\""<<sigma[diode] <<"\" cos=\""<<cos(angle[diode]) <<"\" range=\""<<((diode==1)?"H":"L")<<"EX8\" />"<<endl <<"\t\t\t\t\t<calPed avg=\""<<mpv[2*diode+1] <<"\" sig=\""<<ratio[diode] <<"\" cos=\""<<-1000 <<"\" range=\""<<((diode)?"H":"L")<<"EX1\" />"<<endl; } xml<<"\t\t\t\t</face>"<<endl; } xml<<"\t\t\t</xtal>"<<endl; } xml<<"\t\t</layer>"<<endl; } xml<<"\t</tower>"<<endl; xml<<"</calCalib>"<<endl; xml.close(); tree->SetBranchAddress("*", 0); histFile->Close(); } void RootTreeAnalysis::GainToXml( char* filename ){ Float_t Nb_MeV= 12.5; std::ofstream xml( filename ); histFile= new TFile( m_histFileName ); Float_t peak, gain, rms, mgain[2], norm; TNtuple *tree_muons= (TNtuple*) histFile->Get("Gain_tree"); if (!tree_muons){ printf("ERROR:No Gain_tree TREE\n"); return; } tree_muons->SetBranchStatus("*", 0); tree_muons->SetBranchStatus("MPV_LEX8", 1); tree_muons->SetBranchAddress("MPV_LEX8", &peak); tree_muons->SetBranchStatus("Width_LEX8", 1); tree_muons->SetBranchAddress("Width_LEX8", &rms); TNtuple *tree_pdl= (TNtuple*) histFile->Get("Pdl_tree"); if (!tree_pdl){ printf("ERROR:NO Pdl_tree TREE\n"); return; } tree_pdl->SetBranchStatus("*", 0); tree_pdl->SetBranchStatus("Gain_LEX", 1); tree_pdl->SetBranchAddress("Gain_LEX", mgain); tree_pdl->SetBranchStatus("Gain_HEX", 1); tree_pdl->SetBranchAddress("Gain_HEX", mgain+1); TNtuple *tree_att= (TNtuple*) histFile->Get("Taper_tree"); Bool_t taper= tree_att!=0; if ( taper ){ tree_att= (TNtuple*) histFile->Get("LogPoverN_tree"); if (!tree_att){ printf("ERROR:NO LogPoverN_tree or Taper_tree TREE\n"); return; } tree_att->SetBranchStatus("*", 0); tree_att->SetBranchStatus("norm_POS", 1); tree_att->SetBranchAddress("norm_POS", &norm ); printf("ERROR:NO LogPoverN_tree TREE\n"); } else { tree_att->SetBranchStatus("*", 0); tree_att->SetBranchStatus("norm", 1); tree_att->SetBranchAddress("norm", &norm ); } short int rg, layer, column, face; //header xml<<"<?xml version=\"1.0\" ?>"<<endl<<endl; xml<<"<!-- $Header: my Pdl-->"<<endl<<endl; xml<<"<!-- Approximately real CAL gain XML file for EM, according to calCalibv3.dtd -->"<<endl<<endl; xml<<"<!DOCTYPE calCalib SYSTEM \"../calCalib_v3.dtd\" [] >"<<endl<<endl; //calCalib xml<<"<calCalib>"<<endl; xml<<"\t<generic\tinstrument=\"EM\" timestamp=\"2003-11-2-12:56\""<<endl; xml<<"\t\t\t\tcalibType=\"CAL_ElecGain\" fmtVersion=\"v2r0\">"<<endl<<endl; xml<<"\t\t<inputSample\tstartTime=\"2003-2-21-05:49:12\" stopTime=\"2003-2-24-07:07:02\""<<endl; xml<<"\t\t\t\t\ttriggers=\"random\" mode=\"normal\" source=\"stuff\" >"<<endl<<endl; xml<<"\t\tTimes are start and stop time of calibration run."<<endl; xml<<"\t\tOther attributes are just made up for code testing."<<endl; xml<<"\t\t</inputSample>"<<endl; xml<<"\t</generic>"<<endl<<endl<<endl; xml<<"<!-- EM instrument: 8 layers, 12 columns -->"<<endl<<endl; xml<<"\t<dimension nRow=\"1\" nCol=\"1\" nLayer=\"8\" nXtal=\"12\" nFace=\"2\" />"<<endl<<endl; xml<<"\t<tower iRow=\"0\" iCol=\"0\">"<<endl; for( layer=0; layer<8; layer++ ){ xml<<"\t\t<layer iLayer=\""<<layer<<"\">"<<endl; for( column=0; column<12; column++ ){ xml<<"\t\t\t<xtal iXtal=\""<<column<<"\">"<<endl; for( face=1; face>-1; face-- ){ xml<<"\t\t\t\t<face end=\""<<((face==0)?"POS":"NEG")<<"\">"<<endl; tree_pdl->GetEntry( layer*24 + column*2 + face ); tree_muons->GetEntry( layer*24 + column*2 + face ); if( !taper ) tree_att->GetEntry( layer*24 + column*2 + face ); for( rg=0; rg<4; rg++ ){ if( taper ) tree_att->GetEntry( 192*rg+layer*24 + column*2 + face ); switch( rg ){ case 0: gain= peak/Nb_MeV; if( taper || gain ) gain *= norm; else gain/= norm; rms/= peak; break; case 2: gain /= 8; rms /= 8; break; default: gain *= mgain[rg/2]; rms *= mgain[rg/2]; break; } xml<<"\t\t\t\t\t<calGain avg=\""<<gain <<"\" sig=\""<<rms<<"\" range=\"" <<((rg<2)?"L":"H")<<"EX"<<((rg%2==0)?"8":"1")<<"\" />"<<endl; } xml<<"\t\t\t\t</face>"<<endl; } xml<<"\t\t\t</xtal>"<<endl; } xml<<"\t\t</layer>"<<endl; } //end file xml<<"\t</tower>"<<endl; xml<<"</calCalib>"<<endl; xml.close(); tree_pdl->SetBranchStatus("*", 1); tree_muons->SetBranchStatus("*", 1); tree_att->SetBranchStatus("*", 1); histFile.Close(); } void RootTreeAnalysis::MuonSlopesToXml( char* filename ){ std::ofstream xml( filename ); histFile= new TFile( m_histFileName ); Float_t slope; TNtuple *tree= (TNtuple*) histFile->Get("logPoverN"); if (!tree){ printf("ERROR:NO CAL CORR TREE\n"); return; } tree->SetBranchStatus("*", 0); tree->SetBranchStatus("slope", 1); tree->SetBranchAddress("slope", &slope); short int rg, layer, column, face; //header xml<<"<?xml version=\"1.0\" ?>"<<endl<<endl; xml<<"<!-- $Header: my Pdl-->"<<endl<<endl; xml<<"<!-- Approximately real CAL muon slope XML file for EM, according to calCalibv3.dtd -->"<<endl<<endl; xml<<"<!DOCTYPE calCalib SYSTEM \"../calCalib_v3.dtd\" [] >"<<endl<<endl; //calCalib xml<<"<calCalib>"<<endl <<"\t<generic\tinstrument=\"EM\" timestamp=\"2003-11-2-12:56\""<<endl <<"\t\t\t\tcalibType=\"CAL_MuSlope\" fmtVersion=\"v2r0\">"<<endl<<endl <<"\t\t<inputSample\tstartTime=\"2003-2-21-05:49:12\"" <<" stopTime=\"2003-2-24-07:07:02\""<<endl <<"\t\t\t\t\ttriggers=\"random\" mode=\"normal\" source=\"stuff\" >"<<endl <<endl; xml<<"\t\tTimes are start and stop time of calibration run."<<endl <<"\t\tOther attributes are just made up for code testing."<<endl; xml<<"\t\t</inputSample>"<<endl <<"\t</generic>"<<endl<<endl<<endl; xml<<"<!-- EM instrument: 8 layers, 12 columns -->"<<endl<<endl <<"\t<dimension nRow=\"1\" nCol=\"1\" " <<"nLayer=\"8\" nXtal=\"12\" nFace=\"1\" />"<<endl<<endl; xml<<"\t<tower iRow=\"0\" iCol=\"0\">"<<endl; for( layer=0; layer<8; layer++ ){ xml<<"\t\t<layer iLayer=\""<<layer<<"\">"<<endl; for( column=0; column<12; column++ ){ xml<<"\t\t\t<xtal iXtal=\""<<column<<"\">"<<endl; xml<<"\t\t\t\t<face end=\"NA\">"<<endl; tree->GetEntry( layer*24 + column*2 + face ); for( rg=0; rg<4; rg++ ){ xml<<"\t\t\t\t\t<muSlope slope=\""<<slope<<"\" range=\""; xml<<((rg<2)?"L":"H")<<"EX"<<((rg%2==0)?"8":"1")<<"\" />"<<endl; } xml<<"\t\t\t\t</face>"<<endl; xml<<"\t\t\t</xtal>"<<endl; } xml<<"\t\t</layer>"<<endl; } //end file xml<<"\t</tower>"<<endl; xml<<"</calCalib>"<<endl; xml.close(); tree->SetBranchStatus("*", 0); histFile->Close(); } void RootTreeAnalysis::Go(Int_t numEvents){ //init // Purpose and Method: Event Loop // All analysis goes here // To read only selected branches - saves processing time // Comment out any branches you are not interested in. //branch status if (digiTree) { digiTree->SetBranchStatus("*",0); // disable all branches // activate desired brances digiTree->SetBranchStatus("m_cal*",1); digiTree->SetBranchStatus("m_tkr*",1); digiTree->SetBranchStatus("m_eventId", 1); digiTree->SetBranchStatus("m_runId", 1); } // leaving all recon branches activated for now if (reconTree) { reconTree->SetBranchStatus("*",0); // disable all branches // activate desired branches reconTree->SetBranchStatus("m_cal", 1); reconTree->SetBranchStatus("m_tkr", 1); } Int_t nentries = GetEntries(); std::cout << "\nNum Events in File is: " << nentries << std::endl; Int_t curI=0; Int_t nMax = TMath::Min(numEvents+m_StartEvent,nentries); if (m_StartEvent == nentries) { std::cout << " all events in file read" << std::endl; return; } if (nentries <= 0) return; // Keep track of how many bytes we have read in from the data files Int_t nbytes = 0, nb = 0; HistDefine(); if( (job_id>1) && !getPdl( pdl_mpv, pdl_width ) ) return; if( (job_id==4) && !getLogPoverN( logPoverN_slope ) ) return; // BEGINNING OF EVENT LOOP Double_t position[19]; Int_t XtalAdc[16]; Short_t col[8]; for (Int_t ievent= m_StartEvent; ievent<nMax; ievent++, curI=ievent) { //init if (evt) evt->Clear(); if (rec) rec->Clear(); digiEventId = 0; reconEventId = 0; mcEventId = 0; digiRunNum = 0; reconRunNum = 0; mcRunNum = 0; nb = GetEvent(ievent); nbytes += nb; if ( evt ) { switch(job_id){ case 0: Pdl(); break; case 1: Pdl_Correlated(); break; case 2: Pdl_Corr_NoMuon(); break; default: if ( (Make_Cut( position, XtalAdc, col ))==0 ) continue; Make_Hist( position, XtalAdc, col ); } if (ievent%1000==0) { printf("[%ld]", ievent); fflush(stdout); } if (ievent>=50000 && ievent%50000==0) histFile->Write("", TObject::kOverwrite); } } // end analysis code in event loop //end m_StartEvent = curI; histFile->Write("", TObject::kOverwrite); histFile->Close(); } #endif
[ "" ]
d1bcd1e9aac2c6bdc1ef978a31c1f5ff95012c7f
b9514762eb348e2447ad69534e5955acfa0649af
/Source/Lutefisk3D/Input/Controls.h
c0eaafffa43b89261b4d26a6840bf72aa537c96c
[ "Apache-2.0", "BSD-2-Clause", "Zlib", "MIT", "LicenseRef-scancode-khronos", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Prashant-Jonny/lutefisk3d
d2c23c463e14a9845e9cb183004e53fa789cd86d
397f188689f7410a331782992ded4204ab11b0b2
refs/heads/master
2020-12-03T07:54:34.221642
2015-10-28T08:42:20
2015-10-28T08:42:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,130
h
// // Copyright (c) 2008-2015 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #pragma once #include "../Core/Variant.h" namespace Urho3D { /// %Controls sent over the network. class Controls { public: /// Construct. Controls(); /// Destruct. ~Controls(); /// Reset to initial state. void Reset(); /// Set or release buttons. void Set(unsigned buttons, bool down = true) { if (down) buttons_ |= buttons; else buttons_ &= ~buttons; } /// Check if a button is held down. bool IsDown(unsigned button) const { return (buttons_ & button) != 0; } /// Check if a button was pressed on this frame. Requires previous frame's controls. bool IsPressed(unsigned button, const Controls& previousControls) const { return (buttons_ & button) != 0 && (previousControls.buttons_ & button) == 0; } /// Button state. unsigned buttons_; /// Mouse yaw. float yaw_; /// Mouse pitch. float pitch_; /// Extra control data. VariantMap extraData_; }; }
[ "nemerle5@gmail.com" ]
nemerle5@gmail.com
13103629938a6ed4b0a21917e315570edfd93b01
c7aac55da99b0c2fbaa67d86b6a7be604c69dc4e
/hw2-starterCode/.history/hw2_core_code/hw2_20200321013551.cpp
943fe64705b8ef0670d6553085003ffb61ac4a6c
[]
no_license
RealZiangLiu/usc_csci420_sp20
76733daa3ec84d9c3283330b65ca37fda416a350
c3a7e38d32cf1f14100512a6da23aa34673f682d
refs/heads/master
2023-02-19T09:33:39.379731
2020-04-23T01:29:34
2020-04-23T01:29:34
242,432,725
1
0
null
null
null
null
UTF-8
C++
false
false
31,715
cpp
/* CSCI 420 Computer Graphics, USC Assignment 2: Roller Coaster C++ starter code Student username: ziangliu ID: 9114346039 */ #include "basicPipelineProgram.h" #include "openGLMatrix.h" #include "imageIO.h" #include "openGLHeader.h" #include "glutHeader.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <cstring> #include <string> #include <vector> #if defined(WIN32) || defined(_WIN32) #ifdef _DEBUG #pragma comment(lib, "glew32d.lib") #else #pragma comment(lib, "glew32.lib") #endif #endif #if defined(WIN32) || defined(_WIN32) char shaderBasePath[1024] = SHADER_BASE_PATH; #else char shaderBasePath[1024] = "../openGLHelper-starterCode"; #endif using namespace std; // Constant parameters const double param_s = 0.5; const double param_u_step = 0.001; const int speed = 5; // represents one control point along the spline struct Point { double x; double y; double z; Point () {}; Point (double x_, double y_, double z_) : x(x_), y(y_), z(z_) {} Point operator- (Point& other) { return Point(x - other.x, y - other.y, z - other.z); } Point operator+ (Point& other) { return Point(x + other.x, y + other.y, z + other.z); } Point operator* (double mult) { return Point(x * mult, y * mult, z * mult); } Point operator/ (double div) { return Point(x / div, y / div, z / div); } void normalize () { double norm = sqrt(x * x + y * y + z * z); x /= norm; y /= norm; z /= norm; } Point cross (Point& other) { Point res(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x); double norm = sqrt(res.x * res.x + res.y * res.y + res.z * res.z); return res / norm; } }; Point normalize (Point& pt) { double norm = sqrt(pt.x * pt.x + pt.y * pt.y + pt.z * pt.z); return pt / norm; } // spline struct // contains how many control points the spline has, and an array of control points struct Spline { int numControlPoints; Point * points; }; struct CatmullMatrix { const vector< vector<double> > basis = { {-param_s, 2 - param_s, param_s - 2, param_s }, {2 * param_s, param_s - 3, 3 - 2 * param_s, -param_s}, {-param_s, 0, param_s, 0 }, {0, 1, 0, 0}}; Point computePosition (double u_, Point& p_1, Point& p_2, Point& p_3, Point& p_4) { vector<double> first_res(4, 0.0); vector<double> final_res(3, 0.0); vector<double> design = {pow(u_, 3), pow(u_, 2), u_, 1.0}; vector<Point> control = {p_1, p_2, p_3, p_4}; // Multiply design matrix with basis for (int i=0; i<4; ++i) { for (int j=0; j<4; ++j) { first_res[i] += (design[j] * basis[j][i]); } } // Multiply previous result with control matrix for (int i=0; i<4; ++i) { final_res[0] += (first_res[i] * control[i].x); final_res[1] += (first_res[i] * control[i].y); final_res[2] += (first_res[i] * control[i].z); } return Point(final_res[0], final_res[1], final_res[2]); } Point computeTangent (double u_, Point& p_1, Point& p_2, Point& p_3, Point& p_4) { vector<double> first_res(4, 0.0); vector<double> final_res(3, 0.0); vector<double> design = {3 * pow(u_, 2), 2 * u_, 1.0, 0.0}; vector<Point> control = {p_1, p_2, p_3, p_4}; // Multiply design matrix with basis for (int i=0; i<4; ++i) { for (int j=0; j<4; ++j) { first_res[i] += (design[j] * basis[j][i]); } } // Multiply previous result with control matrix for (int i=0; i<4; ++i) { final_res[0] += (first_res[i] * control[i].x); final_res[1] += (first_res[i] * control[i].y); final_res[2] += (first_res[i] * control[i].z); } Point res(final_res[0], final_res[1], final_res[2]); return normalize(res); } }; CatmullMatrix computeMatrix; // the spline array Spline * splines; // total number of splines int numSplines; int mousePos[2]; // x,y coordinate of the mouse position int leftMouseButton = 0; // 1 if pressed, 0 if not int middleMouseButton = 0; // 1 if pressed, 0 if not int rightMouseButton = 0; // 1 if pressed, 0 if not typedef enum { ROTATE, TRANSLATE, SCALE } CONTROL_STATE; CONTROL_STATE controlState = ROTATE; // state of the world float landRotate[3] = { 0.0f, 0.0f, 0.0f }; float landTranslate[3] = { 0.0f, 0.0f, 0.0f }; float landScale[3] = { 1.0f, 1.0f, 1.0f }; int windowWidth = 1280; int windowHeight = 720; char windowTitle[512] = "CSCI 420 homework II"; int mode = 1; int record_animation = 0; int camera_on_rail = 0; int roller_frame_count = 0; GLuint VBO; GLuint VAO; GLuint EBO; vector<GLuint> splineVBOs; vector<GLuint> splineVAOs; vector<int> splineVertexCnt; // store point positions along spline vector< vector<Point> > splinePointCoords; vector< vector<Point> > splineTangents; vector< vector<Point> > splineNormals; vector< vector<Point> > splineBinormals; OpenGLMatrix matrix; BasicPipelineProgram * pipelineProgram; int frame_cnt = 0; // void renderWireframe(); void renderSplines(); int loadSplines(char * argv) { char * cName = (char *) malloc(128 * sizeof(char)); FILE * fileList; FILE * fileSpline; int iType, i = 0, j, iLength; // load the track file fileList = fopen(argv, "r"); if (fileList == NULL) { printf ("can't open file\n"); exit(1); } // stores the number of splines in a global variable fscanf(fileList, "%d", &numSplines); splines = (Spline*) malloc(numSplines * sizeof(Spline)); // reads through the spline files for (j = 0; j < numSplines; j++) { i = 0; fscanf(fileList, "%s", cName); fileSpline = fopen(cName, "r"); if (fileSpline == NULL) { printf ("can't open file\n"); exit(1); } // gets length for spline file fscanf(fileSpline, "%d %d", &iLength, &iType); // allocate memory for all the points splines[j].points = (Point *)malloc(iLength * sizeof(Point)); splines[j].numControlPoints = iLength; // saves the data to the struct while (fscanf(fileSpline, "%lf %lf %lf", &splines[j].points[i].x, &splines[j].points[i].y, &splines[j].points[i].z) != EOF) { i++; } } free(cName); return 0; } int initTexture(const char * imageFilename, GLuint textureHandle) { // read the texture image ImageIO img; ImageIO::fileFormatType imgFormat; ImageIO::errorType err = img.load(imageFilename, &imgFormat); if (err != ImageIO::OK) { printf("Loading texture from %s failed.\n", imageFilename); return -1; } // check that the number of bytes is a multiple of 4 if (img.getWidth() * img.getBytesPerPixel() % 4) { printf("Error (%s): The width*numChannels in the loaded image must be a multiple of 4.\n", imageFilename); return -1; } // allocate space for an array of pixels int width = img.getWidth(); int height = img.getHeight(); unsigned char * pixelsRGBA = new unsigned char[4 * width * height]; // we will use 4 bytes per pixel, i.e., RGBA // fill the pixelsRGBA array with the image pixels memset(pixelsRGBA, 0, 4 * width * height); // set all bytes to 0 for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { // assign some default byte values (for the case where img.getBytesPerPixel() < 4) pixelsRGBA[4 * (h * width + w) + 0] = 0; // red pixelsRGBA[4 * (h * width + w) + 1] = 0; // green pixelsRGBA[4 * (h * width + w) + 2] = 0; // blue pixelsRGBA[4 * (h * width + w) + 3] = 255; // alpha channel; fully opaque // set the RGBA channels, based on the loaded image int numChannels = img.getBytesPerPixel(); for (int c = 0; c < numChannels; c++) // only set as many channels as are available in the loaded image; the rest get the default value pixelsRGBA[4 * (h * width + w) + c] = img.getPixel(w, h, c); } // bind the texture glBindTexture(GL_TEXTURE_2D, textureHandle); // initialize the texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelsRGBA); // generate the mipmaps for this texture glGenerateMipmap(GL_TEXTURE_2D); // set the texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // query support for anisotropic texture filtering GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); printf("Max available anisotropic samples: %f\n", fLargest); // set anisotropic texture filtering glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 0.5f * fLargest); // query for any errors GLenum errCode = glGetError(); if (errCode != 0) { printf("Texture initialization error. Error code: %d.\n", errCode); return -1; } // de-allocate the pixel array -- it is no longer needed delete [] pixelsRGBA; return 0; } // write a screenshot to the specified filename void saveScreenshot(const char * filename) { unsigned char * screenshotData = new unsigned char[windowWidth * windowHeight * 3]; glReadPixels(0, 0, windowWidth, windowHeight, GL_RGB, GL_UNSIGNED_BYTE, screenshotData); ImageIO screenshotImg(windowWidth, windowHeight, 3, screenshotData); if (screenshotImg.save(filename, ImageIO::FORMAT_JPEG) == ImageIO::OK) std::cout << "File " << filename << " saved successfully." << endl; else std::cout << "Failed to save file " << filename << '.' << endl; delete [] screenshotData; } // write a screenshot to the specified filename /* void saveScreenshot(const char * filename) { int scale = 2; int ww = windowWidth * scale; int hh = windowHeight * scale; unsigned char * screenshotData = new unsigned char[ww * hh * 3]; glReadPixels(0, 0, ww, hh, GL_RGB, GL_UNSIGNED_BYTE, screenshotData); unsigned char * screenshotData1 = new unsigned char[windowWidth * windowHeight * 3]; for (int h = 0; h < windowHeight; h++) { for (int w = 0; w < windowWidth; w++) { int h1 = h * scale; int w1 = w * scale; screenshotData1[(h * windowWidth + w) * 3] = screenshotData[(h1 * ww + w1) * 3]; screenshotData1[(h * windowWidth + w) * 3 + 1] = screenshotData[(h1 * ww + w1) * 3 + 1]; screenshotData1[(h * windowWidth + w) * 3 + 2] = screenshotData[(h1 * ww + w1) * 3 + 2]; } } ImageIO screenshotImg(windowWidth, windowHeight, 3, screenshotData1); if (screenshotImg.save(filename, ImageIO::FORMAT_JPEG) == ImageIO::OK) cout << "File " << filename << " saved successfully." << endl; else cout << "Failed to save file " << filename << '.' << endl; delete [] screenshotData; delete [] screenshotData1; }*/ void displayFunc() { // render some stuff... glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Reset roller coaster frame counter roller_frame_count %= splineVertexCnt[0]; float m[16], p[16]; // Column-major if (!camera_on_rail) { matrix.SetMatrixMode(OpenGLMatrix::ModelView); matrix.LoadIdentity(); matrix.LookAt(0, 0, 5, 0, 0, 0, 0, 1, 0); // matrix.SetMatrixMode(OpenGLMatrix::ModelView); matrix.Translate(landTranslate[0], landTranslate[1], landTranslate[2]); matrix.Rotate(landRotate[0], 1, 0, 0); matrix.Rotate(landRotate[1], 0, 1, 0); matrix.Rotate(landRotate[2], 0, 0, 1); matrix.Scale(landScale[0], landScale[1], landScale[2]); matrix.GetMatrix(m); matrix.SetMatrixMode(OpenGLMatrix::Projection); matrix.GetMatrix(p); } else { matrix.SetMatrixMode(OpenGLMatrix::ModelView); matrix.LoadIdentity(); int focusIdx = (roller_frame_count+1) % splineVertexCnt[0]; matrix.LookAt(splinePointCoords[0][roller_frame_count].x + 0.01 * splineNormals[0][roller_frame_count].x, splinePointCoords[0][roller_frame_count].y + 0.01 * splineNormals[0][roller_frame_count].y, splinePointCoords[0][roller_frame_count].z + 0.01 * splineNormals[0][roller_frame_count].z, // eye point splinePointCoords[0][focusIdx].x + 0.01 * splineNormals[0][focusIdx].x, splinePointCoords[0][focusIdx].y + 0.01 * splineNormals[0][focusIdx].y, splinePointCoords[0][focusIdx].z + 0.01 * splineNormals[0][focusIdx].z, // focus point splineNormals[0][roller_frame_count].x, splineNormals[0][roller_frame_count].y, splineNormals[0][roller_frame_count].z); matrix.Translate(landTranslate[0], landTranslate[1], landTranslate[2]); matrix.Rotate(landRotate[0], 1, 0, 0); matrix.Rotate(landRotate[1], 0, 1, 0); matrix.Rotate(landRotate[2], 0, 0, 1); matrix.Scale(landScale[0], landScale[1], landScale[2]); matrix.GetMatrix(m); matrix.SetMatrixMode(OpenGLMatrix::Projection); matrix.GetMatrix(p); } // ++roller_frame_count; roller_frame_count += speed; // DEBUG print cout << "Coord: " << splineTangents[0][roller_frame_count].x << " " << splineTangents[0][roller_frame_count].y << " " << splineTangents[0][roller_frame_count].z << endl; // get a handle to the program GLuint program = pipelineProgram->GetProgramHandle(); // get a handle to the modelViewMatrix shader variable GLint h_modelViewMatrix = glGetUniformLocation(program, "modelViewMatrix"); // get a handle to the projectionMatrix shader variable GLint h_projectionMatrix = glGetUniformLocation(program, "projectionMatrix"); // Get handle to mode shader variable GLint h_mode = glGetUniformLocation(program, "mode"); // bind shader pipelineProgram->Bind(); // Upload matrices to GPU GLboolean isRowMajor = GL_FALSE; glUniformMatrix4fv(h_modelViewMatrix, 1, isRowMajor, m); glUniformMatrix4fv(h_projectionMatrix, 1, isRowMajor, p); // set variable pipelineProgram->SetModelViewMatrix(m); pipelineProgram->SetProjectionMatrix(p); // renderWireframe(); renderSplines(); glutSwapBuffers(); } void idleFunc() { if (record_animation == 1) { // Save screenshots for animation if (frame_cnt % 4 == 0 && frame_cnt < 1200) { string file_path = "../screenshots/"; string id; int t = frame_cnt / 4; for (int i=0; i<3; ++i) { id += to_string(t % 10); t /= 10; } reverse(id.begin(), id.end()); file_path += (id + ".jpg"); saveScreenshot(file_path.c_str()); } ++frame_cnt; } // make the screen update glutPostRedisplay(); } void reshapeFunc(int w, int h) { glViewport(0, 0, w, h); matrix.SetMatrixMode(OpenGLMatrix::Projection); matrix.LoadIdentity(); matrix.Perspective(54.0f, (float)w / (float)h, 0.01f, 100.0f); matrix.SetMatrixMode(OpenGLMatrix::ModelView); } void mouseMotionDragFunc(int x, int y) { // mouse has moved and one of the mouse buttons is pressed (dragging) // the change in mouse position since the last invocation of this function int mousePosDelta[2] = { x - mousePos[0], y - mousePos[1] }; switch (controlState) { // translate the landscape case TRANSLATE: if (leftMouseButton) { // control x,y translation via the left mouse button landTranslate[0] += mousePosDelta[0] * 0.01f; landTranslate[1] -= mousePosDelta[1] * 0.01f; } if (middleMouseButton) { // control z translation via the middle mouse button landTranslate[2] += mousePosDelta[1] * 0.01f; } break; // rotate the landscape case ROTATE: if (leftMouseButton) { // control x,y rotation via the left mouse button landRotate[0] += mousePosDelta[1]; landRotate[1] += mousePosDelta[0]; } if (middleMouseButton) { // control z rotation via the middle mouse button landRotate[2] += mousePosDelta[1]; } break; // scale the landscape case SCALE: if (leftMouseButton) { // control x,y scaling via the left mouse button landScale[0] *= 1.0f + mousePosDelta[0] * 0.01f; landScale[1] *= 1.0f - mousePosDelta[1] * 0.01f; } if (middleMouseButton) { // control z scaling via the middle mouse button landScale[2] *= 1.0f - mousePosDelta[1] * 0.01f; } break; } // store the new mouse position mousePos[0] = x; mousePos[1] = y; } void mouseMotionFunc(int x, int y) { // mouse has moved // store the new mouse position mousePos[0] = x; mousePos[1] = y; } void mouseButtonFunc(int button, int state, int x, int y) { // a mouse button has has been pressed or depressed // keep track of the mouse button state, in leftMouseButton, middleMouseButton, rightMouseButton variables switch (button) { case GLUT_LEFT_BUTTON: leftMouseButton = (state == GLUT_DOWN); break; case GLUT_MIDDLE_BUTTON: middleMouseButton = (state == GLUT_DOWN); break; case GLUT_RIGHT_BUTTON: rightMouseButton = (state == GLUT_DOWN); break; } // keep track of whether CTRL and SHIFT keys are pressed switch (glutGetModifiers()) { case GLUT_ACTIVE_CTRL: controlState = TRANSLATE; break; case GLUT_ACTIVE_SHIFT: controlState = SCALE; break; // if CTRL and SHIFT are not pressed, we are in rotate mode default: controlState = ROTATE; break; } // store the new mouse position mousePos[0] = x; mousePos[1] = y; } void keyboardFunc(unsigned char key, int x, int y) { switch (key) { case 27: // ESC key exit(0); // exit the program break; case ' ': std::cout << "You pressed the spacebar." << endl; break; case 't': // Translate controlState = TRANSLATE; break; case 'x': // take a screenshot saveScreenshot("screenshot.jpg"); break; case 's': // Start capture animation record_animation = (1 - record_animation); break; case 'r': // Run the roller coaster camera_on_rail = 1 - camera_on_rail; if (camera_on_rail) { cout << "Placing camera on rail. Press 'r' again to change." << endl; } else { cout << "Camera free move mode. Press 'r' again to change." << endl; } break; } } // void renderPoints() { // glBindVertexArray(pointVAO); // glDrawArrays(GL_POINTS, 0, pointNumVertex); // glBindVertexArray(0); // } // void renderWireframe() { // glBindVertexArray(wireVAO); // glDrawElements(GL_LINES, wireIdxCnt, GL_UNSIGNED_INT, (void*)0); // glBindVertexArray(0); // } void renderSplines () { for (size_t i=0; i<numSplines; ++i) { glBindVertexArray(splineVAOs[i]); glDrawArrays(GL_LINE_STRIP, 0, splineVertexCnt[i]); glBindVertexArray(0); } } void compute_store_points_tangents (glm::vec3* pointPositions, int splineIdx, int pointCnt, int u_cnt, Point& p_1, Point& p_2, Point& p_3, Point& p_4) { Point res = computeMatrix.computePosition(u_cnt * param_u_step, p_1, p_2, p_3, p_4); // Position vector to put into VBO pointPositions[pointCnt] = glm::vec3(res.x, res.y, res.z); // Global position vector to track point locations splinePointCoords[splineIdx].push_back(res); Point tangent = computeMatrix.computeTangent(u_cnt * param_u_step, p_1, p_2, p_3, p_4); // Global tangent vector to track tangent of spline at this point splineTangents[splineIdx].push_back(tangent); } void compute_catmull_rom_point (glm::vec3* pointPositions, Point* points, int currNumCtrlPts, int splineIdx, Point& prev_1, Point& prev_2, Point& next_1, bool connect_prev = false, bool connect_next = false) { int pointCnt = 0; if (connect_prev) { // First segment to connect with previous spline for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) { compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, prev_2, prev_1, points[1], points[2]); ++pointCnt; } // Second segment to connect with previous spline for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) { compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, prev_1, points[1], points[2], points[3]); ++pointCnt; } } int start = connect_prev ? 2 : 1; int end = connect_next ? (currNumCtrlPts-3) : (currNumCtrlPts-2); for (int i=start; i<end; ++i) { for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) { compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, points[i-1], points[i], points[i+1], points[i+2]); ++pointCnt; } } // last point // Point last; if (connect_next) { cout << "[DEBUG]: connect next is true" << endl; for (int u_cnt=0; u_cnt <= (int)(1.0 / param_u_step); ++u_cnt) { compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, points[currNumCtrlPts-4], points[currNumCtrlPts-3], points[currNumCtrlPts-2], next_1); ++pointCnt; } } else { compute_store_points_tangents(pointPositions, splineIdx, pointCnt, (int)(1.0 / param_u_step), points[currNumCtrlPts-4], points[currNumCtrlPts-3], points[currNumCtrlPts-2], points[currNumCtrlPts-1]); ++pointCnt; } // Compute initial Frenet Frame vectors Point initial_V(0.0, 0.0, 1.0); Point T_0 = splineTangents[splineIdx][0]; Point N_0 = T_0.cross(initial_V); Point B_0 = T_0.cross(N_0); splineNormals[splineIdx].push_back(N_0); splineBinormals[splineIdx].push_back(B_0); for (int i=1; i<pointCnt; ++i) { splineNormals[splineIdx].push_back(splineBinormals[splineIdx][i-1].cross(splineTangents[splineIdx][i])); splineBinormals[splineIdx].push_back(splineTangents[splineIdx][i].cross(splineNormals[splineIdx][i])); } } void add_square_rail (glm::vec3* pointPositions, int splineIdx) { for (int i=1; i<splineVertexCnt[splineIdx]; ++i) { Point p_0 = splinePointCoords[splineIdx][i-1]; Point n_0 = splineNormals[splineIdx][i-1]; Point b_0 = splineBinormals[splineIdx][i-1]; Point p_1 = splinePointCoords[splineIdx][i]; Point n_1 = splineNormals[splineIdx][i]; Point b_1 = splineBinormals[splineIdx][i]; Point v_0, v_1, v_2, v_3, v_4, v_5, v_6, v_7; } } void initScene(int argc, char *argv[]) { // load the splines from the provided filename loadSplines(argv[1]); printf("Loaded %d spline(s).\n", numSplines); for(int i=0; i<numSplines; i++) printf("Num control points in spline %d: %d.\n", i, splines[i].numControlPoints); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); /* Initialize pipelineProgram */ pipelineProgram = new BasicPipelineProgram; int ret = pipelineProgram->Init(shaderBasePath); if (ret != 0) abort(); Point prev_1_point; Point prev_2_point; Point next_1_point; // Intialize global coord and tangent vectors splinePointCoords.resize(numSplines); splineTangents.resize(numSplines); splineNormals.resize(numSplines); splineBinormals.resize(numSplines); for (int i=0; i<numSplines; ++i) { // cout << "[DEBUG] Control points: " << splines[i].numControlPoints << endl; int currNumCtrlPts = splines[i].numControlPoints; // currNumCtrlPts - 3 segments, +1 for endpoint int uNumPoints = ((int)(1.0 / param_u_step)) * (currNumCtrlPts - 3) + 1; if (i > 0) { // uNumPoints += (int)(1.0 / param_u_step); } // // Compute tangent for control points p_2 ~ p_(n-1) // Point* tangentPoints = new Point[currNumCtrlPts - 2]; // for (int j=1; j<currNumCtrlPts-1; ++j) { // tangentPoints[j-1] = (splines[i].points[j+1] - splines[i].points[j-1]) * param_s; // } // // DEBUG output // for (int i=0; i<currNumCtrlPts-2; ++i) { // cout << tangentPoints[i].x << ", " << tangentPoints[i].y << ", " << tangentPoints[i].z << endl; // } GLuint currVBO, currVAO; glm::vec3* pointPositions = new glm::vec3[uNumPoints]; // TODO: move color computation to vertex shader glm::vec4* pointColors = new glm::vec4[uNumPoints]; bool connect_prev = false; if (i > 0) { connect_prev = true; prev_1_point = splines[i-1].points[splines[i-1].numControlPoints-2]; prev_2_point = splines[i-1].points[splines[i-1].numControlPoints-3]; } bool connect_next = false; if (i < numSplines - 1) { connect_next = true; next_1_point = splines[i+1].points[1]; } // Disable multiple curve connection // connect_prev = false; // connect_next = false; compute_catmull_rom_point(pointPositions, splines[i].points, currNumCtrlPts, i, prev_1_point, prev_2_point, next_1_point, connect_prev, connect_next); // Set colors for (int i=0; i<uNumPoints; ++i) { pointColors[i] = glm::vec4(1.0, 1.0, 1.0, 1.0); } // DEBUG output // for (int i=0; i<uNumPoints; ++i) { // cout << pointPositions[i][0] << ", " << pointPositions[i][1] << ", " << pointPositions[i][2] << endl; // } // TODO: add function to compute eight points for cross-section for every two points on rail // Set positions VBO glGenBuffers(1, &currVBO); glBindBuffer(GL_ARRAY_BUFFER, currVBO); // glBufferData(GL_ARRAY_BUFFER, sizeof(pointPositions) + sizeof(pointColors), nullptr, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * uNumPoints + sizeof(glm::vec4) * uNumPoints, nullptr, GL_STATIC_DRAW); // Upload position data // glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(pointPositions), pointPositions); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * uNumPoints, pointPositions); // Upload color data // glBufferSubData(GL_ARRAY_BUFFER, sizeof(pointPositions), sizeof(pointColors), pointColors); glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * uNumPoints, sizeof(glm::vec4) * uNumPoints, pointColors); glGenVertexArrays(1, &currVAO); glBindVertexArray(currVAO); // Bind pointVBO glBindBuffer(GL_ARRAY_BUFFER, currVBO); // Set "position" layout GLuint loc = glGetAttribLocation(pipelineProgram->GetProgramHandle(), "position"); glEnableVertexAttribArray(loc); const void * offset = (const void*) 0; GLsizei stride = 0; glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset); // Set "color" layout loc = glGetAttribLocation(pipelineProgram->GetProgramHandle(), "color"); glEnableVertexAttribArray(loc); // offset = (const void*) sizeof(pointPositions); offset = (const void*) (sizeof(glm::vec3) * uNumPoints); glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, stride, offset); glBindVertexArray(0); // Unbind the VAO glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind the VBO splineVBOs.push_back(currVBO); splineVAOs.push_back(currVAO); splineVertexCnt.push_back(uNumPoints); delete [] pointColors; delete [] pointPositions; // delete [] tangentPoints; } /* { // glm::vec3 pointPositions[pointNumVertex]; glm::vec3* pointPositions = new glm::vec3[pointNumVertex]; // glm::vec4 pointColors[pointNumVertex]; glm::vec4* pointColors = new glm::vec4[pointNumVertex]; for (int x=0; x<imageWidth; ++x) { for (int y=0; y<imageHeight; ++y) { double color_R = heightmapImage->getPixel(x, y, channels[0]) / 255.0; double color_G = heightmapImage->getPixel(x, y, channels[1]) / 255.0; double color_B = heightmapImage->getPixel(x, y, channels[2]) / 255.0; double color_height = (color_R / 3.0 + color_G / 3.0 + color_B / 3.0); pointPositions[y * imageWidth + x] = glm::vec3((double)(x - imageWidth/2.0) / imageWidth * 4, color_height, (double)(y - imageHeight/2.0) / imageHeight * 4); pointColors[y * imageWidth + x] = glm::vec4(color_R, color_G, color_B, 1); } } // Set positions VBO glGenBuffers(1, &pointVBO); glBindBuffer(GL_ARRAY_BUFFER, pointVBO); // glBufferData(GL_ARRAY_BUFFER, sizeof(pointPositions) + sizeof(pointColors), nullptr, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * pointNumVertex + sizeof(glm::vec4) * pointNumVertex, nullptr, GL_STATIC_DRAW); // Upload position data // glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(pointPositions), pointPositions); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * pointNumVertex, pointPositions); // Upload color data // glBufferSubData(GL_ARRAY_BUFFER, sizeof(pointPositions), sizeof(pointColors), pointColors); glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * pointNumVertex, sizeof(glm::vec4) * pointNumVertex, pointColors); glGenVertexArrays(1, &pointVAO); glBindVertexArray(pointVAO); // Bind pointVBO glBindBuffer(GL_ARRAY_BUFFER, pointVBO); // Set "position" layout GLuint loc = glGetAttribLocation(pipelineProgram->GetProgramHandle(), "position"); glEnableVertexAttribArray(loc); const void * offset = (const void*) 0; GLsizei stride = 0; glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset); // Set "color" layout loc = glGetAttribLocation(pipelineProgram->GetProgramHandle(), "color"); glEnableVertexAttribArray(loc); // offset = (const void*) sizeof(pointPositions); offset = (const void*) (sizeof(glm::vec3) * pointNumVertex); glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, stride, offset); glBindVertexArray(0); // Unbind the VAO glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind the VBO delete [] pointPositions; delete [] pointColors; } */ glEnable(GL_DEPTH_TEST); std::cout << "GL error: " << glGetError() << std::endl; } int main(int argc, char *argv[]) { if (argc<2) { printf ("usage: %s <trackfile>\n", argv[0]); exit(0); } std::cout << "Initializing GLUT..." << endl; glutInit(&argc,argv); std::cout << "Initializing OpenGL..." << endl; #ifdef __APPLE__ glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL); #else glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL); #endif glutInitWindowSize(windowWidth, windowHeight); glutInitWindowPosition(0, 0); glutCreateWindow(windowTitle); std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << endl; std::cout << "OpenGL Renderer: " << glGetString(GL_RENDERER) << endl; std::cout << "Shading Language Version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; #ifdef __APPLE__ // This is needed on recent Mac OS X versions to correctly display the window. glutReshapeWindow(windowWidth - 1, windowHeight - 1); #endif // tells glut to use a particular display function to redraw glutDisplayFunc(displayFunc); // perform animation inside idleFunc glutIdleFunc(idleFunc); // callback for mouse drags glutMotionFunc(mouseMotionDragFunc); // callback for idle mouse movement glutPassiveMotionFunc(mouseMotionFunc); // callback for mouse button changes glutMouseFunc(mouseButtonFunc); // callback for resizing the window glutReshapeFunc(reshapeFunc); // callback for pressing the keys on the keyboard glutKeyboardFunc(keyboardFunc); // init glew #ifdef __APPLE__ // nothing is needed on Apple #else // Windows, Linux GLint result = glewInit(); if (result != GLEW_OK) { std::cout << "error: " << glewGetErrorString(result) << endl; exit(EXIT_FAILURE); } #endif // do initialization initScene(argc, argv); // sink forever into the glut loop glutMainLoop(); }
[ "ziangliu@usc.edu" ]
ziangliu@usc.edu
1e1fd808169f2a2f264cf57750d18ecb19c922bd
eab70ad1a99d2542f0328baed80b554c76c7a1e5
/SDLEngine/GComboHandler.cpp
9fdf8594ce74f9976341064171d46ab00f09b3bd
[]
no_license
EZroot/StarShooter
4874bf6c8848119478bcba8081acc55b944bced2
7d17d05961444a75eb90810130a52721b9c5d442
refs/heads/master
2021-12-14T21:25:05.604006
2021-11-20T02:26:41
2021-11-20T02:26:41
151,177,023
0
0
null
null
null
null
UTF-8
C++
false
false
1,223
cpp
#include "GComboHandler.h" #include "ELog.h" GComboHandler::GComboHandler() { } GComboHandler::~GComboHandler() { } void GComboHandler::AddKill() { killCounter++; } void GComboHandler::AddScore(int score) { switch(killMultiplier) { case 2: playerScore += score * 2; break; case 3: playerScore += score * 3; break; case 4: playerScore += score * 4; break; case 5: playerScore += score * 5; break; default: playerScore += score; break; } } void GComboHandler::UpdateCombos(float updateStep) { //If we just killed someone if (killCounter > (prevCounter+1)) { prevCounter = killCounter; //record kill shakeCamera = true; //check if our timer is running for a multiplier if (killMultiplier <= 3 && killTimer > 0) //limit multiplier to 3 { killMultiplier++; //go up a multiplier } //reset timer killTimer = 60; } //Update timer if (killTimer > 0) { killTimer -= 1; } //End camera shake if (killTimer <= 50) { //Default camera shake shakeCamera = false; } //End multiplier if (killTimer <= 0) { killMultiplier = 0; killTimer = 0; } } int GComboHandler::killCounter = 0; int GComboHandler::killMultiplier = 0; int GComboHandler::playerScore = 0;
[ "utohaha@gmail.com" ]
utohaha@gmail.com
136a24b84f97865e27b5a5eca1961f8dc8d1f552
64a1533f4541b76181cd6d3cec3b28876c969250
/jonathanpr/attila/attila.cpp
74c3a9756d3ae5a42e51b23353ba822ef356d2e3
[]
no_license
drkvogel/retrasst
df1db3330115f6e2eea7afdb869e070a28c1cae8
ee952fe39cf1a00998b00a09ca361fc7c83fa336
refs/heads/master
2020-05-16T22:53:26.565996
2014-08-01T16:52:16
2014-08-01T16:52:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,829
cpp
#include <stdlib.h> #include "randdefs.h" #include "xbasic.h" #include "xcgi.h" #include "xdb.h" #include "xquery.h" #include "xencode.h" #include "randutil.h" #include "model.h" #include "view.h" //--------------------------------------------------------------------------- static RAND_UTIL *ru = NULL; static XDB *db = NULL; //--------------------------------------------------------------------------- // REPORT TO LOG FILE. static void report( const std::string & problem ) { ru->getCGI()->log( problem.c_str() ); } static void run( void ) { XCGI * params = ru->getCGI( ); Model info( params ); try { info.parse(params); info.check( db, ru,params); info.logResult( db, params ); } catch( const std::string &problem ) { report( problem + '\n' ); } catch( const std::exception &error ) { report( error.what() + '\n' ); } const View * page = info.nextStage( ); page->sendHTML( ); delete page; } //--------------------------------------------------------------------------- int main( int argc, char **argv ) { XCGI cgi( argc, argv ); cgi.writeHeader( XCGI::typeHtml ); std::string e; ru = new RAND_UTIL( &cgi ); #ifndef __BORLANDC__ db = ru->openDB( "erg_attila" ); #else db = ru->openDB( "dice_erg::erg_attila" ); #endif if ( ru->isValid() ) { std::vector<std::string> sty; sty.push_back( "attila.css" ); ru->htmlBeginDoc( "Attila Randomisation", sty ); ru->htmlBeginBody( ); #ifndef _DEBUG if ( ru->approvedIP() ) #endif { run(); } ru->htmlEndBody( ); ru->htmlEndDoc(); } else { printf(ru->getLastError().c_str()); printf( "\nError initiating" ); } XDELETE( ru ); cgi.end(); return( EXIT_SUCCESS ); } //---------------------------------------------------------------------------
[ "chris.bird@ctsu.ox.ac.uk" ]
chris.bird@ctsu.ox.ac.uk
4c863289f625a57726206a87037856d9c608a121
eb5456a1d1465fb33dd51566cb7d05be116b6f1b
/WebServer_VD3.cpp
a04705ea960d6f64102d8e6679f01060f52ae3a2
[]
no_license
ndq3004/SocketQ
194fcb095c0ba561c085f80c986e8f8386d3ce8c
2a807d1bc5b694c4f03d17ebb60bfa5b9316d8e0
refs/heads/master
2020-04-10T16:16:41.311707
2018-12-10T08:21:18
2018-12-10T08:21:18
161,140,004
0
0
null
null
null
null
UTF-8
C++
false
false
2,194
cpp
// WebServer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include "winsock2.h" int main() { WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa); SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); SOCKADDR_IN addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(8080); bind(listener, (SOCKADDR *)&addr, sizeof(addr)); listen(listener, 5); while (1) { SOCKET client = accept(listener, NULL, NULL); char buf[1024]; int ret; // Nhan yeu cau tu trinh duyet ret = recv(client, buf, sizeof(buf), 0); buf[ret] = 0; printf("%s", buf); /*char cmd[16], path[1024]; sscanf(buf, "%s %s", cmd, path);*/ if (strncmp(buf + 4, "/xinchao", 8) == 0) { // Tra ket qua cho trinh duyet char *header = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n"; send(client, header, strlen(header), 0); char *content = "<html><body><h1>Xin chao</h1></body></html>"; send(client, content, strlen(content), 0); } else if (strncmp(buf + 4, "/hello", 6) == 0) { // Tra ket qua cho trinh duyet char *header = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n"; send(client, header, strlen(header), 0); char *content = "<html><body><h1>Hello</h1></body></html>"; send(client, content, strlen(content), 0); } else if (strncmp(buf + 4, "/image", 6) == 0 || strncmp(buf + 4, "/favicon.ico", 12) == 0) { // Tra ket qua cho trinh duyet char *header = "HTTP/1.1 200 OK\nContent-Type: image/jpg\n\n"; send(client, header, strlen(header), 0); FILE *f = fopen("C:\\test_server\\city.jpg", "rb"); while (1) { ret = fread(buf, 1, sizeof(buf), f); if (ret > 0) send(client, buf, ret, 0); else break; } fclose(f); } else { // Tra ket qua cho trinh duyet char *header = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n"; send(client, header, strlen(header), 0); char *content = "<html><body><h1>Yeu cau khong duoc ho tro</h1></body></html>"; send(client, content, strlen(content), 0); } // Dong ket noi closesocket(client); } closesocket(listener); WSACleanup(); return 0; }
[ "ndq3004@gmail.com" ]
ndq3004@gmail.com
8bc5515db11bcc76490914c83a5c0ba2c10ea5b0
55a56b8abfa4bc18f0ff21622472879a98b2cbc9
/Rozgrzewka3/SigmoidFunction.cpp
5ce3ab12844714ac29547d941bea5fe1301c913b
[]
no_license
lorthal/IAD1
e4cf335e7a3255cc62594445790bf896a7367c9c
adb922fc41325887f3c427baa4ac2ee2262b352b
refs/heads/master
2020-03-10T17:49:30.658980
2019-04-01T11:25:08
2019-04-01T11:25:08
129,509,438
0
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
#include "stdafx.h" #include "SigmoidFunction.h" #include "math.h" double SigmoidFunction::GetResult(const double &input) { return 1 / (1 + exp(-input)); } double SigmoidFunction::GetDerivativeFromInput(const double &input) { return GetResult(input) * (1 - GetResult(input)); } double SigmoidFunction::GetDerivativeFromOutput(const double &output) { return (1 - output) * output; }
[ "bkluchcinski@gmail.com" ]
bkluchcinski@gmail.com
20d67f69017c42a3220345bf2ae40d36b8d24ef5
07191b583c3a78c397931aeff47ffa53155da549
/Library/Vector3.h
9c5c58d2cd3e682c790a24cbb5ee858136278027
[ "MIT" ]
permissive
allenbrubaker/raytracer
f3289dd3933cc566270458c1e07287eb281c2b06
29b3af0fc26ea95998a32ae0ec5d6f48eb433e9e
refs/heads/master
2021-01-20T04:47:24.488026
2014-11-19T04:46:05
2014-11-19T04:46:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,672
h
#ifndef VECTOR3_H #define VECTOR3_H #include <math.h> #include <stdlib.h> #include <assert.h> #include <iostream.h> #include <iomanip.h> class Vector3 { public: Vector3() { e[0] = 0; e[1] = 0; e[2] = 0;} Vector3(float e0, float e1, float e2) {e[0]=e0; e[1]=e1; e[2]=e2;} float x() const { return e[0]; } float y() const { return e[1]; } float z() const { return e[2]; } void setX(float a) { e[0] = a; } void setY(float a) { e[1] = a; } void setZ(float a) { e[2] = a; } inline Vector3(const Vector3 &v) { e[0] = v.e[0]; e[1] = v.e[1]; e[2] = v.e[2]; } const Vector3& operator+() const { return *this; } Vector3 operator-() const { return Vector3(-e[0], -e[1], -e[2]); } float& operator[](int i) { return e[i]; } float operator[](int i) const { return e[i];} Vector3& operator+=(const Vector3 &v2); Vector3& operator-=(const Vector3 &v2); Vector3& operator*=(const float t); Vector3& operator/=(const float t); float length() const { return sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]); } float squaredLength() const { return e[0]*e[0] + e[1]*e[1] + e[2]*e[2]; } void makeUnitVector(); float minComponent() const { return e[indexOfMinComponent()]; } float maxComponent() const { return e[indexOfMaxComponent()]; } float maxAbsComponent() const { return e[indexOfMaxAbsComponent()]; } float minAbsComponent() const { return e[indexOfMinAbsComponent()]; } int indexOfMinComponent() const { return (e[0]< e[1] && e[0]< e[2]) ? 0 : (e[1] < e[2] ? 1 : 2); } int indexOfMinAbsComponent() const { if (fabs(e[0]) < fabs(e[1]) && fabs(e[0]) < fabs(e[2])) return 0; else if (fabs(e[1]) < fabs(e[2])) return 1; else return 2; } int indexOfMaxComponent() const { return (e[0]> e[1] && e[0]> e[2]) ? 0 : (e[1] > e[2] ? 1 : 2); } int indexOfMaxAbsComponent() const { if (fabs(e[0]) > fabs(e[1]) && fabs(e[0]) > fabs(e[2])) return 0; else if (fabs(e[1]) > fabs(e[2])) return 1; else return 2; } float e[3]; }; inline bool operator==(const Vector3 &t1, const Vector3 &t2) { return ((t1[0]==t2[0])&&(t1[1]==t2[1])&&(t1[2]==t2[2])); } inline bool operator!=(const Vector3 &t1, const Vector3 &t2) { return ((t1[0]!=t2[0])||(t1[1]!=t2[1])||(t1[2]!=t2[2])); } inline istream &operator>>(istream &is, Vector3 &t) { is >> t[0] >> t[1] >> t[2]; return is; } inline ostream &operator<<(ostream &os, const Vector3 &t) { os << t[0] << " " << t[1] << " " << t[2]; return os; } inline Vector3 unitVector(const Vector3& v) { float k = 1.0f / sqrt(v.e[0]*v.e[0] + v.e[1]*v.e[1] + v.e[2]*v.e[2]); return Vector3(v.e[0]*k, v.e[1]*k, v.e[2]*k); } inline void Vector3::makeUnitVector() { float k = 1.0f / sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]); e[0] *= k; e[1] *= k; e[2] *= k; } inline Vector3 operator+(const Vector3 &v1, const Vector3 &v2) { return Vector3( v1.e[0] + v2.e[0], v1.e[1] + v2.e[1], v1.e[2] + v2.e[2]); } inline Vector3 operator-(const Vector3 &v1, const Vector3 &v2) { return Vector3( v1.e[0] - v2.e[0], v1.e[1] - v2.e[1], v1.e[2] - v2.e[2]); } inline Vector3 operator*(float t, const Vector3 &v) { return Vector3(t*v.e[0], t*v.e[1], t*v.e[2]); } inline Vector3 operator*(const Vector3 &v, float t) { return Vector3(t*v.e[0], t*v.e[1], t*v.e[2]); } inline Vector3 operator/(const Vector3 &v, float t) { return Vector3(v.e[0]/t, v.e[1]/t, v.e[2]/t); } inline float dot(const Vector3 &v1, const Vector3 &v2) { return v1.e[0] *v2.e[0] + v1.e[1] *v2.e[1] + v1.e[2] *v2.e[2]; } inline Vector3 cross(const Vector3 &v1, const Vector3 &v2) { return Vector3( (v1.e[1]*v2.e[2] - v1.e[2]*v2.e[1]), (v1.e[2]*v2.e[0] - v1.e[0]*v2.e[2]), (v1.e[0]*v2.e[1] - v1.e[1]*v2.e[0])); } inline Vector3& Vector3::operator+=(const Vector3 &v){ e[0] += v.e[0]; e[1] += v.e[1]; e[2] += v.e[2]; return *this; } inline Vector3& Vector3::operator-=(const Vector3& v) { e[0] -= v.e[0]; e[1] -= v.e[1]; e[2] -= v.e[2]; return *this; } inline Vector3& Vector3::operator*=(const float t) { e[0] *= t; e[1] *= t; e[2] *= t; return *this; } inline Vector3& Vector3::operator/=(const float t) { e[0] /= t; e[1] /= t; e[2] /= t; return *this; } inline Vector3 reflect(const Vector3& in, const Vector3& normal) { // assumes unit length normal return in - normal * (2 * dot(in, normal)); } inline float cos_theta(const Vector3& u, const Vector3& v) { return dot(u,v) / (u.length()*v.length()); } #endif
[ "allenbrubaker@gmail.com" ]
allenbrubaker@gmail.com
51abb84c2a5606db3855d3aa5a7dfbd697cf230b
784e683fe0239f991228e0d7632ace5cc2f55ad8
/resource/examples/advanced/InducedPolarization/PolAnalyzer.cxx
b38c1ea7fda1a7ca17754affdeaa662780fd5a78
[]
no_license
rheask8246/megalib
5751ee8e5b00bc6c9a0cacea2c1d82a600f08336
a681302a429aa4a9cb1201c00db1d964fb92a056
refs/heads/master
2021-07-23T14:13:32.687763
2019-01-11T05:41:49
2019-01-11T05:41:49
239,953,431
0
0
null
2020-02-12T07:39:40
2020-02-12T07:39:39
null
UTF-8
C++
false
false
13,117
cxx
/* * PolAnalyzer.cxx * * * Copyright (C) by Andreas Zoglauer. * All rights reserved. * * * This code implementation is the intellectual property of * Andreas Zoglauer. * * By copying, distributing or modifying the Program (or any work * based on the Program) you indicate your acceptance of this statement, * and all its terms. * */ // Standard #include <iostream> #include <string> #include <sstream> #include <csignal> #include <cstdlib> using namespace std; // ROOT #include <TROOT.h> #include <TMath.h> #include <TEnv.h> #include <TSystem.h> #include <TApplication.h> #include <TStyle.h> #include <TCanvas.h> #include <TH1.h> #include <TH2.h> // MEGAlib #include "MGlobal.h" #include "MStreams.h" #include "MGeometryRevan.h" #include "MDDetector.h" #include "MFileEventsEvta.h" #include "MDVolumeSequence.h" #include "MRERawEvent.h" #include "MRESE.h" /******************************************************************************/ class PolAnalyzer { public: /// Default constructor PolAnalyzer(); /// Default destructor ~PolAnalyzer(); /// Parse the command line bool ParseCommandLine(int argc, char** argv); /// Analyze what eveer needs to be analyzed... bool Analyze(); /// Interrupt the analysis void Interrupt() { m_Interrupt = true; } private: /// True, if the analysis needs to be interrupted bool m_Interrupt; /// The sim file name with polarization input TString m_PolFileName; /// The sim file name with unpolarization input TString m_NotPolFileName; /// The geometry file name TString m_GeometryFileName; /// The minimum energy double m_EnergyMin; /// The maximum energy double m_EnergyMax; }; /******************************************************************************/ double Modulation(double* x, double* par) { return par[0] + par[1]*cos(2*(x[0]-par[2] + 90.0)*c_Rad); }; /****************************************************************************** * Default constructor */ PolAnalyzer::PolAnalyzer() : m_Interrupt(false), m_EnergyMin(0), m_EnergyMax(1000000) { gStyle->SetPalette(1, 0); } /****************************************************************************** * Default destructor */ PolAnalyzer::~PolAnalyzer() { // Intentionally left blanck } /****************************************************************************** * Parse the command line */ bool PolAnalyzer::ParseCommandLine(int argc, char** argv) { ostringstream Usage; Usage<<endl; Usage<<" Usage: PolAnalyzer <options>"<<endl; Usage<<" General options:"<<endl; Usage<<" -p: sim file name with polarized data"<<endl; Usage<<" -u: sim file name with UN-polarized data"<<endl; Usage<<" -g: geometry file name"<<endl; Usage<<" -e: energy min, energy max"<<endl; Usage<<" -h: print this help"<<endl; Usage<<endl; string Option; // Check for help for (int i = 1; i < argc; i++) { Option = argv[i]; if (Option == "-h" || Option == "--help" || Option == "?" || Option == "-?") { cout<<Usage.str()<<endl; return false; } } // Now parse the command line options: for (int i = 1; i < argc; i++) { Option = argv[i]; // First check if each option has sufficient arguments: // Single argument if (Option == "-p" || Option == "-u" || Option == "-g") { if (!((argc > i+1) && (argv[i+1][0] != '-' || isalpha(argv[i+1][1]) == 0))){ cout<<"Error: Option "<<argv[i][1]<<" needs a second argument!"<<endl; cout<<Usage.str()<<endl; return false; } } // Multiple arguments template else if (Option == "-e") { if (!((argc > i+2) && (argv[i+1][0] != '-' || isalpha(argv[i+1][1]) == 0) && (argv[i+2][0] != '-' || isalpha(argv[i+2][1]) == 0))){ cout<<"Error: Option "<<argv[i][1]<<" needs two arguments!"<<endl; cout<<Usage.str()<<endl; return false; } } // Then fulfill the options: if (Option == "-p") { m_PolFileName = argv[++i]; cout<<"Accepting file name with polarized data: "<<m_PolFileName<<endl; } else if (Option == "-u") { m_NotPolFileName = argv[++i]; cout<<"Accepting file name with UN-polarized data: "<<m_NotPolFileName<<endl; } else if (Option == "-g") { m_GeometryFileName = argv[++i]; cout<<"Accepting geometry file name: "<<m_GeometryFileName<<endl; } else if (Option == "-e") { m_EnergyMin = atof(argv[++i]); m_EnergyMax = atof(argv[++i]); cout<<"Accepting energy limits: "<<m_EnergyMin<<" & " <<m_EnergyMax<<endl; } else { cout<<"Error: Unknown option \""<<Option<<"\"!"<<endl; cout<<Usage.str()<<endl; return false; } } if (m_PolFileName == "") { cout<<"Error: Please give a file name!"<<endl; return false; } if (m_GeometryFileName == "") { cout<<"Error: Please give a geometry file name!"<<endl; return false; } return true; } /****************************************************************************** * Do whatever analysis is necessary */ bool PolAnalyzer::Analyze() { if (m_Interrupt == true) return false; // Load geometry: MGeometryRevan Geometry; if (Geometry.ScanSetupFile(m_GeometryFileName.Data()) == true) { cout<<"Geometry "<<Geometry.GetName()<<" loaded!"<<endl; Geometry.ActivateNoising(false); Geometry.SetGlobalFailureRate(0.0); } else { cout<<"Loading of geometry "<<Geometry.GetName()<<" failed!!"<<endl; return false; } TH1D* SpectralHist = new TH1D("Spectrum", "Spectrum", 100, m_EnergyMin, m_EnergyMax); SpectralHist->SetXTitle("Energy in keV"); SpectralHist->SetYTitle("counts"); int PolBins = 90; TH1D* PolAzimuthHist = new TH1D("AzimuthalPol", "Azimuthal scatter angle distribution of polarized data", PolBins, -180.0, 180); PolAzimuthHist->SetXTitle("Azimuthal scatter angle in degree"); PolAzimuthHist->SetYTitle("counts"); PolAzimuthHist->SetMinimum(0); TH1D* NotPolAzimuthHist = new TH1D("AzimuthalNotPol", "Azimuthal scatter angle distribution of UN-polarized data", PolBins, -180.0, 180); NotPolAzimuthHist->SetXTitle("Azimuthal scatter angle in degree"); NotPolAzimuthHist->SetYTitle("counts"); NotPolAzimuthHist->SetMinimum(0); TH1D* CorrectedAzimuthHist = new TH1D("CorrectedPolarizationSignature", "Corrected polarization signature", PolBins, -180.0, 180); CorrectedAzimuthHist->SetXTitle("Azimuthal scatter angle in degree"); CorrectedAzimuthHist->SetYTitle("corrected counts"); CorrectedAzimuthHist->SetMinimum(0); MRERawEvent* Event = 0; // Open the polarized file MFileEventsEvta PolData(&Geometry); if (PolData.Open(m_PolFileName.Data()) == false) { mlog<<"Unable to open file "<<m_PolFileName<<endl; return false; } while ((Event = PolData.GetNextEvent()) != 0) { // Determine the energy deposit in CZT: int NHits = 0; double Energy = 0.0; MVector WeightedPos; for (int r = 0; r < Event->GetNRESEs(); ++r) { if (Event->GetRESEAt(r)->GetDetector() == 8) { ++NHits; Energy += Event->GetRESEAt(r)->GetEnergy(); WeightedPos += Event->GetRESEAt(r)->GetPosition()*Event->GetRESEAt(r)->GetEnergy(); } } if (NHits > 0) { if (Energy > m_EnergyMin && Energy < m_EnergyMax) { WeightedPos[0] /= NHits; WeightedPos[1] /= NHits; WeightedPos[2] /= NHits; double Azimuth = WeightedPos.Phi(); SpectralHist->Fill(Energy); PolAzimuthHist->Fill(Azimuth*c_Deg); } } delete Event; } // Open the polarized file MFileEventsEvta NotPolData(&Geometry); if (NotPolData.Open(m_NotPolFileName.Data()) == false) { mlog<<"Unable to open file "<<m_NotPolFileName<<endl; return false; } while ((Event = NotPolData.GetNextEvent()) != 0) { // Determine the energy deposit in CZT: int NHits = 0; double Energy = 0.0; MVector WeightedPos; for (int r = 0; r < Event->GetNRESEs(); ++r) { if (Event->GetRESEAt(r)->GetDetector() == 8) { ++NHits; Energy += Event->GetRESEAt(r)->GetEnergy(); WeightedPos += Event->GetRESEAt(r)->GetPosition()*Event->GetRESEAt(r)->GetEnergy(); } } if (NHits > 0) { if (Energy > m_EnergyMin && Energy < m_EnergyMax) { WeightedPos[0] /= NHits; WeightedPos[1] /= NHits; WeightedPos[2] /= NHits; double Azimuth = WeightedPos.Phi(); SpectralHist->Fill(Energy); NotPolAzimuthHist->Fill(Azimuth*c_Deg); } } delete Event; } // Normalize both to counts/deg: for (int b = 1; b <= PolAzimuthHist->GetNbinsX(); ++b) { if (PolAzimuthHist->GetBinContent(b) == 0) { mgui<<"You don't have enough statistics: Some bins are zero!"<<endl; return false; } PolAzimuthHist->SetBinContent(b, PolAzimuthHist->GetBinContent(b)/PolAzimuthHist->GetBinWidth(b)); } for (int b = 1; b <= NotPolAzimuthHist->GetNbinsX(); ++b) { if (NotPolAzimuthHist->GetBinContent(b) == 0) { mgui<<"You don't have enough statistics: Some bins are zero!"<<endl; return false; } NotPolAzimuthHist->SetBinContent(b, NotPolAzimuthHist->GetBinContent(b)/NotPolAzimuthHist->GetBinWidth(b)); } // Correct the image: double Mean = PolAzimuthHist->Integral()/CorrectedAzimuthHist->GetNbinsX(); // The scaling is necessary, since we cannot assume that pol and background have been measured for exactly the same time... Mean *= NotPolAzimuthHist->Integral()/PolAzimuthHist->Integral(); for (int b = 1; b <= CorrectedAzimuthHist->GetNbinsX(); ++b) { CorrectedAzimuthHist->SetBinContent(b, PolAzimuthHist->GetBinContent(b)/NotPolAzimuthHist->GetBinContent(b)*Mean); } /* TCanvas* SpectralCanvas = new TCanvas(); SpectralCanvas->cd(); SpectralHist->Draw(); SpectralCanvas->Update(); TCanvas* PolAzimuthCanvas = new TCanvas(); PolAzimuthCanvas->cd(); PolAzimuthHist->Draw(); PolAzimuthCanvas->Update(); TCanvas* NotPolAzimuthCanvas = new TCanvas(); NotPolAzimuthCanvas->cd(); NotPolAzimuthHist->Draw(); NotPolAzimuthCanvas->Update(); */ // Try to fit a cosinus TCanvas* CorrectedAzimuthCanvas = new TCanvas(); CorrectedAzimuthCanvas->cd(); TF1* Lin = new TF1("LinearModulation", "pol0", -180*0.99, 180*0.99); CorrectedAzimuthHist->Fit(Lin, "RQFI"); TF1* Mod = new TF1("Modulation", Modulation, -180*0.99, 180*0.99, 3); Mod->SetParNames("Offset (#)", "Scale (#)", "Shift (deg)"); Mod->SetParameters(Lin->GetParameter(0), 0.5, 0); Mod->SetParLimits(1, 0, 10000000); Mod->SetParLimits(2, -200, 200); CorrectedAzimuthHist->Fit(Mod, "RQ"); CorrectedAzimuthHist->Draw(); CorrectedAzimuthCanvas->Update(); double Modulation = fabs(Mod->GetParameter(1)/Mod->GetParameter(0)); double ModulationError = sqrt((Mod->GetParError(1)*Mod->GetParError(1))/(Mod->GetParameter(0)*Mod->GetParameter(0)) + (Mod->GetParError(0)*Mod->GetParError(0)*Mod->GetParameter(1)*Mod->GetParameter(1))/ (Mod->GetParameter(0)*Mod->GetParameter(0)*Mod->GetParameter(0)*Mod->GetParameter(0))); double PolarizationAngle = Mod->GetParameter(2); double PolarizationAngleError = Mod->GetParError(2); while (PolarizationAngle < 0) PolarizationAngle += 180; while (PolarizationAngle > 180) PolarizationAngle -= 180; mout<<endl; mout<<"Polarization analysis:"<<endl; mout<<endl; mout<<"Modulation: "<<Modulation<<"+-"<<ModulationError<<endl; mout<<"Polarization angle: ("<<PolarizationAngle<<"+-"<<PolarizationAngleError<<") deg"<<endl; mout<<endl; CorrectedAzimuthHist->Draw(); CorrectedAzimuthCanvas->Update(); return true; } /******************************************************************************/ PolAnalyzer* g_Prg = 0; int g_NInterruptCatches = 1; /******************************************************************************/ /****************************************************************************** * Called when an interrupt signal is flagged * All catched signals lead to a well defined exit of the program */ void CatchSignal(int a) { if (g_Prg != 0 && g_NInterruptCatches-- > 0) { cout<<"Catched signal Ctrl-C (ID="<<a<<"):"<<endl; g_Prg->Interrupt(); } else { abort(); } } /****************************************************************************** * Main program */ int main(int argc, char** argv) { // Catch a user interupt for graceful shutdown // signal(SIGINT, CatchSignal); // Initialize global MEGALIB variables, especially mgui, etc. MGlobal::Initialize(); TApplication PolAnalyzerApp("PolAnalyzerApp", 0, 0); g_Prg = new PolAnalyzer(); if (g_Prg->ParseCommandLine(argc, argv) == false) { cerr<<"Error during parsing of command line!"<<endl; return -1; } if (g_Prg->Analyze() == false) { cerr<<"Error during analysis!"<<endl; return -2; } PolAnalyzerApp.Run(); cout<<"Program exited normally!"<<endl; return 0; } /* * Cosima: the end... ******************************************************************************/
[ "andreas@megalibtoolkit.com" ]
andreas@megalibtoolkit.com
fd385161ae28adbbb1e9172134478351be102639
4442c37280e426d963304e5863cb25c96fff9e2a
/include/cefal/instances/monoid/with_functions.h
f1bb3877379a70e3010d2f2bd7b989a3bd4adf40
[ "BSD-3-Clause" ]
permissive
codereport/cefal
2f2cee47897636dab2fc391492e5e66fd67d9d1b
e5b37ffff77d9b9a147c7aa6e3bb8d64b77ed212
refs/heads/master
2021-05-19T16:24:21.738435
2020-03-31T23:55:01
2020-03-31T23:55:01
252,025,749
0
0
BSD-3-Clause
2020-03-31T23:53:50
2020-03-31T23:53:49
null
UTF-8
C++
false
false
2,439
h
/* Copyright 2020, Dennis Kormalev * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holders nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #pragma once #include "cefal/common.h" #include "cefal/monoid.h" #include <algorithm> #include <type_traits> namespace cefal::instances { namespace detail { template <typename T> struct MonoidFromFunctionsExists { using type = T; }; } // namespace detail template <detail::HasMonoidMethods T> struct Monoid<T> { static T empty() { return T::empty(); } template <typename T1, typename T2> static T append(T1&& left, T2&& right) { static_assert(std::is_same_v<std::remove_cvref_t<T1>, T>, "Argument type should be the same as monoid"); static_assert(std::is_same_v<std::remove_cvref_t<T2>, T> || std::is_same_v<std::remove_cvref_t<T2>, helpers::SingletonFrom<T>>, "Argument type should be the same as monoid"); return std::forward<T1>(left).append(std::forward<T2>(right)); } }; } // namespace cefal::instances
[ "kormalev.denis@gmail.com" ]
kormalev.denis@gmail.com
1fb2e6d94177f241f5aacd2471c9f4865a884345
6868bb166c3a3e6e3e2ce0e6f7a9aef50ef0f645
/jni/Rule_Implementor/Binary_Filter_Specification.h
553d0a443a9b4802d9b318ff26bed26e85e69b68
[]
no_license
JDRiley/ContactWrangler
6a110cf2e784f4c79668bdfd1f4be913fd62b5c9
fc384452c3affa79917cbed328173b7775c6b102
refs/heads/master
2020-12-11T04:12:38.538444
2015-03-19T20:29:26
2015-03-19T20:29:26
19,506,278
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
h
#ifndef BINARY_FILTER_SPECIFICATION_H #define BINARY_FILTER_SPECIFICATION_H #include "Filter_Specification.h" namespace jomike{ class Binary_Filter_Specification : public Filter_Specification{ public: Binary_Filter_Specification( Filter_Specification* i_left_filter, Filter_Specification* i_right_filter); //Deleting Constructors and Assignment Operators Binary_Filter_Specification(const Binary_Filter_Specification& irk_src); Binary_Filter_Specification(Binary_Filter_Specification&& irv_src); Binary_Filter_Specification& operator=(const Binary_Filter_Specification&) = delete; Binary_Filter_Specification& operator=(Binary_Filter_Specification&&) = delete; Binary_Filter_Specification* get_copy()const override = 0; Binary_Filter_Specification* move_copy()override = 0; protected: Filter_Specification& left_filter(); const Filter_Specification& left_filter()const; Filter_Specification& right_filter(); const Filter_Specification& right_filter()const; private: Filter_Specification* M_left_filter; Filter_Specification* M_right_filter; }; } #endif //BINARY_FILTER_SPECIFICATION_H
[ "jilesione@gmail.com" ]
jilesione@gmail.com
25781c6c16dfa887cc5a9527a529594fe89fb143
6f1321785ead226a5e5fef938ce61f902fe4d5f5
/AC/316.cxx
8e39a18d8f890b94733e9e00737a3a4cbc1ddeda
[]
no_license
ichoyjx/SGU
ac8cc0d4d69bea1315d0169e39357064c325cc72
51ddd2d84168e41c98ab1d7e39a00f6079f393a7
refs/heads/master
2021-01-23T13:48:45.614234
2014-02-20T06:12:18
2014-02-20T06:12:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
772
cxx
#include <iostream> using namespace std; struct tank { int _hit_points; int _score_points; }; int main() { int N, M; cin >> N >> M ; tank t[N]; int i; for (i=0; i<N; i++) { t[i]._hit_points = 100; t[i]._score_points = 0; } for (i=0; i<M; i++) { int shots, hits; cin >> shots >> hits; shots--; hits--; if (t[shots]._hit_points > 0) { if (t[hits]._hit_points > 0) { t[shots]._score_points += 3; } t[hits]._hit_points -= 8; } } for (i=0; i<N; i++) { if (t[i]._hit_points > 0) { cout << t[i]._hit_points << " " << (t[i]._score_points) + (t[i]._hit_points /2) << endl ; } else { cout << t[i]._hit_points << " " << (t[i]._score_points) << endl; } } return 0; }
[ "brianyang1106@gmail.com" ]
brianyang1106@gmail.com
2f672054055474c674eb962a4b214a6abb86406a
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/core/dom/idle_deadline.cc
371bd32be33fd2eadd0069cb8e45ce77baaabdb4
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
1,096
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/dom/idle_deadline.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/core/timing/performance.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" #include "third_party/blink/renderer/platform/wtf/time.h" namespace blink { IdleDeadline::IdleDeadline(double deadline_seconds, CallbackType callback_type) : deadline_seconds_(deadline_seconds), callback_type_(callback_type) {} double IdleDeadline::timeRemaining() const { double time_remaining = deadline_seconds_ - CurrentTimeTicksInSeconds(); if (time_remaining < 0) { return 0; } else if (Platform::Current() ->CurrentThread() ->Scheduler() ->ShouldYieldForHighPriorityWork()) { return 0; } return 1000.0 * Performance::ClampTimeResolution(time_remaining); } } // namespace blink
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
04381473185ec77874ed0f2d4c5dfe37bee86f9e
b6ff5e342f3675087d2704199bb5a46362b5fc20
/1GI/S2/Programmation Orienté Objet en C++/Issam/Les ensembles/main.cpp
8b2c64212e93788693188d02fb50a4bbd08d3046
[]
no_license
Ssouh/EHTP
75f5071282a1b0ed500d5c27e73b514fefe7af61
96558e59e398f652ae2e8a560b9dcd4ee3e8c6a8
refs/heads/main
2023-03-14T11:56:46.424726
2021-03-04T09:49:05
2021-03-04T09:49:05
330,687,825
0
0
null
2021-01-24T18:02:23
2021-01-18T14:15:22
null
UTF-8
C++
false
false
325
cpp
#include <iostream> #include "UnEnsemble.h" using namespace std; int main() { UnEnsemble N; N.ajoute(5); N.ajoute(3); N.ajoute(1); N.ajoute(4); UnEnsemble Q; Q.ajoute(1); Q.ajoute(3); Q.ajoute(8); N.afficheToi(); Q.afficheToi(); cout << Q.estInclus(N) ; return 0; }
[ "safi-bigg@live.fr" ]
safi-bigg@live.fr
a0edb6635e995c317c84c656edf80166900e2a81
03052fe27cfc8758c078cbbf23dd6b0ea5c87e9c
/Analog_Joystick/PC_Gameport_Analog_Joystick.ino
0909a9f9d660c8cb6704664d9bb2f31d43cf0f30
[]
no_license
mrouillard/Arduino-PC-Gameport-HID
d741b4fbe1b0976c494abb1b068e262ed7fb1b73
56b31685ab2dd256ae458f984f27da2856445526
refs/heads/master
2021-05-28T10:21:17.625050
2015-03-18T07:08:50
2015-03-18T07:08:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,752
ino
// Settings #define ENABLE_DEBUG; // Pins const int button0 = 7; const int button1 = 6; const int button2 = 5; const int button3 = 4; const int axis0 = A0; const int axis1 = A1; const int axis2 = A2; const int axis3 = A3; // Analog to digital const int AXIS_MIN = 550; const int AXIS_MAX = 1023; const int AXIS_NUL = 720; // Joestick JoyState_t joyStick; // Ugly vars int buttonState0= 0; int buttonState1= 0; int buttonState2= 0; int buttonState3= 0; int buttonState4= 0; int buttonState5= 0; int buttonState6= 0; int buttonState7= 0; // Setup void setup() { Serial.begin(9600); // pull up pinMode(button0, INPUT_PULLUP); pinMode(button1, INPUT_PULLUP); pinMode(button2, INPUT_PULLUP); pinMode(button3, INPUT_PULLUP); } void loop(){ // read data buttonState0 = !digitalRead(button0); buttonState1 = !digitalRead(button1); buttonState2 = !digitalRead(button2); buttonState3 = !digitalRead(button3); buttonState4 = analogRead(axis0); buttonState5 = analogRead(axis1); buttonState6 = analogRead(axis2); buttonState7 = analogRead(axis3); #ifdef ENABLE_DEBUG Serial.print(buttonState0); Serial.print(buttonState1); Serial.print(buttonState2); Serial.print(buttonState3); Serial.print(" "); Serial.print(buttonState4); Serial.print(" "); Serial.print(buttonState5); Serial.print(" "); Serial.print(buttonState6); Serial.print(" "); Serial.print(buttonState7); Serial.println(""); #endif float tempState = 127; if(buttonState4>AXIS_NUL){ tempState = 127+(AXIS_NUL - buttonState4)/2; } else{ tempState =127+ (AXIS_NUL - buttonState4)/1; } tempState = tempState<0?0:tempState; tempState = tempState>255?255:tempState; joyStick.xAxis = tempState; tempState = 127; if(buttonState5>AXIS_NUL){ tempState = 127+(AXIS_NUL - buttonState5)/2; } else{ tempState =127+ (AXIS_NUL - buttonState5)/1; } tempState = tempState<0?0:tempState; tempState = tempState>255?255:tempState; joyStick.yAxis = tempState; tempState = buttonState6 - AXIS_MIN; tempState = tempState<0?0:tempState; tempState = (256 *tempState)/ (float)(AXIS_MAX-AXIS_MIN); tempState = tempState>255?255:tempState; joyStick.rudder = tempState; tempState = buttonState7 - AXIS_MIN; tempState = tempState<0?0:tempState; tempState = (256 *tempState)/ (float)(AXIS_MAX-AXIS_MIN); tempState = abs(tempState - 256); tempState = tempState<0?0:tempState; tempState = tempState>255?255:tempState; joyStick.throttle = tempState; // all another axis set to zero position joyStick.zAxis = 127; joyStick.xRotAxis = 127; joyStick.yRotAxis = 127; joyStick.zRotAxis = 127; //joyStick.throttle = 127; //joyStick.rudder = 127; // hat connected to 4 key if(buttonState0 && buttonState1 && buttonState2 && buttonState3){ joyStick.hatSw1 = 0; } else if(buttonState0 && buttonState1 && !buttonState2 && buttonState3){ joyStick.hatSw1 = 4; } else if(buttonState0 && buttonState1 && !buttonState2 && !buttonState3){ joyStick.hatSw1 = 6; } else if(buttonState0 && buttonState1 && buttonState2 && !buttonState3){ joyStick.hatSw1 = 2; } else{ joyStick.hatSw1 = 8; // buttons connects joyStick.buttons = 0; // digital buttons to mask if(buttonState0){ joyStick.buttons = joyStick.buttons | 1; } if(buttonState1){ joyStick.buttons = joyStick.buttons | 2; } if(buttonState2){ joyStick.buttons = joyStick.buttons | 4; } if(buttonState3){ joyStick.buttons = joyStick.buttons | 8; } } // and hat2 to center joyStick.hatSw2 = 8; Joystick.setState(&joyStick); delay(1); }
[ "vladimir.bandurka@onix-systems.com" ]
vladimir.bandurka@onix-systems.com
777aa5f04757a4f7f5adb47be60b54c105bd15a2
428989cb9837b6fedeb95e4fcc0a89f705542b24
/erle/ros2_ws/install/include/rcl_interfaces/msg/dds_opensplice/ParameterDescriptor_Dcps.cpp
eed8fe2166585a92ec10dcb8b67dcd93535017aa
[]
no_license
swift-nav/ros_rover
70406572cfcf413ce13cf6e6b47a43d5298d64fc
308f10114b35c70b933ee2a47be342e6c2f2887a
refs/heads/master
2020-04-14T22:51:38.911378
2016-07-08T21:44:22
2016-07-08T21:44:22
60,873,336
1
2
null
null
null
null
UTF-8
C++
false
false
136
cpp
/home/erle/ros2_ws/build/rcl_interfaces/rosidl_typesupport_opensplice_cpp/rcl_interfaces/msg/dds_opensplice/ParameterDescriptor_Dcps.cpp
[ "igdoty@swiftnav.com" ]
igdoty@swiftnav.com
60216b6a627662dbe861c275a584eee4b80d9b6d
e1d4d7dbe919bae1ae4c022292197a576ab78db6
/include/physics/gravity.h
405b7076218141e21922118553ee0209dabded02
[ "MIT" ]
permissive
blurrybloop/wdgs
1aee2a9268a57deffe25620cac5c9ebec325c9bb
439e487a03ec9e534ae9e9c4b4a962a69ff3c6cc
refs/heads/master
2020-07-02T17:09:46.321544
2019-09-28T10:38:30
2019-09-29T07:29:59
74,293,458
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,742
h
#ifndef _WDGS_PHYSICS_GRAVITY_H #define _WDGS_PHYSICS_GRAVITY_H #include "memmng.h" namespace WDGS { namespace Physics { struct MaterialPoint { glm::dvec3 worldPosition; //позиция в мировых координатах glm::dvec3 worldVelocity; //скорость в мировых координатах double mass; //масса }; const int MP_LENGTH = sizeof(MaterialPoint) / sizeof(double); class GravityController { DECLARE_MEMMNG(GravityController) public: static const double gravityConst; void AddMP(MaterialPoint* mp); void RemoveMP(MaterialPoint* mp); void Refresh(double step, double timestep); protected: double currentStep; double prevTimestep; GravityController() { currentStep = DBL_MAX; prevTimestep = 0.0; } //Вектор производных для закона всемирного притяжения static void Equations(std::vector<MaterialPoint*>& objs, size_t index, std::vector<double>& flow); std::vector<std::vector<double>> k[4]; std::vector<MaterialPoint*> buf0, buf1, buf2, buf3; std::vector<std::vector<double>> scale; std::vector<std::vector<double>> Delta; void RK4Step(std::vector<MaterialPoint*>& in, std::vector<MaterialPoint*>& out, double dt // fixed time step ); double RK4AdaptiveStep(std::vector<MaterialPoint*>& in,// returns adapted time step std::vector<MaterialPoint*>& out, double dt, // initial time step double& adt, double accuracy = 1e-6); public: ~GravityController() { for (size_t i = 0; i < buf0.size(); ++i) { delete buf1[i]; delete buf2[i]; delete buf3[i]; } } }; } } #endif
[ "Стас@СТАС-ПК" ]
Стас@СТАС-ПК
e35e072e5e7d351d4b462bc03145351920e17a74
f267871d2ecf907d1d1e604be01d056f5ef42754
/Player.h
e457ca57e39b05d5df40f247cec99bbc88d6ecc0
[]
no_license
cheonjeong/-TEAM-Visual_Bat
0b90bb22eab67f6e750639d36fc46070770ad94f
43ac529e3c599dfadcca4021831e06845803a7e8
refs/heads/master
2020-08-04T04:30:18.449179
2019-10-12T08:42:59
2019-10-12T08:42:59
212,005,463
0
0
null
2019-10-01T03:28:45
2019-10-01T03:28:45
null
UTF-8
C++
false
false
392
h
#pragma once #include "Dynamic.h" class CPlayer : public CDynamic { public: CPlayer(); ~CPlayer(); private: D3DXVECTOR3 m_vMousePos; float m_fCamDistance; public: void KeyCheck(); void MouseCheck(); void SetCameraPos(); public: virtual void SetContantTable(); public: virtual HRESULT Initialize(); virtual void Progress(); virtual void Render(); virtual void Release() ; };
[ "amorigeta+git@gmail.com" ]
amorigeta+git@gmail.com
0d6173028ed29d250e2a6a91ae546ad5bdc843b3
07e7958bb57d6caa25225c6bc6db2194daea671c
/spree-master/project2/Library/QHTM_FullSource1967/components/debughlp/trace.cpp
c489fa4466beef00dbfc790922a0eaa7649dc4ce
[]
no_license
pedromela/9d
34eb86d1acc863586c8e7338fc5f5c6ccaaacaa9
c65024fba16eca04b4eec897d312eb295ce60cfa
refs/heads/master
2021-07-21T07:34:18.570081
2017-10-30T17:58:45
2017-10-30T17:58:45
108,886,922
0
1
null
null
null
null
UTF-8
C++
false
false
5,930
cpp
/*---------------------------------------------------------------------- Copyright (c) 1998-present Russ Freeman. All Rights Reserved. Web site: http://www.gipsysoft.com/ This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1) This source code may not be distributed as part of a commercial library without written permission from the author 2) The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is requested but not required. 3) Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4) Altered source is encouraged to be submitted back to the original author so it can be shared with the community. Please share your changes. Don't make me use GPL! 5) This notice may not be removed or altered from any source distribution. 6) If you have any confusion then ask File: Trace.cpp Owner: russf@gipsysoft.com Purpose: TRACE handling function. ----------------------------------------------------------------------*/ #include "stdafx.h" #include <WinHelper.h> #include "DebugHlp.h" static WinHelper::CCriticalSection g_sect; class CTraceLock: private WinHelper::CCriticalSection::CLock // // Simple lock class for the critcal section { public: inline CTraceLock() : WinHelper::CCriticalSection::CLock( g_sect ) { } private: CTraceLock( const CTraceLock &); CTraceLock& operator =( const CTraceLock &); }; static char g_szLogFileName[ MAX_PATH + MAX_PATH ] = {0}; void DebugTraceToFileA( LPCSTR pcszFilename ) { strcpy( g_szLogFileName, pcszFilename ); } void DebugTraceToFileW( LPCWSTR pcszFilename ) { WideCharToMultiByte( CP_ACP, 0, pcszFilename, -1, g_szLogFileName, MAX_PATH + MAX_PATH, NULL, NULL ); } void WriteToLogFileA( LPCSTR pcsz, bool bIncludeDateTime, bool bIncludeCRLF ) { if( g_szLogFileName[ 0 ] ) { int nRetries = 40; HANDLE h = INVALID_HANDLE_VALUE; while( ( h = CreateFileA( g_szLogFileName, GENERIC_WRITE | GENERIC_READ ,FILE_SHARE_READ ,NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL ) ) == INVALID_HANDLE_VALUE && nRetries-- ) { Sleep( 50 ); } if( h == INVALID_HANDLE_VALUE ) return; SetFilePointer( h, 0, 0, FILE_END ); DWORD dwWrite; if( bIncludeDateTime ) { SYSTEMTIME st; GetSystemTime( &st ); char szDateBuffer[ 256 ]; (void)WriteFile( h, szDateBuffer, sprintf( szDateBuffer, "%02d-%02d-%04d\t%02d:%02d:%02d\t", st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond ), &dwWrite, NULL ); } (void)WriteFile( h, pcsz, strlen( pcsz ), &dwWrite, NULL ); if( bIncludeCRLF ) { (void)WriteFile( h, "\r\n", 2, &dwWrite, NULL ); } CloseHandle( h ); } } void _cdecl DebugTraceLineAndFileA( LPCSTR pcszFilename, int nLine ) { CTraceLock lock; OutputDebugStringA( pcszFilename ); char szLineNumber[30] = "("; ltoa( nLine, szLineNumber + 1, 10 ); strcat( szLineNumber , ") : " ); OutputDebugStringA( szLineNumber ); } void _cdecl DebugTraceA( LPCSTR pcszFormat, ... ) { CTraceLock lock; va_list marker; va_start( marker, pcszFormat ); LPSTR pszBuffer = DBGH_vmalprintfA( pcszFormat, marker ); OutputDebugStringA( pszBuffer ); if( g_szLogFileName[0] ) { WriteToLogFileA( pszBuffer, true, false ); } free( pszBuffer ); va_end( marker ); } void _cdecl DebugTraceLineAndFileW( LPCWSTR pcszFilename, int nLine ) { CTraceLock lock; OutputDebugStringW( pcszFilename ); WCHAR szLineNumber[30] = L"("; _ltow( nLine, szLineNumber + 1, 10 ); wcscat( szLineNumber , L") : " ); OutputDebugStringW( szLineNumber ); } void _cdecl DebugTraceW( LPCWSTR pcszFormat, ... ) { CTraceLock lock; va_list marker; va_start( marker, pcszFormat ); LPWSTR pszBuffer = DBGH_vmalprintfW( pcszFormat, marker ); OutputDebugStringW( pszBuffer ); if( g_szLogFileName[0] ) { const UINT uLength = wcslen( pszBuffer ); char *psz = static_cast<char*>( malloc( uLength + 1 ) ); WideCharToMultiByte( CP_ACP, 0, pszBuffer, uLength, psz, uLength + 1, NULL, NULL ); WriteToLogFileA( psz, true, false ); free( psz ); } free( pszBuffer ); va_end( marker ); } void _cdecl DebugTraceMemory( LPVOID lp, UINT uSize ) { if( ::IsBadReadPtr( lp, uSize ) ) { TRACE( _T("Can't read memory for DebugTraceMemory\n") ); } else { char *pChar = (char *)lp; TCHAR szBufferText[ 256 ] = _T(""); TCHAR szBufferHex[ 256 ] = _T(""); TCHAR szHexChar[ 4 ]; wsprintf( szBufferText, _T("Memory dump of %d bytes at 0x%08x\r\n"), uSize, lp ); OutputDebugString( szBufferText ); szBufferText[ 0 ] = '\000'; CTraceLock lock; int nChars = 0; for( UINT u = 0; u < uSize; u++ ) { if( *pChar < 32 ) { _tcscat( szBufferText, _T(".") ); } else { TCHAR sz[ 2 ] = {*pChar, 0 }; _tcscat( szBufferText, sz ); } _tcscat( szBufferText, _T(" ") ); wsprintf( szHexChar, _T("%02x"), (unsigned char)(*pChar) ); _tcscat( szBufferHex, szHexChar ); _tcscat( szBufferHex, _T(" ") ); nChars++; if( nChars == 16 ) { nChars = 0; _tcscat( szBufferText, _T("\r\n") ); _tcscat( szBufferHex, _T("\r\n") ); OutputDebugString( szBufferText ); OutputDebugString( szBufferHex ); szBufferText[ 0 ] = szBufferHex[ 0 ] = 0; } pChar++; } if( nChars ) { _tcscat( szBufferText, _T("\r\n") ); _tcscat( szBufferHex, _T("\r\n") ); OutputDebugString( szBufferText ); OutputDebugString( szBufferHex ); szBufferText[ 0 ] = szBufferHex[ 0 ] = 0; } } }
[ "pedro.miguel.69@hotmail.com" ]
pedro.miguel.69@hotmail.com
fa952133dce1050992cd0cb2fa4968be68c95801
7d211617a1d20db4eac5e3f6e9b090786f22af29
/test/unit/winstl/time/test.unit.winstl.time.comparison_functions/implicit_link.cpp
888914d75fad4a52d56c7ae722370e1efd636576
[ "BSD-2-Clause" ]
permissive
synesissoftware/STLSoft-1.10-delta
b3f3f6f9b26527b9ea5a7e92b8ebfbdf381153fb
926617f5a3468d36861eadfbdc65823f77a90e62
refs/heads/master
2021-01-15T15:49:31.532263
2019-04-16T03:01:32
2019-04-16T03:01:32
42,432,619
3
1
null
null
null
null
UTF-8
C++
false
false
862
cpp
/* ///////////////////////////////////////////////////////////////////////// * File: implicit_link.cpp * * Purpose: Implicit link file for the test.unit.winstl.time.comparison_functions project. * * Created: 8th April 2014 * Updated: 8th April 2014 * * Status: Wizard-generated * * License: (Licensed under the Synesis Software Open License) * * Copyright (c) 2014, Synesis Software Pty Ltd. * All rights reserved. * * www: http://www.synesis.com.au/software * * ////////////////////////////////////////////////////////////////////// */ /* ///////////////////////////////////////////////////////////////////////// * Includes */ /* xTests Header Files */ #include <xtests/implicit_link.h> /* ///////////////////////////// end of file //////////////////////////// */
[ "matthew@synesis.com.au" ]
matthew@synesis.com.au
c6a493af7e1f9da24c0880f56d98b0f9a3de6a13
021d05847e6618f1e4c86ab462e1afe851fe8634
/homework_3.cpp
528bad8ddef8ddd3db8d36debc165d06b812cdc5
[]
no_license
yiyanglin0102/CS368
808a3f42e72de350961e6302ba373e9ef35d6304
07ef43fecdcb89d51ea3d47e357900afaea095ab
refs/heads/master
2022-03-06T23:53:24.880651
2019-10-10T06:02:30
2019-10-10T06:02:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,540
cpp
#include <iostream> #include <map> #include <vector> #include <set> #include <string> #include <time.h> // time #include <cstdlib> using namespace std; // don't change this function // purpose: prints a map of the cave to the console // input: the printable map a vector of strings // output: none - console output of the cave diagram void Print_Cave_Diagram(const vector<string> &cave_diagram){ for (auto s : cave_diagram) cout<<s <<endl; } // Implement these functions below // Do not change the function prototpyes void Initialize_Cave(map<vector<int>, set<string> > &cave); void Print_Square(map<vector<int>, set<string> > &cave); void Get_Cave_Diagram(map<vector<int>, set<string> > &cave, vector<string> &cave_diagram); // sample main function int main() { map<vector<int>, set<string> > cave; Initialize_Cave(cave); Print_Square(cave); vector<string> cave_diagram; Get_Cave_Diagram(cave, cave_diagram); Print_Cave_Diagram(cave_diagram); return 0; } // add the player, ladder, wumpus, pits, gold, stench, breeze to the map // input: // output: void Initialize_Cave(map<vector<int>, set<string> > &cave) { srand(time(NULL)); // place the "ladder" in row 1 column 1 cave[{1,1}].insert("ladder"); // place the "player" at the same location as the ladder cave[{1,1}].insert("player"); // place the "wumpus" - can't be in the same square as the ladder int random1 = 2+(rand()%3); int random2 = 2+(rand()%3); cave[{random1,random2}].insert("wumpus"); // place the 3 "pits" - can't be in the same square as the ladder, wumpus, or another pit int random3 = 2+(rand()%3); int random4 = 2+(rand()%3); int random5 = 2+(rand()%3); int random6 = 2+(rand()%3); int random7 = 2+(rand()%3); int random8 = 2+(rand()%3); while(random1 == random3 && random2 == random4) { random3 = 2+(rand()%3); random4 = 2+(rand()%3); } cave[{random3,random4}].insert("pit"); while(random3 == random5 && random4 == random6) { random5 = 2+(rand()%3); random6 = 2+(rand()%3); } cave[{random5,random6}].insert("pit"); while(random5 == random7 && random6 == random8) { random7 = 2+(rand()%3); random8 = 2+(rand()%3); } cave[{random7,random8}].insert("pit"); // place the "gold" - can't be in the same square as a pit or the ladder int random9 = 2+(rand()%3); int random10 = 2+(rand()%3); while((random9 == random3 && random10 == random4) || (random9 == random5 && random10 == random6) || (random9 == random7 && random10 == random8)) { random9 = 2+(rand()%3); random10 = 2+(rand()%3); } cave[{random9,random10}].insert("gold"); // place the "stench" squares to the left, right, up, and down from the wumpus cave[{random1,random2+1}].insert("stench"); cave[{random1,random2-1}].insert("stench"); cave[{random1-1,random2}].insert("stench"); cave[{random1+1,random2}].insert("stench"); // place the "breeze" squares to the left, right, up, and down from the three pits cave[{random3,random4+1}].insert("breeze"); cave[{random3,random4-1}].insert("breeze"); cave[{random3-1,random4}].insert("breeze"); cave[{random3+1,random4}].insert("breeze"); cave[{random5,random6+1}].insert("breeze"); cave[{random5,random6-1}].insert("breeze"); cave[{random5-1,random6}].insert("breeze"); cave[{random5+1,random6}].insert("breeze"); cave[{random7,random8+1}].insert("breeze"); cave[{random7,random8-1}].insert("breeze"); cave[{random7-1,random8}].insert("breeze"); cave[{random7+1,random8}].insert("breeze"); } // print the contents of the square // input: // output: void Print_Square(map<vector<int>, set<string> > &cave) { for (int r=1; r<=4; r++) { for (int c=1; c<=4; c++) { cout << r<< ", "<< c << endl; cout << "This part of the cave contains" << endl; if(cave[{r,c}].empty() != false) { cout<<" nothing"<<endl<<endl; } if (cave[{r,c}].empty() == false) { for(set<string>::iterator it = cave[{r,c}].begin(); it != cave[{r,c}].end(); it++) { cout<<" "<<*it<<endl; } cout<<endl; } } } } // build a vector of strings where each string in the vector represents one row of the cave output // input: // output: void Get_Cave_Diagram(map<vector<int>, set<string> > &cave, vector<string> &cave_diagram) { int cell_rows = 5; int cell_columns = 11; int total_rows = cell_rows*4 + 1; int total_columns = cell_columns*4 + 1; // fill in with vertical cell divisions for (int r=0; r<total_rows; r++) { string row(total_columns, ' '); for (int c=0; c<total_columns; c+=cell_columns) { row[c] = '|'; } cave_diagram.push_back(row); } // udpate horizontal rows with '-' for (int i=0; i<total_rows; i+=cell_rows) { cave_diagram[i] = string(total_columns, '-'); } // update cell corners with '+' for (int r=0; r<total_rows; r+=cell_rows) { for (int c=0; c<total_columns; c+=cell_columns) { cave_diagram[r][c]='+'; } } // replace the part of the string with the cell contents for (int c=1; c<=4; c++) { for (int r=1; r<=4; r++) { for(set<string>::iterator it = cave[{r,c}].begin(); it != cave[{r,c}].end(); it++) { string word = *it; for(int i=0; i< word.length(); i++) { char letter = word.at(i); if(r == 1 && c == 1) { if(cave_diagram[2].at(3+i) != ' ') { cave_diagram[3].at(3+i) = letter; } else if(cave_diagram[1].at(3+i) != ' ') { cave_diagram[2].at(3+i) = letter; } else cave_diagram[1].at(3+i) = letter; } if(r == 1 && c == 2) { if(cave_diagram[2].at(14+i) != ' ') { cave_diagram[3].at(14+i) = letter; } else if(cave_diagram[1].at(14+i) != ' ') { cave_diagram[2].at(14+i) = letter; } else cave_diagram[1].at(14+i) = letter; } if(r == 1 && c == 3) { if(cave_diagram[2].at(25+i) != ' ') { cave_diagram[3].at(25+i) = letter; } else if(cave_diagram[1].at(25+i) != ' ') { cave_diagram[2].at(25+i) = letter; } else cave_diagram[1].at(25+i) = letter; } if(r == 1 && c == 4) { if(cave_diagram[2].at(36+i) != ' ') { cave_diagram[3].at(36+i) = letter; } else if(cave_diagram[1].at(36+i) != ' ') { cave_diagram[2].at(36+i) = letter; } else cave_diagram[1].at(36+i) = letter; } if(r == 2 && c == 1) { if(cave_diagram[7].at(3+i) != ' ') { cave_diagram[8].at(3+i) = letter; } else if(cave_diagram[6].at(3+i) != ' ') { cave_diagram[7].at(3+i) = letter; } else cave_diagram[6].at(3+i) = letter; } if(r == 2 && c == 2) { if(cave_diagram[7].at(14+i) != ' ') { cave_diagram[8].at(14+i) = letter; } else if(cave_diagram[6].at(14+i) != ' ') { cave_diagram[7].at(14+i) = letter; } else cave_diagram[6].at(14+i) = letter; } if(r == 2 && c == 3) { if(cave_diagram[7].at(25+i) != ' ') { cave_diagram[8].at(25+i) = letter; } else if(cave_diagram[6].at(25+i) != ' ') { cave_diagram[7].at(25+i) = letter; } else cave_diagram[6].at(25+i) = letter; } if(r == 2 && c == 4) { if(cave_diagram[7].at(36+i) != ' ') { cave_diagram[8].at(36+i) = letter; } else if(cave_diagram[6].at(36+i) != ' ') { cave_diagram[7].at(36+i) = letter; } else cave_diagram[6].at(36+i) = letter; } if(r == 3 && c == 1) { if(cave_diagram[12].at(3+i) != ' ') { cave_diagram[13].at(3+i) = letter; } else if(cave_diagram[11].at(3+i) != ' ') { cave_diagram[12].at(3+i) = letter; } else cave_diagram[11].at(3+i) = letter; } if(r == 3 && c == 2) { if(cave_diagram[12].at(14+i) != ' ') { cave_diagram[13].at(14+i) = letter; } else if(cave_diagram[11].at(14+i) != ' ') { cave_diagram[12].at(14+i) = letter; } else cave_diagram[11].at(14+i) = letter; } if(r == 3 && c == 3) { if(cave_diagram[12].at(25+i) != ' ') { cave_diagram[13].at(25+i) = letter; } else if(cave_diagram[11].at(25+i) != ' ') { cave_diagram[12].at(25+i) = letter; } else cave_diagram[11].at(25+i) = letter; } if(r == 3 && c == 4) { if(cave_diagram[12].at(36+i) != ' ') { cave_diagram[13].at(36+i) = letter; } else if(cave_diagram[11].at(36+i) != ' ') { cave_diagram[12].at(36+i) = letter; } else cave_diagram[11].at(36+i) = letter; } if(r == 4 && c == 1) { if(cave_diagram[17].at(3+i) != ' ') { cave_diagram[18].at(3+i) = letter; } else if(cave_diagram[16].at(3+i) != ' ') { cave_diagram[17].at(3+i) = letter; } else cave_diagram[16].at(3+i) = letter; } if(r == 4 && c == 2) { if(cave_diagram[17].at(14+i) != ' ') { cave_diagram[18].at(14+i) = letter; } else if(cave_diagram[16].at(14+i) != ' ') { cave_diagram[17].at(14+i) = letter; } else cave_diagram[16].at(14+i) = letter; } if(r == 4 && c == 3) { if(cave_diagram[17].at(25+i) != ' ') { cave_diagram[18].at(25+i) = letter; } else if(cave_diagram[16].at(25+i) != ' ') { cave_diagram[17].at(25+i) = letter; } else cave_diagram[16].at(25+i) = letter; } if(r == 4 && c == 4) { if(cave_diagram[17].at(36+i) != ' ') { cave_diagram[18].at(36+i) = letter; } else if(cave_diagram[16].at(36+i) != ' ') { cave_diagram[17].at(36+i) = letter; } else cave_diagram[16].at(36+i) = letter; } } } } } }
[ "yiyanglin@YiYang-Lins-MacBook.local" ]
yiyanglin@YiYang-Lins-MacBook.local
5c636125f4467c79b3db136276ae93dc4737f702
925afab438e3d3807161ff798e3f584d532ea012
/system/file.cc
9fd155609794ac80bf27c0461dbe64d2fe62259b
[ "MIT", "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
gm-archive/dejavu-llvm
dd9d7326df55bbf3add222b313b0dab3bac3ddd8
568dfa38f226a8994d0bfc07db2cdb466db10529
refs/heads/master
2022-01-09T19:00:29.163035
2015-09-06T03:04:35
2015-09-06T03:04:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
582
cc
#include <dejavu/system/file.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <cerrno> int file_buffer::open_file(const char *path) { int fd = open(path, O_RDONLY); if (fd == -1) return errno; struct stat s; if (fstat(fd, &s) == -1) { close(fd); return errno; } length = s.st_size; data = static_cast<char*>(mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0)); if (data == MAP_FAILED) { close(fd); return errno; } close(fd); return 0; } file_buffer::~file_buffer() { munmap(const_cast<char*>(data), length); }
[ "rpjohnst@gmail.com" ]
rpjohnst@gmail.com
7ba88dde6c449f8f2a026f99dab1cbf693db830a
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/hunk_2575.cpp
8d00fe10d060238aef5483701eeb6f2467f24e5e
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
131
cpp
{ fatal ("Not implemented"); } - -ConnectionDetail::ConnectionDetail() : me(), peer() -{ - fatal ("Not implemented"); -}
[ "993273596@qq.com" ]
993273596@qq.com
a928999c7301b228f5b130969744e1aad58784a3
55b48309b6dce51e477c88aaef14e30759fd72e0
/Examples/Sept03-Morning-Objects-Vector-Pointers/Card.cpp
5bbf12ab2e2e7dde9d54f9368dac669c3cad6bd0
[]
no_license
domfarolino/talaga-ds
0e80b04d60e0fd46c85515facd08138324169343
e5f0daff17bf3690937a81adf2a3a161dbf35a19
refs/heads/master
2021-01-11T00:08:15.378627
2015-11-20T03:05:39
2015-11-20T03:05:39
70,751,070
0
0
null
null
null
null
UTF-8
C++
false
false
319
cpp
#include <string> #include "Card.h" using namespace std; Card::Card(){ number = 7; suit = "Diamonds"; } Card::Card(int number, string suit){ this->number = number; // Note this->suit = suit; } // Getters string Card::getSuit() const{ return suit; } int Card::getNumber() const{ return number; }
[ "paul.talaga@uc.edu" ]
paul.talaga@uc.edu
f64d8edb42be1ec17ec2483db2de6706d4085060
a7585b991f397ff214b256b860c23786fd50a7ac
/01.Length_Of_The_Word.cpp
aab80ba769bf673eac718aee26bdbc9a049463ac
[]
no_license
nehapandey13/Cracking-Coding-Interview
1577bf6d057f2375ea2ce0272ea16a6e8cb41e29
fab81bbc4c051286efcefa0924523c8d6b2d1e61
refs/heads/master
2023-06-30T20:29:19.291836
2021-08-04T20:42:00
2021-08-04T20:42:00
392,818,168
1
0
null
null
null
null
UTF-8
C++
false
false
1,009
cpp
//Problem Statement /*Given a string s consists of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: Input: s = "Hello World" Output: 5 Example 2: Input: s = " fly me to the moon " Output: 4 */ //Solution 1 class Solution { public: int lengthOfLastWord(string s) { int count = 0; int l=s.size(); int i=0; while(i<l){ if(s[i]!=' '){ count++; i++; }else{ //Current character is a space while(i<l && s[i]==' ')i++; if(i==l){ // end of the string return count; } else{ count=0; } } } return count; }
[ "neha224229@gmail.com" ]
neha224229@gmail.com
d5f3f6cf839d7025a3d42ce2ca6eb31894dbeefc
bc16d26b3a1db2977b536dd370861e01921ee3e8
/dune/Utilities/SignalShapingServiceDUNE.h
26e68b9f63a6c993fc76090c6c7067a2bf689e2a
[]
no_license
jhugon/dunetpc
b6f5cb420492753b9d1890bcf526d26f7e425bb2
13f26ab523ff9e350f7e93a9d6e49302a2b48843
refs/heads/master
2020-04-12T09:41:08.977996
2016-09-02T00:34:26
2016-09-02T00:34:26
63,374,613
0
0
null
null
null
null
UTF-8
C++
false
false
7,785
h
/////////////////////////////////////////////////////////////////////// /// /// \file SignalShapingServiceDUNE.h /// /// \brief Service to provide microboone-specific signal shaping for /// simulation (convolution) and reconstruction (deconvolution). /// /// \author H. Greenlee (original class) /// /// This service inherits from SignalShaping and supplies /// microboone-specific configuration. It is intended that SimWire and /// CalWire modules will access this service. /// /// FCL parameters: /// /// FieldBins - Number of bins of field response. /// Col3DCorrection - 3D path length correction for collection plane. /// Ind3DCorrection - 3D path length correction for induction plane. /// ColFieldRespAmp - Collection field response amplitude. /// IndFieldRespAmp - Induction field response amplitude. /// ShapeTimeConst - Time constants for exponential shaping. /// ColFilter - Root parameterized collection plane filter function. /// ColFilterParams - Collection filter function parameters. /// IndFilter - Root parameterized induction plane filter function. /// IndFilterParams - Induction filter function parameters. /// //////////////////////////////////////////////////////////////////////// #ifndef SIGNALSHAPINGSERVICEDUNE_H #define SIGNALSHAPINGSERVICEDUNE_H #include <vector> #include "fhiclcpp/ParameterSet.h" #include "art/Framework/Services/Registry/ActivityRegistry.h" #include "art/Framework/Services/Registry/ServiceMacros.h" #include "lardata/Utilities/SignalShaping.h" #include "TF1.h" #include "TH1D.h" using DoubleVec = std::vector<double>; namespace util { class SignalShapingServiceDUNE { public: // Constructor, destructor. SignalShapingServiceDUNE(const fhicl::ParameterSet& pset, art::ActivityRegistry& reg); ~SignalShapingServiceDUNE(); // Update configuration parameters. void reconfigure(const fhicl::ParameterSet& pset); std::vector<DoubleVec> GetNoiseFactVec() { return fNoiseFactVec; } double GetASICGain(unsigned int const channel) const; double GetShapingTime(unsigned int const channel) const; double GetRawNoise(unsigned int const channel) const ; double GetDeconNoise(unsigned int const channel) const; // Accessors. int FieldResponseTOffset(unsigned int const channel) const; const util::SignalShaping& SignalShaping(unsigned int channel) const; // Do convolution calcution (for simulation). template <class T> void Convolute(unsigned int channel, std::vector<T>& func) const; // Do deconvolution calcution (for reconstruction). template <class T> void Deconvolute(unsigned int channel, std::vector<T>& func) const; double GetDeconNorm(){return fDeconNorm;}; private: // Private configuration methods. // Post-constructor initialization. void init() const{const_cast<SignalShapingServiceDUNE*>(this)->init();} void init(); // Calculate response functions. void SetFieldResponse(); void SetElectResponse(double shapingtime, double gain); // Calculate filter functions. void SetFilters(); // Attributes. bool fInit; ///< Initialization flag. // Sample the response function, including a configurable // drift velocity of electrons void SetResponseSampling(); // Fcl parameters. int fNFieldBins; ///< number of bins for field response double fCol3DCorrection; ///< correction factor to account for 3D path of ///< electrons thru wires double fInd3DCorrection; ///< correction factor to account for 3D path of ///< electrons thru wires double fColFieldRespAmp; ///< amplitude of response to field double fIndUFieldRespAmp; ///< amplitude of response to field double fIndVFieldRespAmp; ///< amplitude of response to field std::vector<double> fFieldResponseTOffset; ///< Time offset for field response in ns std::vector<double> fCalibResponseTOffset; double fInputFieldRespSamplingPeriod; ///< Sampling period in the input field response. double fDeconNorm; double fADCPerPCAtLowestASICGain; ///< Pulse amplitude gain for a 1 pc charge impulse after convoluting it the with field and electronics response with the lowest ASIC gain setting of 4.7 mV/fC std::vector<DoubleVec> fNoiseFactVec; std::vector<double> fASICGainInMVPerFC; std::vector<double> fShapeTimeConst; ///< time constants for exponential shaping TF1* fColFilterFunc; ///< Parameterized collection filter function. TF1* fIndUFilterFunc; ///< Parameterized induction filter function. TF1* fIndVFilterFunc; ///< Parameterized induction filter function. bool fUseFunctionFieldShape; ///< Flag that allows to use a parameterized field response instead of the hardcoded version bool fUseHistogramFieldShape; ///< Flag that turns on field response shapes from histograms bool fGetFilterFromHisto; ///< Flag that allows to use a filter function from a histogram instead of the functional dependency TF1* fColFieldFunc; ///< Parameterized collection field shape function. TF1* fIndUFieldFunc; ///< Parameterized induction field shape function. TF1* fIndVFieldFunc; ///< Parameterized induction field shape function. TH1F *fFieldResponseHist[3]; ///< Histogram used to hold the field response, hardcoded for the time being TH1D *fFilterHist[3]; ///< Histogram used to hold the collection filter, hardcoded for the time being // Following attributes hold the convolution and deconvolution kernels util::SignalShaping fColSignalShaping; util::SignalShaping fIndUSignalShaping; util::SignalShaping fIndVSignalShaping; // Field response. std::vector<double> fColFieldResponse; std::vector<double> fIndUFieldResponse; std::vector<double> fIndVFieldResponse; // Electronics response. std::vector<double> fElectResponse; // Filters. std::vector<TComplex> fColFilter; std::vector<TComplex> fIndUFilter; std::vector<TComplex> fIndVFilter; }; } //---------------------------------------------------------------------- // Do convolution. template <class T> inline void util::SignalShapingServiceDUNE:: Convolute(unsigned int channel, std::vector<T>& func) const { SignalShaping(channel).Convolute(func); //negative number int time_offset = FieldResponseTOffset(channel); std::vector<T> temp; if (time_offset <=0){ temp.assign(func.begin(),func.begin()-time_offset); func.erase(func.begin(),func.begin()-time_offset); func.insert(func.end(),temp.begin(),temp.end()); }else{ temp.assign(func.end()-time_offset,func.end()); func.erase(func.end()-time_offset,func.end()); func.insert(func.begin(),temp.begin(),temp.end()); } } //---------------------------------------------------------------------- // Do deconvolution. template <class T> inline void util::SignalShapingServiceDUNE:: Deconvolute(unsigned int channel, std::vector<T>& func) const { SignalShaping(channel).Deconvolute(func); int time_offset = FieldResponseTOffset(channel); std::vector<T> temp; if (time_offset <=0){ temp.assign(func.end()+time_offset,func.end()); func.erase(func.end()+time_offset,func.end()); func.insert(func.begin(),temp.begin(),temp.end()); }else{ temp.assign(func.begin(),func.begin()+time_offset); func.erase(func.begin(),func.begin()+time_offset); func.insert(func.end(),temp.begin(),temp.end()); } } //---------------------------------------------------------------------- DECLARE_ART_SERVICE(util::SignalShapingServiceDUNE, LEGACY) #endif
[ "dladams@bnl.gov" ]
dladams@bnl.gov
38439c5074d9f89042a5dc4bc25456260db90d33
49ce12d85e15b5efe986ffeb18aad0c5dcdb0a79
/clock_base.cpp
13ca2f62e248ce2a408c1802058d57b98dd43315
[]
no_license
MinatoOmori/educ2018_cpp
5586e6bc353702ef54d26a6f0b84b130f6eac73a
aae0de88d967e3cc1a58cb6406f922c76167cbe2
refs/heads/master
2021-01-25T14:16:20.261086
2018-03-06T07:23:23
2018-03-06T07:23:23
123,675,207
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
cpp
#include <iostream> #include <fstream> #include <string> #include <stdio.h> #include <vector> using namespace std; int main(int argc, char* argv[]) { int answer[100] = {}; ifstream ifs(argv[1]); if (!ifs) { cout<<"text file error."<<endl; return -1; } vector<char> memory; char tmp; while (ifs.get(tmp)) { memory.push_back(tmp); } auto itr = memory.begin(); int* ptr; ptr = &answer[0]; auto left_par = memory.begin(); while (itr != memory.end()) { if (*itr == '>') { ptr++; } else if (*itr == '<') { ptr--; } else if (*itr == '+') { (*ptr)++; } else if (*itr == '-') { (*ptr)--; } else if (*itr == '.') { putchar(*ptr); } else if (*itr == ',') { *ptr = getchar(); } else if (*itr == '[') { if (*ptr == 0) { for (auto right_par = itr; right_par != memory.end(); right_par++) { if (*right_par == ']') { itr = right_par; break; } } } else { left_par = itr; } } else if (*itr == ']') { itr = left_par-1; } itr++; } return 0; }
[ "minato@oomori-linux.westlab" ]
minato@oomori-linux.westlab
246ce2b7ff3b0d0a59e76d449ede1ac14b11f27e
088e589cc77aac615517697015c8af1bbacde9ef
/ball.h
4d09a907327e534a017e7bed3aab6781e1031a3c
[]
no_license
connor226/Volleyball-game
7734a12b81c1f17147593ad65184ce3c57dd6cac
d3e57c6468212ed4ef0802cf4e94f56663788526
refs/heads/main
2023-02-20T15:34:36.496056
2021-01-18T13:28:19
2021-01-18T13:28:19
322,568,842
0
0
null
null
null
null
UTF-8
C++
false
false
547
h
#ifndef INC_BITS_H #include <bits/stdc++.h> #define INC_BITS_H #endif #ifndef INC_SDL_H #include "SDL2/SDL.h" #include "SDL2/SDL_image.h" #define INC_SDL_H #endif #define X first #define Y second class BALL{ public: pair<int, int> v; SDL_Texture *pic; SDL_Rect model; BALL(char side){ v = {0,0}; model.h = ball_size; model.w = ball_size; if(side == 'L') model.x = ScreenWidth / 4 - PlayerWidth1 / 2; if(side == 'R') model.x = ScreenWidth * 3 / 4 - PlayerWidth1 / 2; model.y = initial_height; } private: };
[ "connor.taipei@gmail.com" ]
connor.taipei@gmail.com
cd3a35a91296a384f03847cddcb7570e2a5f7408
75e4cf413843a59bb030a5e9959f9fc0168d04e1
/Parking.cpp
37c5504b6280d0602f79e19777b60ffb04194dff
[]
no_license
SkyeFox379/Learning_C_PlusPlus
a1a3c81a2918085514f42f8046ac11ae5cda5a6d
75d15236f60df6f7306efbb7d4826607619fad2d
refs/heads/master
2020-03-17T04:34:52.733623
2018-07-06T22:13:15
2018-07-06T22:13:15
133,281,015
0
0
null
null
null
null
UTF-8
C++
false
false
909
cpp
#include <iostream> #include <cmath> #include <vector> #include <algorithm> using namespace std; int walkingDistance(vector<int> stores, int len) { int difference, distance = 0; int k; for(k = 0; k < len - 1; k++) { difference = abs(stores[k] - stores[k+1]); distance = distance + difference; } distance = distance + abs( (stores[0] - stores[len - 1]) ); return distance; } int main() { int cases, stores, storeLoc, distance; int k; vector<int> locations; cin >> cases; for(int x = 0; x < cases; x++) { locations.clear(); cin >> stores; for(k = 0; k < stores; k++) { cin >> storeLoc; locations.push_back(storeLoc); } sort(locations.begin(), locations.end()); distance = walkingDistance(locations, stores); cout << distance << endl; } return 0; }
[ "skylar.hagen@trojans.dsu.edu" ]
skylar.hagen@trojans.dsu.edu
c5439a733cf71f826f78788c12b4e9d2a83c0159
ed216d6af2b9e55fdf650cbf52d1754f6e653bb2
/common/src/filesystem/VectorFileBuffer.hpp
9f4f97da3949f470bbecf64f357c35a1dfda9c20
[]
no_license
jessevdp/avansync
6153350f53361671f912c18f937be18ebb06f36b
a4d43d5039b8b5cc198d952d3b838dc3cace96cc
refs/heads/main
2023-04-21T15:26:07.837618
2021-05-08T16:21:28
2021-05-08T16:21:28
323,093,760
0
0
null
null
null
null
UTF-8
C++
false
false
413
hpp
#pragma once #include "FileBuffer.hpp" #include <vector> namespace avansync { class VectorFileBuffer : public FileBuffer { private: std::vector<char> _buffer {}; public: VectorFileBuffer() = default; explicit VectorFileBuffer(int capacity); char* data() override; [[nodiscard]] size_t size() const override; void reserve(int capacity) override; }; } // namespace avansync
[ "jessevdp@hey.com" ]
jessevdp@hey.com
2fb0996c901c9d1314094b834c852fa5636115d0
95b51dac4dad8df1605113f88417bccd0e496927
/hw0-folder/Parser/util.cpp
3c4e80690cd148568ffbad222da94d23834e01c2
[]
no_license
pwon111/cs171
a0005e103e2cb480b3205e32d4167d560e727f80
d74e94ee37928ce96c56b9b26bc3557b5827ecac
refs/heads/master
2021-01-16T00:58:03.010373
2015-01-19T04:19:32
2015-01-19T04:19:32
29,453,178
0
0
null
null
null
null
UTF-8
C++
false
false
2,325
cpp
/* CS/CNS 171 Fall 2014 * * This file contains the actual implementations of the functions in util.h. * Right now, each function simply returns the identity matrix. You will * fill these functions in with the proper implementations in Assignment 1. */ #include "util.h" /* Gets the translation matrix for a given translation vector (x, y, z). */ MatrixXd get_translate_mat(float x, float y, float z) { MatrixXd translation_matrix = MatrixXd::Identity(4,4); translation_matrix(0, 3) = x; translation_matrix(1, 3) = y; translation_matrix(2, 3) = z; return translation_matrix; } /* Gets the rotation matrix for a given rotation axis (x, y, z) and angle. */ MatrixXd get_rotate_mat(float x, float y, float z, float angle) { MatrixXd rotation_matrix(4, 4); // first row rotation_matrix << x * x + (1 - x * x) * cos(angle), x * y * (1 - cos(angle)) - z * sin(angle), x * z * (1 - cos(angle)) + y * sin(angle), 0, // second row y * x * (1 - cos(angle)) + z * sin(angle), y * y + (1 - y * y) * cos(angle), y * z * (1 - cos(angle)) - x * sin(angle), 0, // third row z * x * (1 - cos(angle)) - y * sin(angle), z * y * (1 - cos(angle)) + x * sin(angle), z * z + (1 - z * z) * cos(angle), 0, // fourth row 0, 0, 0, 1; return rotation_matrix; } /* Gets the scaling matrix for a given scaling vector (x, y, z). */ MatrixXd get_scale_mat(float x, float y, float z) { MatrixXd scaling_matrix = MatrixXd::Identity(4,4); scaling_matrix(0, 0) = x; scaling_matrix(1, 1) = y; scaling_matrix(2, 2) = z; return scaling_matrix; } /* Gets the perspective projection matrix given the frustum parameters. */ MatrixXd get_perspective_mat(float near, float far, float left, float right, float top, float bottom) { MatrixXd perspective_matrix(4, 4); // first row perspective_matrix << 2 * near / (right - left), 0, (right + left) / (right - left), 0, // second row 0, 2 * near / (top - bottom), (top + bottom) / (top - bottom), 0, // third row 0, 0, (far + near) / (near - far), 2 * far * near / (near - far), // fourth row 0, 0, -1, 0; return perspective_matrix; }
[ "pwon111@gmail.com" ]
pwon111@gmail.com
a99d4c0310dee36e31ac67f5afa1587e4e99bea5
d3ca74c678dfb5d3c8de90b27abb15847ba67a0d
/cppfiles/exercise/object_oriented/ex08_abstraction_encapsulation.cpp
af2d0b21c7ee7feb0dfe27756d0b19fe9684b1f1
[]
no_license
jsupratman13/workspace
6807dafccc8949a54205a16a75d5e49852fa118b
9ef4dc80b430f14f3caaca57e5eee90c919fcf9b
refs/heads/master
2021-12-27T21:21:49.956437
2021-12-20T09:39:31
2021-12-20T09:39:31
28,377,814
0
0
null
2021-01-29T06:37:39
2014-12-23T04:45:40
Python
UTF-8
C++
false
false
895
cpp
//Data abstraction: provide only essential information to oustside //provide two advantages: prevent user leverl, implment may change without changing user-level //seperate code to interface and implementation //Data Encapsulation is a mechanism of bundling data and the functions that use them //data Abstraction is a mechanism of exposing only the interfaces and hiding the implmentation details from the user #include <iostream> using namespace std; class Adder{ public: //constructor Adder(int i =0); //interface to outside world void addNum(int number); int getTotal(); private: //hidden data from outside world int total; }; Adder::Adder(int i){ total = i; } void Adder::addNum(int number){ total += number; } int Adder::getTotal(){ return total; } int main(){ Adder a; a.addNum(30); a.addNum(10); a.addNum(20); cout << "Total: "<< a.getTotal() << endl; }
[ "s1426071BL@s.chibakoudai.jp" ]
s1426071BL@s.chibakoudai.jp
22ee14951aefc73556c9666bd769ca8707522812
10aa16a8f81bf77cf0fb7abb88d962904f4d6f98
/arcade_src/GraphicLib.h
a0398af46f1bef8a58acdefba186f62bbde695c4
[]
no_license
qlem/Arcade
2001b45d230f2451d2eac7a4267fb359d786ae9f
107206b73be9afad423b6956ab6735e687584b30
refs/heads/master
2021-04-25T13:05:26.947427
2017-11-17T16:27:35
2017-11-17T16:27:35
110,548,769
0
1
null
null
null
null
UTF-8
C++
false
false
537
h
// // Created by raven57 on 07/04/17. // #ifndef CPP_ARCADE_GRAPHICLIB_H #define CPP_ARCADE_GRAPHICLIB_H #include <string> #include "../inc/IGraphic.hh" namespace arcade { class GraphicLib { private: std::string name = ""; IGraphic *graphicLib = NULL; public: GraphicLib(); GraphicLib(const std::string &fileName, IGraphic *graphicLib); ~GraphicLib(); const std::string &getName() const; IGraphic *getGraphicLib() const; }; } #endif //CPP_ARCADE_GRAPHICLIB_H
[ "clement.dommerc@epitech.eu" ]
clement.dommerc@epitech.eu
47f1358a32719d378b3c37f5009d6d009c6653ba
dd04f0ee4b8d0b9e9e8db66bb8d7c0d91d2e793b
/banking_system/accountClass.hpp
44d6882fe763e23c056ee7710b6e9cb7e411d1a0
[]
no_license
victorvg17/cpp-projects
aedd5844f2fad263eccfdf2ed1182a3c08ccec01
4b5a5fb17ce452415d2fd590dc7e4878cf62ab7c
refs/heads/master
2020-08-04T01:49:56.053097
2019-10-19T19:40:28
2019-10-19T19:40:28
211,960,036
0
0
null
null
null
null
UTF-8
C++
false
false
890
hpp
#include<iostream> #include<fstream> #include<iomanip> namespace bank{ using namespace std; /** Account class used in the project **/ class account{ int account_no; char account_name[50]; int deposit; char account_type; public: void create_account(); //for getting data from customer void show_account() const; //function to show data on screen void modify_account(); //function to add new data void deposit_amount(int amount); //to accept deposit and add to current deposit void draw_amount(int amount); //to draw amount deposit and reduce from current deposit void report() const; //to show account details in tabular form; const: read only int return_account_no() const; //to return account number int return_deposit_amount() const; //to return current amount in deposit char return_account_type() const; //return type of account }; } //namespace bank
[ "victorvg17" ]
victorvg17
d295d7089cf18df163981b409c8b23f41d213ade
6411864368e4dd44d3f968bb0aa0de15bb80efe1
/TurtleTank_codes/PaintControll_full_functionallities/PaintControll_full_functionallities.ino
1e1c9937c777ad9da74700940d1f1fc804db436a
[]
no_license
DjPitti/G565-TurtleTank
0d9408975afdb55a9d7d25f15e00801952fb697f
7abb66b92d3965cace85ab1dcc9a2304166c61dc
refs/heads/master
2023-02-04T18:07:35.873598
2020-12-20T12:47:17
2020-12-20T12:47:17
323,061,078
0
0
null
null
null
null
UTF-8
C++
false
false
8,788
ino
//paintcontroll with ros and the functions // version 2.1 // ros lib #include <ros.h> #include <std_msgs/String.h> #include <std_msgs/Int8.h> //servo lib #include <Servo.h> // pin int valve_pin = 4; int pump_pin = 3; //variables bool paint_guard_state = false; bool valve_state = false; bool pump_state = false; // servo current possition and delay be tween every possition when moving Servo pg_servo; int pg_pos = 180; int servo_delay = 6; // delays in micro seconds, we also tried it with nano seconds both didnt work as wanted. int guard2pump_delay = 650000;// 650; int pump2valve_delay = 250000; //250; //delay from the pump opening until the valve opening int valve2pump_delay = 500000;// 500; int pump2guard_delay = 2000000; //2000; // * we should to it different use tyiming instead. //variables for the Main int led = 13; // status led bool led_state = true; char input_string; String start_str, input_str, variable_str; //ros ros::NodeHandle node_handle; //publisher std_msgs::String valve_status_msg; std_msgs::String pump_status_msg; std_msgs::String paint_guard_status_msg; //subs std_msgs::Int8 valve_msg; std_msgs::Int8 pump_msg; std_msgs::Int8 paint_guard_msg; std_msgs::Int8 paint_action_msg; std_msgs::Int8 turtleTank_msg; // ------------------------ Functions for controlling the pump, valve and paint_guard ------------------------ void servo_func(bool pos_bool) { int pos; if (pos_bool == true) { Serial.println("s-HIGH"); //add error handeling for (pos = pg_pos; pos > 0; pos -= 1) { // goes from 180 degrees to 0 degrees pg_servo.write(pos); // tell servo to go to position in variable 'pos' delay(servo_delay); // waits 15ms for the servo to reach the position Serial.print(pos); Serial.print(" ,"); } } else { Serial.println("s-low"); //add error handeling for (pos = pg_pos; pos < 180; pos += 1) { // goes from 0 degrees to 180 degrees // in steps of 1 degree pg_servo.write(pos); // tell servo to go to position in variable 'pos' delay(servo_delay); // waits 15ms for the servo to reach the position Serial.print(pos); Serial.print(" ,"); } } pg_pos = pos; Serial.print(" : "); Serial.println(pg_pos); paint_guard_state == pos_bool; } void set_pump_state(bool state) { // start(true)/stop(false the pump if (pump_state == state) { Serial.print("Error: 01 [Pump state was already set to: "); Serial.println(state); return; } else { if (state == true) { Serial.println("true"); // digitalWrite(8, HIGH); digitalWrite(pump_pin, HIGH); } else { // digitalWrite(8, LOW); digitalWrite(pump_pin, LOW); Serial.println("false"); } pump_state = state; Serial.print("Pump is now set to: " ); Serial.println(state); } } bool get_pump_state() { // read the state of the pump Serial.print("pump is: "); Serial.println(pump_state); return pump_state; } void set_valve_state(bool state) { // open(true)/close(false) valve if (valve_state == state) { Serial.print("Error: 02 [Valve state was already set to: " ); Serial.println(state); return; } if (state == true) { digitalWrite(valve_pin, HIGH); } else { digitalWrite(valve_pin, LOW); } valve_state = state; Serial.print("Valve is now set to: "); Serial.println(state); } bool get_valve_state() { // read the state of the valve Serial.print("valve is: "); Serial.println(valve_state); return valve_state; } void set_paint_guard_state(bool state) { // move paint gueard up(false)/down(true) if (paint_guard_state == state) { Serial.print("Error: 03 [Paint_guard state was already set to: "); Serial.println(state); return; } servo_func(state); paint_guard_state = state; Serial.print("Paint_guard is now set to: "); Serial.println(state); } bool get_paint_guard_state() { // read state of paint guard Serial.print("paint_guard is: "); Serial.println(paint_guard_state); return paint_guard_state; } void start_painting() { // initial start painting frequence Serial.println("prepare to start painting"); set_paint_guard_state(true); delayMicroseconds(guard2pump_delay); set_pump_state(true); delayMicroseconds(pump2valve_delay); set_valve_state(true); Serial.println("painting is ongoing"); } void stop_painting() { // inital stop painting frequence Serial.println("prepare to stop painting"); set_valve_state(false); delayMicroseconds(valve2pump_delay); set_pump_state(false); delayMicroseconds(pump2guard_delay); set_paint_guard_state(false); Serial.println("painting is stopped\n"); } void paint_cycle(int distance) { // start paint frequence, wait for x ms, stop painting float distance_sec = distance / 1000; Serial.print("Painting for: "); Serial.print( distance_sec ); Serial.println("seconds"); start_painting(); Serial.println("painting: "); delay(distance * 1000); Serial.println("DONE"); stop_painting(); } //------------------------------------------------------------------------ //------------------------ subs function ------------------------ void valve_subscriberCallback(const std_msgs::Int8& valve_msg) { if (valve_msg.data == 1) { node_handle.loginfo("valve: 1"); set_valve_state(true); } else { node_handle.loginfo("valve: 0"); set_valve_state(false); } } void pump_subscriberCallback(const std_msgs::Int8& pump_msg) { if (pump_msg.data == 1) { node_handle.loginfo("pump: 1"); set_pump_state(true); } else { node_handle.loginfo("pump: 0"); set_pump_state(false); } } void paint_guard_subscriberCallback(const std_msgs::Int8& paint_guard_msg) { if (paint_guard_msg.data == 1) { node_handle.loginfo("paint_guard: 1"); set_paint_guard_state(true); } else { node_handle.loginfo("paint_guard: 0"); set_paint_guard_state(false); } } void paint_action_subscriberCallback(const std_msgs::Int8&paint_action_msg) { if (paint_action_msg.data == 1) { node_handle.loginfo("paint_action: 1"); start_painting(); } else { node_handle.loginfo("paint_action: 0"); stop_painting(); } node_handle.loginfo("done"); } //------------------------------------------------------------------------ // pubs ros::Publisher valve_publisher("valve_status", &valve_status_msg); ros::Publisher pump_publisher("pump_status", &pump_status_msg); ros::Publisher paint_guard_publisher("paint_guard_status", &paint_guard_status_msg); // SUBS ros::Subscriber<std_msgs::Int8> valve_subscriber("valve", &valve_subscriberCallback); ros::Subscriber<std_msgs::Int8> pump_subscriber("pump", &pump_subscriberCallback); ros::Subscriber<std_msgs::Int8> paint_guard_subscriber("paint_guard", &paint_guard_subscriberCallback); ros::Subscriber<std_msgs::Int8> paint_action_subscriber("paint_action", &paint_action_subscriberCallback); void setup() { Serial.begin(57600); Serial.print("Start_setup: "); pinMode(valve_pin, OUTPUT); pinMode(pump_pin, OUTPUT); pg_servo.attach(2); pg_servo.write(180); pinMode(led, OUTPUT); // ros node_handle.initNode(); // pups node_handle.advertise(valve_publisher); node_handle.advertise(pump_publisher); node_handle.advertise(paint_guard_publisher); // subs node_handle.subscribe(valve_subscriber); node_handle.subscribe(pump_subscriber); node_handle.subscribe(paint_guard_subscriber); node_handle.subscribe(paint_action_subscriber); node_handle.loginfo("main"); Serial.println("DONE"); digitalWrite(led, HIGH); } void loop() { // valve if (valve_state == true) { valve_status_msg.data = "valve: open"; Serial.print("valve_open, "); } else { valve_status_msg.data = "valve: closed"; Serial.print("valve_closed, "); } // pump if (pump_state == true) { pump_status_msg.data = "pump: on"; Serial.print("pump on, "); } else { pump_status_msg.data = "pump: off"; Serial.print("pump off, "); } //paint_guard if (paint_guard_state == true) { paint_guard_status_msg.data = "paint_guard: down"; Serial.println("pg down, "); } else { paint_guard_status_msg.data = "paint_guard: up"; Serial.println("pg up "); } valve_publisher.publish( &valve_status_msg ); pump_publisher.publish( &pump_status_msg ); paint_guard_publisher.publish( &paint_guard_status_msg ); node_handle.spinOnce(); delay(10); }
[ "per.daetz@live.de" ]
per.daetz@live.de
6b0f749fcf2ac1c35bc8e8b69ed8badb97aef33e
5148fa0353d516be3ea0d7cc47020e807293e20d
/HRD Average sessions and Average Test time Table 2/percentage_reduction_table2_with_knowledge.cpp
626ce6d084da9262690744ee651f94d390fb66ae
[]
no_license
daku5768/Pre-Bond-TSV-s-Defects
84fda301f2aeb245ceb10183646e55bdf9d47cc3
6c958b7e65e9c0d79d4b9e3b27fa46baaa933a34
refs/heads/master
2022-12-19T10:37:49.301308
2020-09-20T02:36:39
2020-09-20T02:36:39
296,985,985
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
#include<bits/stdc++.h> using namespace std; void fun(double a[],double b[]) { for(int i=0;i<21;i++) cout<<(b[i]-a[i])/b[i]*100<<endl; } int main() { double a[]={3,4.5,5.85,6.69,4,5.66,7.30,8.53,9.46,5,6.66,8.38,9.76,10.89,11.78,5,7.25,9.84,11.94,13.67,15.07}; double b[]={5,5.3,6.4,7.5,7,7.5,8.7,10.3,11.8,8,9.6,11.1,12.6,14.3,15.8,9,10.8,12.3,13.9,15.1,18}; fun(a,b); return 0; }
[ "32503959+daku5768@users.noreply.github.com" ]
32503959+daku5768@users.noreply.github.com
2a43c5fa9173e8ce11fe7a1c078fd1613101912e
816d47056b602635deb5190114cf4ce51a3225cb
/system/dfs/fzu2277.cpp
ca016dea54a69e85e7c7be07da68a23a93464599
[]
no_license
yezi1000/ACM-ICPC
284ab7ea1fd479a7ce8243bd00a3417fdcb9a93f
905621cfa75662c4cec5410516ea228e9ca73ab4
refs/heads/master
2021-07-22T04:51:45.671884
2018-10-16T10:58:04
2018-10-16T10:58:04
132,892,581
1
0
null
null
null
null
UTF-8
C++
false
false
2,707
cpp
#include<cstdio> #include<algorithm> #include<queue> #include<iostream> #include<cmath> #include<vector> #include<set> #include<stack> #include<map> #include<cstring> #define eps 1e-8 #define pi acos(-1) #define mp make_pair #define PH push #define pb push_back #define PII pair<ll,ll> #define VI vector<int> #define fi first #define se second #define N(a,b) a=N(a,b) #define Min(a,b) a=min(a,b) #define sqr(x) ((x)*(x)) #define CL(a) memset(a,0,sizeof a) #define fr(i,n) for(int i=1;i<=n;i++) #define FR(i,S,n) for(int i=S;i<=n;i++) #define dr(i,n) for(int i=n;i;i--) #define DR(i,n,S) for(int i=n;i>=S;i--) #define SZ(x) ((int)(x).size()) #define all(n) n.begin(),n.end() #define rd(x) scanf("%d",&x) #define pr(x) printf("%d",x) #define prn(x) printf("%d\n",x) typedef long long ll; #define mo 1000000007 ll expow(ll a,ll b,ll p) {ll v=1; for (; b; b>>=1,a=a*a%p)if (b&1)v=v*a%p; return v;} ll inv(ll a,ll p) {return expow(a,p-2,p);} using namespace std; namespace bit { const int MX=300000+10; int c[MX],n; void init(int x) { memset(c,0,sizeof(c)); n=x; } int lowbit(int x) { return x&(-x); } void update(int x,int u) {//单点修改 while (x<=n) { c[x]=(c[x]+u)%mo; x+=lowbit(x); } } void iupdate(int l,int r,int u){//区间修改 update(l,u); update(r+1,-u+mo); } int sum(int x) { int sum=0; while (x>0) { sum=(sum+c[x])%mo; x-=lowbit(x); } return sum%mo; } int getsum(int l,int r) { return sum(r)-sum(l-1); } } // binary indexed tree const int N=300000+10; struct node{ int l,r; }p[N]; vector<int>e[N]; int r[N],a[N],cnt; int dep[N]; void dfs(int t,int dep){ p[t].l=++cnt; dep[t]=dep; for(int j=0;j<(int)e[t].size();j++) dfs(e[t][j],dep+1); p[t].r=cnt; } int kk; void up(int v,int x){ bit::iupdate(p[v].l,p[v].r,x); for(int j=0;j<e[v].size();j++) dfs2(e[v][j]); } void init(int q){ bit::init(q); for(int j=1;j<=q;j++) e[j].clear(); cnt=0; } int main(){ #ifndef ONLINE_JUDGE freopen("D:\\GitHub\\ACM-ICPC\\other\\in.txt","r",stdin); #endif int T; scanf("%d",&T); //cout<<T<<endl; while(T--){ int n; int tx; scanf("%d",&n); init(n); for(int j=2;j<=n;j++){ scanf("%d",&tx); e[tx].pb(j); r[j]=tx; } dfs(1); //cout<<"e"<<endl; int q,v,x; scanf("%d",&q); while(q--){ int t; scanf("%d",&t); if(t==1){ scanf("%d%d%d",&v,&x,&kk); up(v,x); } else { scanf("%d",&v); printf("%d\n",bit::sum(v)); } } //cout<<"e"<<endl; } return 0; }
[ "30385445+yezi1000@users.noreply.github.com" ]
30385445+yezi1000@users.noreply.github.com
bb0591ff133ee772e19c2c44361877f5efbcc1d4
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/remoting/client/chromoting_client.h
11d4948b713a6a33fc03f6759182cdddacd4dbab
[ "BSD-3-Clause" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
5,463
h
// Copyright (c) 2012 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. // ChromotingClient is the controller for the Client implementation. #ifndef REMOTING_CLIENT_CHROMOTING_CLIENT_H_ #define REMOTING_CLIENT_CHROMOTING_CLIENT_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "remoting/protocol/client_authentication_config.h" #include "remoting/protocol/client_stub.h" #include "remoting/protocol/clipboard_stub.h" #include "remoting/protocol/connection_to_host.h" #include "remoting/protocol/input_stub.h" #include "remoting/protocol/mouse_input_filter.h" #include "remoting/protocol/session_config.h" #include "remoting/protocol/video_stub.h" #include "remoting/signaling/signal_strategy.h" namespace base { class SingleThreadTaskRunner; } // namespace base namespace remoting { namespace protocol { class CandidateSessionConfig; class SessionManager; class TransportContext; class VideoRenderer; } // namespace protocol class AudioConsumer; class AudioDecodeScheduler; class ClientContext; class ClientUserInterface; class FrameConsumerProxy; class ChromotingClient : public SignalStrategy::Listener, public protocol::ConnectionToHost::HostEventCallback, public protocol::ClientStub { public: // |client_context|, |user_interface| and |video_renderer| must outlive the // client. |audio_consumer| may be null, in which case audio will not be // requested. ChromotingClient(ClientContext* client_context, ClientUserInterface* user_interface, protocol::VideoRenderer* video_renderer, base::WeakPtr<AudioConsumer> audio_consumer); ~ChromotingClient() override; void set_protocol_config( std::unique_ptr<protocol::CandidateSessionConfig> config); // Used to set fake/mock objects for tests which use the ChromotingClient. void SetConnectionToHostForTests( std::unique_ptr<protocol::ConnectionToHost> connection_to_host); // Start the client. Must be called on the main thread. |signal_strategy| // must outlive the client. void Start(SignalStrategy* signal_strategy, const protocol::ClientAuthenticationConfig& client_auth_config, scoped_refptr<protocol::TransportContext> transport_context, const std::string& host_jid, const std::string& capabilities); protocol::ConnectionToHost::State connection_state() const { return connection_->state(); } protocol::ClipboardStub* clipboard_forwarder() { return connection_->clipboard_forwarder(); } protocol::HostStub* host_stub() { return connection_->host_stub(); } protocol::InputStub* input_stub() { return &mouse_input_scaler_; } // ClientStub implementation. void SetCapabilities(const protocol::Capabilities& capabilities) override; void SetPairingResponse( const protocol::PairingResponse& pairing_response) override; void DeliverHostMessage(const protocol::ExtensionMessage& message) override; void SetVideoLayout(const protocol::VideoLayout& layout) override; // ClipboardStub implementation for receiving clipboard data from host. void InjectClipboardEvent(const protocol::ClipboardEvent& event) override; // CursorShapeStub implementation for receiving cursor shape updates. void SetCursorShape(const protocol::CursorShapeInfo& cursor_shape) override; // ConnectionToHost::HostEventCallback implementation. void OnConnectionState(protocol::ConnectionToHost::State state, protocol::ErrorCode error) override; void OnConnectionReady(bool ready) override; void OnRouteChanged(const std::string& channel_name, const protocol::TransportRoute& route) override; private: // SignalStrategy::StatusObserver interface. void OnSignalStrategyStateChange(SignalStrategy::State state) override; bool OnSignalStrategyIncomingStanza(const buzz::XmlElement* stanza) override; // Starts connection once |signal_strategy_| is connected. void StartConnection(); // Called when the connection is authenticated. void OnAuthenticated(); // Called when all channels are connected. void OnChannelsConnected(); base::ThreadChecker thread_checker_; std::unique_ptr<protocol::CandidateSessionConfig> protocol_config_; // The following are not owned by this class. ClientUserInterface* user_interface_ = nullptr; protocol::VideoRenderer* video_renderer_ = nullptr; SignalStrategy* signal_strategy_ = nullptr; std::string host_jid_; protocol::ClientAuthenticationConfig client_auth_config_; scoped_refptr<protocol::TransportContext> transport_context_; std::unique_ptr<protocol::SessionManager> session_manager_; std::unique_ptr<protocol::ConnectionToHost> connection_; protocol::MouseInputFilter mouse_input_scaler_; std::unique_ptr<AudioDecodeScheduler> audio_decode_scheduler_; std::string local_capabilities_; // The set of all capabilities supported by the host. std::string host_capabilities_; // True if |protocol::Capabilities| message has been received. bool host_capabilities_received_ = false; DISALLOW_COPY_AND_ASSIGN(ChromotingClient); }; } // namespace remoting #endif // REMOTING_CLIENT_CHROMOTING_CLIENT_H_
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
3fb2f7d87666576333b494efe8584d0e580f4d2e
297497957c531d81ba286bc91253fbbb78b4d8be
/third_party/libwebrtc/rtc_tools/frame_analyzer/reference_less_video_analysis_unittest.cc
4722d73561048df9021058d05d7d02a4f337c459
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
C++
false
false
1,352
cc
#include <vector> #include "api/scoped_refptr.h" #include "rtc_tools/frame_analyzer/reference_less_video_analysis_lib.h" #include "rtc_tools/video_file_reader.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" class ReferenceLessVideoAnalysisTest : public ::testing::Test { public: void SetUp() override { video = webrtc::test::OpenY4mFile( webrtc::test::ResourcePath("reference_less_video_test_file", "y4m")); ASSERT_TRUE(video); } rtc::scoped_refptr<webrtc::test::Video> video; std::vector<double> psnr_per_frame; std::vector<double> ssim_per_frame; }; TEST_F(ReferenceLessVideoAnalysisTest, MatchComputedMetrics) { compute_metrics(video, &psnr_per_frame, &ssim_per_frame); EXPECT_EQ(74, (int)psnr_per_frame.size()); ASSERT_NEAR(27.2f, psnr_per_frame[1], 0.1f); ASSERT_NEAR(24.9f, psnr_per_frame[5], 0.1f); ASSERT_NEAR(0.9f, ssim_per_frame[1], 0.1f); ASSERT_NEAR(0.9f, ssim_per_frame[5], 0.1f); } TEST_F(ReferenceLessVideoAnalysisTest, MatchIdenticalFrameClusters) { compute_metrics(video, &psnr_per_frame, &ssim_per_frame); std::vector<int> identical_frame_clusters = find_frame_clusters(psnr_per_frame, ssim_per_frame); EXPECT_EQ(5, (int)identical_frame_clusters.size()); EXPECT_EQ(1, identical_frame_clusters[0]); EXPECT_EQ(1, identical_frame_clusters[4]); }
[ "mcastelluccio@mozilla.com" ]
mcastelluccio@mozilla.com
fc1c317e4bb93733b16af5571d9163eacc6e4b20
88a2494bbee50a962c000900f94440324f6a2db2
/Data Structures/Arboles Avl/Practica5Avl/Practica5Avl/Practica5Avl.cpp
56b5f828ba8c96dfade0e1c87b114c0706004eea
[]
no_license
manugarcia101/Cplusplus
c8bcad28612f0cc4b5e1a9f4103ea00d3e4d7ba0
9e5308a5e00dc7e3460c6896fa21bfd7a9f0c9c9
refs/heads/master
2020-03-19T04:28:28.212755
2018-06-07T17:49:09
2018-06-07T17:49:09
135,832,739
0
1
null
null
null
null
UTF-8
C++
false
false
2,615
cpp
// Practica5Avl.cpp: define el punto de entrada de la aplicación de consola. // #include "stdafx.h" #include "TextoPredictivo.h" #include <ctime> #include <chrono> #include <iostream> #include <chrono> #include <string> #include <stdexcept> int main() { std::cout << std::endl; std::cout << "INICIO DEL PROGRAMA " << std::endl; std::cout << std::endl; std::cout << "Cargando las palabras en el diccionario, espere por favor " << std::endl; std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); Diccionario miDiccionario("listado.txt"); std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> total = t2 - t1; std::cout << "Duracion de carga de las palabras: " << total.count() << " segundos" << std::endl; std::cout << std::endl; TextoPredictivo t(&miDiccionario); bool continuar = true; bool lista = false; char num; std::string mistring= ""; std::string mistring2 = ""; std::string auxs = ""; do { try { std::cout << "¿Que quieres hacer?" << std::endl << "*Entrenar con frase(1)" << std::endl << "*Entrenar con corpus(2)" << std::endl; std::cin >> num; std::cout << std::endl; if (num == '1') { std::cout << "Introduzca la frase: "; std::getline(std::cin >> std::ws, mistring); t.entrena(mistring); } if (num == '2') { std::chrono::high_resolution_clock::time_point t3 = std::chrono::high_resolution_clock::now(); miDiccionario.Corpus("corpus.txt"); std::chrono::high_resolution_clock::time_point t4 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> total2 = t4 - t3; std::cout << "Duracion de carga de Corpus " << total2.count() << " segundos" << std::endl; } std::cout << std::endl; std::cout << "Introduzca una palabra para obtener sus sucesores:" << std::endl; std::cin >> mistring2; std::cout << std::endl; std::list<Sucesor> MiSuc; MiSuc = t.sugerencia(mistring2); std::list<Sucesor>::iterator i = MiSuc.begin(); int cont = 1; while (i != MiSuc.end()) { std::cout <<"Sucesor "<< cont <<" de " << mistring2 << ": " << i->get_Termino() << std::endl; std::advance(i, 1); ++cont; } std::cout << std::endl; std::cout << "¿Continuar?(Si/No): " << std::endl; std::cin >> auxs; if (auxs == "No") continuar = false; } catch (std::logic_error &e) { std::cout << e.what(); } } while (continuar == true); std::cout << std::endl; std::cout << "FIN DEL PROGRAMA " << std::endl; std::cout << std::endl; return 0; }
[ "manugarcial96@gmail.com" ]
manugarcial96@gmail.com
aa06368413762e8558a1291364d0420ebda07c38
11f92a2dbc8bbdc184602f4ffbe25e407b82cf19
/ConsoleApplication1/treeFromPreAndInTraversal.h
4f5d33d05250aae119212da2131061108b72b7a4
[]
no_license
ethan-was-taken/LeetCodeProblems
dd32a39725673584f1c482bf673f4cc520c03e90
ab89a606cb4c8f8b34c173e9464527fd7126cc4e
refs/heads/master
2020-07-15T11:32:21.215033
2019-08-31T14:08:24
2019-08-31T14:08:24
205,552,671
0
0
null
null
null
null
UTF-8
C++
false
false
4,154
h
#pragma once #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <unordered_set> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class treeFromPreAndInTraversal { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { /* preorderTraversal(TreeNode* curr, TreeNode* construct, vector<int>& preorder, vector<int>& inorder, int &i, int &j): 1. start construction by doing a depth first starting at the root and going left (traversal by preorder?) NOTE: add visited nodes to a hashmap 2. on recursion: if pre[i] == in[j]: increase j until you reach a node you havent visited and increase i by 1 return; (this is how you know you've reached a leaf!) 3. ??? 4. PROFIT */ in = inorder; pre = preorder; if (preorder.size() == 1) { return new TreeNode(pre[0]); } if (preorder.size() == 2) { return handleEdgeCase(); } TreeNode* tree = new TreeNode(pre[0]); tempTree = tree; int preIndex = 1; int inIndex = 0; visited.insert(pre[0]); dfs(tree, preIndex, inIndex); cout << endl << "------------------------------" << endl; postorder(tree); return tree; }; void inOrderPrint(TreeNode* node, vector<int> &toReturn) { if (node == NULL) return; /* first recur on left child */ inOrderPrint(node->left, toReturn); /* then print the data of node */ cout << node->val << "\t"; toReturn.push_back(node->val); /* now recur on right child */ inOrderPrint(node->right, toReturn); }; void preOrderPrint(TreeNode* node, vector<int> &toReturn) { if (node == NULL) return; /* then print the data of node */ cout << node->val << "\t"; toReturn.push_back(node->val); /* first recur on left child */ preOrderPrint(node->left, toReturn); /* now recur on right child */ preOrderPrint(node->right, toReturn); }; void postorder(TreeNode* p, int indent = 0) { if (p != NULL) { if (p->right) { postorder(p->right, indent + 4); } if (indent) { cout << setw(indent) << ' '; } if (p->right) cout << " /\n" << setw(indent) << ' '; cout << p->val << "\n "; if (p->left) { cout << setw(indent) << ' ' << " \\\n"; postorder(p->left, indent + 4); } } cout << endl; }; private: void dfs(TreeNode* curr, int &preIndex, int &inIndex) { if (visited.find(in[inIndex]) != visited.end()) { cout << "we're at a leaf" << endl; postorder(tempTree); cout << "------------------------------" << endl; while (inIndex < in.size() - 1 && visited.find(in[++inIndex]) != visited.end()); return; } if (preIndex >= pre.size() - 1 || inIndex >= in.size() - 1) { cout << "we're at end of line" << endl; if (curr == NULL) cout << "NULLLLL" << endl; else cout << curr->val << endl; postorder(tempTree); cout << "------------------------------" << endl; return; } cout << "before Left" << endl; postorder(tempTree); stopper(); cout << "------------------------------" << endl; // Go left if (preIndex < pre.size()) { curr->left = new TreeNode(pre[preIndex]); visited.insert(pre[preIndex]); preIndex++; dfs(curr->left, preIndex, inIndex); } cout << "before right" << endl; postorder(tempTree); stopper(); cout << "------------------------------" << endl; // Go Right if (preIndex < pre.size()) { curr->right = new TreeNode(pre[preIndex]); visited.insert(pre[preIndex]); preIndex++; dfs(curr->right, preIndex, inIndex); } cout << "after right" << endl; postorder(tempTree); stopper(); cout << "------------------------------" << endl; }; TreeNode* handleEdgeCase() { TreeNode* tree = new TreeNode(pre[0]); if(pre[1] == in[1]) tree->right = new TreeNode(pre[1]); else tree->left = new TreeNode(pre[1]); postorder(tree); return tree; }; void stopper() { int stop; cout << "\t\t\t\t\t"; cin >> stop; }; // -----Global Vars----- vector<int> in; vector<int> pre; TreeNode* tempTree; unordered_set<int> visited; };
[ "ethcf@yahoo.com" ]
ethcf@yahoo.com
4f1c5b1dcd11daeb2440be4bfa94bc87f59fb0b9
76546b84214220c449f2f27ac9a1d79f9bbd1195
/jrtplib/test1/simpletest.cpp
16e3644a202b948f15cdc5a211724227bbb80942
[]
no_license
bomoer/bkvoice
b548ade9a0bc9410c56daf65316086bbebf65432
f9890c6406ca9a3d73a8529a27b3800d0ce6f558
refs/heads/master
2020-07-21T21:50:22.188734
2012-10-25T16:04:21
2012-10-25T16:04:21
33,157,995
0
0
null
null
null
null
UTF-8
C++
false
false
2,229
cpp
#include "rtpsession.h" #include "rtpsessionparams.h" #include "rtpipv4address.h" #include "rtppacket.h" #include "rtpudpv4transmitter.h" #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdio.h> #include <sys/soundcard.h> #include <sys/ioctl.h> #include <fcntl.h> #include <iostream> #define PACKSIZE 130 int main(void) { int status,i; RTPSession s; RTPSessionParams sessparams; RTPUDPv4TransmissionParams transparams; char blaai[100]; transparams.SetPortbase(10000); sessparams.SetOwnTimestampUnit(1.0/8000.0); sessparams.SetUsePollThread(true); sessparams.SetMaximumPacketSize(10000); status = s.Create(sessparams,&transparams); s.SetLocalName((const uint8_t *)"Jori Liesenborgs",16); s.SetLocalEMail((const uint8_t *)"jori@lumumba.luc.ac.be",20); s.SetLocalNote((const uint8_t *)"Blaai",5); s.SetNameInterval(3); s.SetEMailInterval(5); s.SetNoteInterval(2); status = s.AddDestination(RTPIPv4Address(ntohl(inet_addr("192.168.2.115")),5000)); //status = s.AddDestination(RTPIPv4Address(ntohl(inet_addr("127.0.0.1")),7000)); int snd = open("/dev/dsp",O_RDWR); int val; val = 0; status = ioctl(snd,SNDCTL_DSP_STEREO,&val); val = 8; status = ioctl(snd,SNDCTL_DSP_SAMPLESIZE,&val); val = 8000; status = ioctl(snd,SNDCTL_DSP_SPEED,&val); val = 7 | (128<<16); ioctl(snd,SNDCTL_DSP_SETFRAGMENT,&val); i = 0; while (i++ < 40000) { if (i == 1000) { //std::cout <<"Disabling note" << std::endl; s.SetNoteInterval(0); } uint8_t data[PACKSIZE]; RTPTime t1 = RTPTime::CurrentTime(); status = read(snd,data,PACKSIZE); RTPTime t2 = RTPTime::CurrentTime(); t2 -= t1; printf("%d.%06d\n",t2.GetSeconds(),t2.GetMicroSeconds()); status = s.SendPacket(data,PACKSIZE,1,false,PACKSIZE); } close(snd); printf("Destroying...\n"); s.BYEDestroy(RTPTime(10,0),(const uint8_t *)"Leaving session",16); return 0; }
[ "qq271885846@ed4c09e6-f5e8-dd9c-d1e1-30c58becc500" ]
qq271885846@ed4c09e6-f5e8-dd9c-d1e1-30c58becc500
9e5952f3839e4acbe513b24bda7923e13dd72b49
ce161c98d5b1a69fd12b7af691709a76da55b44d
/codeforces/ABBYY_Cup_2_0_-_Easy/B1_Rectangular_Game.cpp
24eb74409eb1d22abfa4d90a6ced375fd557ae62
[]
no_license
cup2of2tea/CompetitiveProgramming
cb45d40ff0c27e2b9891eb135e4e5ef795014989
eaa9bfac351c0eb909c7686534fe647c31eaac65
refs/heads/master
2020-09-02T07:21:18.722266
2019-11-02T14:30:57
2019-11-02T14:30:57
219,165,630
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,433
cpp
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <sstream> #include <cmath> #include <algorithm> #include <map> #include <cstdio> #include <set> #include <ctime> #include <queue> #include <climits> #include <iterator> #define MOD 1000000007   #define LOCAL #ifdef ONLINE_JUDGE #undef LOCAL #endif   #ifdef LOCAL #define cin in #endif   using namespace std;   template < typename T,typename T2 > T2 fac(T n) { return n<2?1:fac<T,T2>(n-1)*n; }   template < typename T,typename T2,typename T3> T2 fac(T n, T3 mod) { return n<2?1:(fac<T,T2,T3>(n-1,mod)*n)%mod; } template <typename T> T nb_combinaisons(T k,T n) { if(n<k) return nb_combinaisons<T>(n,k); return fac<T,long long int>(n)/(fac<T,long long int>(n-k)*fac<T,long long int>(k)); }   template <typename T,typename T2> T nb_permutations(vector<T2> v) { T total=fac<T,T>(v.size()); map<T2,T> m; bool distinct=true; for(long long unsigned c=0; c<v.size(); c++) { m[v[c]]++; if(m[v[c]]-1) distinct=false; } for(typename map<T2,T>::iterator it=m.begin(); it!=m.end(); it++) total/=fac<T,T>(it->second); return total; }   template <typename T,typename T2,typename T3> T nb_permutations(vector<T2> v,T3 mod) { T total=fac<T,T,T3>(v.size(),mod); map<T2,T> m; bool distinct=true; for(long long unsigned c=0; c<v.size(); c++) { m[v[c]]++; if(m[v[c]]-1) distinct=false; } for(typename map<T2,T>::iterator it=m.begin(); it!=m.end(); it++) total/=fac<T,T>(it->second); return total%mod; }   string itoa_2(long long int n) { string s; stringstream ss; ss<<n; ss>>s; while(s.size()!=9) s='0'+s; return s; }   int pgcd (int a,int b) { if(a==0) return b; if(b==0) return a; return pgcd(b,a%b); }   string conversion(int n,int base) { string res=""; while(n!=0) { res=((char)('0'+n%base))+res; n/=base; } return res; }   map<int,int> m;   int bourrin(int n) { if(n==1) return 1; if(m[n]>0) return m[n]; int res=0; for(int c=1;c<n;c++) { if(n%c==0) res=max(res,bourrin(c)+n); } m[n]=res; return res; }   int main() { #ifdef LOCAL ifstream in("input.txt"); #endif int n; cin>>n; cout<<bourrin(n); }
[ "comtealexis@gmail.com" ]
comtealexis@gmail.com
f35a9b74592c2d58f59f29dda0a0673ae96ca088
4d2c81684ead286b5e4db9af29814f20accef5df
/coral/PyCoral/src/IConnectionServiceConfiguration.h
a8da0b79484d5c585f091f626bbb60806e303a53
[]
no_license
Teemperor/cms-externals
e0e1c33b9cc745b630e11a5e67ec68b257f5261a
119a977641d34c29a01826c68e8384f97789efaa
refs/heads/master
2021-08-30T20:14:39.551206
2017-12-19T08:52:17
2017-12-19T08:52:17
114,741,614
0
0
null
null
null
null
UTF-8
C++
false
false
610
h
#ifndef PYCORAL_ICONNECTIONSERVICECONFIGURATION_H #define PYCORAL_ICONNECTIONSERVICECONFIGURATION_H #ifdef _DEBUG #undef _DEBUG #include "Python.h" #define _DEBUG #else #include "Python.h" #endif namespace coral { class IConnectionServiceConfiguration; namespace PyCoral { typedef struct { PyObject_HEAD coral::IConnectionServiceConfiguration* object; // The underlying C++ type PyObject* parent; // A reference to the parent object } IConnectionServiceConfiguration; /// Returns the Python type PyTypeObject* IConnectionServiceConfiguration_Type(); } } #endif
[ "teemperor@gmail.com" ]
teemperor@gmail.com
9aa80482cf884dbc1d1f561f1f86b229868ef2b3
8583b5bfc594b994f51d24d012e92ae66bf2e5ea
/src/BabylonCpp/include/babylon/misc/interfaces/iweb_request.h
bd6579dc0c2dbe2969068fed891c1106b9c74cd9
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
samdauwe/BabylonCpp
84b8e51b59f04a847681a97fa6fe0a5c554e9e1f
3dad13a666299cbcf2e2db5b24575c19743e1000
refs/heads/master
2022-01-09T02:49:55.057544
2022-01-02T19:27:12
2022-01-02T19:27:12
77,682,359
309
41
Apache-2.0
2020-11-06T12:16:17
2016-12-30T11:29:05
C++
UTF-8
C++
false
false
577
h
#ifndef BABYLON_MISC_INTERFACES_IWEB_REQUEST_H #define BABYLON_MISC_INTERFACES_IWEB_REQUEST_H #include <string> namespace BABYLON { /** * @brief Interface used to define the mechanism to get data from the network. */ struct IWebRequest { /** * Returns client's response url */ std::string responseURL; /** * Returns client's status */ std::string status; /** * Returns client's status as a text */ std::string statusText; }; // end of struct IWebRequest } // end of namespace BABYLON #endif // end of BABYLON_MISC_INTERFACES_IWEB_REQUEST_H
[ "sam.dauwe@gmail.com" ]
sam.dauwe@gmail.com
ada79ab51b23f8db4ef5d46826ae9728b50bf9ed
06ba1133cc3e93ef31f1456761678b48ed5dc09d
/Assignments/01_variable_operator_expression/Set_1/07.cpp
2bd394855ad18cedaf6135476d070449473d8d13
[]
no_license
uhdang/cppforschool
9c1991712534c7b61ed1173b312b774785a9ef3b
75ff692f5fef3e3737b22b24ce2cf9416db24210
refs/heads/master
2020-03-20T10:48:28.201496
2018-07-10T21:12:09
2018-07-10T21:12:09
137,385,071
0
0
null
null
null
null
UTF-8
C++
false
false
270
cpp
#include <iostream> using namespace std; int main() { int a, b, c; cout << "BEFORE\n"; cout << "a: "; cin >> a; cout << "b: "; cin >> b; c = a; a = b; b = c; cout << "AFTER\n"; cout << "a: " << a << " b: " << b << "\n"; }
[ "uhdang@gmail.com" ]
uhdang@gmail.com
088688faaa6612e2810a6997f7d05c49c23d824e
458b1808572fa333f3e193e10232b3e5b650b30e
/dbms/programs/performance-test/PerformanceTestInfo.h
b5e2f0c0ac1b847b4cf3b3811ad0d63afd5f6f50
[ "Apache-2.0" ]
permissive
liang0/ClickHouse
b5c3e9e923ae9ae8640fdde26ea1724462962c30
6db73152d2e1b7b35a03b7e146549dd84fe2992d
refs/heads/master
2020-04-27T23:50:17.071538
2019-03-10T03:16:51
2019-03-10T03:16:51
174,792,462
1
0
Apache-2.0
2019-03-10T07:41:02
2019-03-10T07:41:02
null
UTF-8
C++
false
false
1,492
h
#pragma once #include <string> #include <vector> #include <map> #include <Interpreters/Settings.h> #include <Poco/Util/XMLConfiguration.h> #include <Poco/AutoPtr.h> #include "StopConditionsSet.h" #include "TestStopConditions.h" #include "TestStats.h" namespace DB { enum class ExecutionType { Loop, Once }; using XMLConfiguration = Poco::Util::XMLConfiguration; using XMLConfigurationPtr = Poco::AutoPtr<XMLConfiguration>; using StringToVector = std::map<std::string, Strings>; /// Class containing all info to run performance test class PerformanceTestInfo { public: PerformanceTestInfo(XMLConfigurationPtr config, const std::string & profiles_file_, const Settings & global_settings_); std::string test_name; std::string path; std::string main_metric; Strings queries; std::string profiles_file; Settings settings; ExecutionType exec_type; StringToVector substitutions; size_t times_to_run; std::vector<TestStopConditions> stop_conditions_by_run; Strings create_queries; Strings fill_queries; Strings drop_queries; private: void applySettings(XMLConfigurationPtr config); void extractQueries(XMLConfigurationPtr config); void processSubstitutions(XMLConfigurationPtr config); void getExecutionType(XMLConfigurationPtr config); void getStopConditions(XMLConfigurationPtr config); void getMetrics(XMLConfigurationPtr config); void extractAuxiliaryQueries(XMLConfigurationPtr config); }; }
[ "alesapin@gmail.com" ]
alesapin@gmail.com
dc57bb00818672a42b1f16ef0a18ff53e9a25a4d
c628b866346ec5c4399945f455c27160b076d927
/Hmwrk/Assignment_4/NumDays.h
bcf05b48d9c4de4ba50a7ae6b1887acdf389fb64
[]
no_license
NKanabolo/KanaboloNornubari_CSC17a_43950
6db39a08552592c84382c16191b0d7fa5b000074
b451fed70b4b7896e6f7ee0a10fa7eeeaf79e87a
refs/heads/master
2021-01-19T17:22:34.160749
2015-06-13T01:48:35
2015-06-13T01:48:35
32,039,909
0
0
null
null
null
null
UTF-8
C++
false
false
864
h
/* * File: NumDays.h * Author: Nornubari Kanabolo * */ #ifndef NUMDAYS_H #define NUMDAYS_H class NumDays { private: float days; //Days of work in a 8 hour shift float hours; //Hours worked public: NumDays(float); //Constructor float getDay() const {return days;} //Accessor for days float getHour() const {return hours;} //Accessor for hours NumDays operator+(const NumDays&); // + operator NumDays operator-(const NumDays&); // - operator NumDays operator++(int); //postfix ++ operator NumDays operator++(); //prefix ++ operator NumDays operator--(int); //postfix -- operator NumDays operator--(); //prefix -- operator }; #endif /* NUMDAYS_H */
[ "nornkable@yahoo.com" ]
nornkable@yahoo.com
88b82a360a3a97f1bc0e6ebf4582196073711ab7
d7ba25c15b630b44f2904638681fd750d6006533
/caffe2/contrib/fbcollective/vendor/fbcollective/allreduce_ring.h
388d4cc4de32106fed3f6a60c6e08806b868f2e2
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
Mathpix/caffe2
6764bf51fdc1cfae37224329f50ff8aa6c3b246f
6687f8447545250cdeb63a4a9baaa6e25c32ad0d
refs/heads/master
2020-05-25T01:18:43.687134
2017-03-14T00:25:40
2017-03-14T00:31:43
84,896,813
1
0
null
2017-03-14T02:34:03
2017-03-14T02:34:03
null
UTF-8
C++
false
false
3,158
h
#pragma once #include <stddef.h> #include <string.h> #include "fbcollective/allreduce.h" #include "fbcollective/context.h" namespace fbcollective { template <typename T> class AllreduceRing : public Allreduce<T> { public: AllreduceRing( const std::shared_ptr<Context>& context, std::vector<T*> ptrs, int dataSize, typename Allreduce<T>::ReduceFunction fn = nullptr) : Allreduce<T>(context, fn), ptrs_(ptrs), dataSize_(dataSize), dataSizeBytes_(dataSize * sizeof(T)), leftPair_(this->getLeftPair()), rightPair_(this->getRightPair()) { inbox_ = static_cast<T*>(malloc(dataSizeBytes_)); outbox_ = static_cast<T*>(malloc(dataSizeBytes_)); // Buffer to send to (rank+1). sendDataBuf_ = rightPair_->createSendBuffer(0, outbox_, dataSizeBytes_); // Buffer that (rank-1) writes to. recvDataBuf_ = leftPair_->createRecvBuffer(0, inbox_, dataSizeBytes_); // Dummy buffers for localized barrier. // Before sending to the right, we only need to know that the node // on the right is done using the inbox that's about to be written // into. No need for a global barrier. sendNotificationBuf_ = leftPair_->createSendBuffer(1, &dummy_, sizeof(dummy_)); recvNotificationBuf_ = rightPair_->createRecvBuffer(1, &dummy_, sizeof(dummy_)); } virtual ~AllreduceRing() { if (inbox_ != nullptr) { free(inbox_); } if (outbox_ != nullptr) { free(outbox_); } } void Run() { // Reduce specified pointers into ptrs_[0] for (int i = 1; i < ptrs_.size(); i++) { this->fn_(ptrs_[0], ptrs_[i], dataSize_); } // Intialize outbox with locally reduced values memcpy(outbox_, ptrs_[0], dataSizeBytes_); int numRounds = this->contextSize_ - 1; for (int round = 0; round < numRounds; round++) { // Initiate write to inbox of node on the right sendDataBuf_->send(); // Wait for inbox write from node on the left recvDataBuf_->waitRecv(); // Reduce this->fn_(ptrs_[0], inbox_, dataSize_); // Wait for outbox write to complete sendDataBuf_->waitSend(); // Prepare for next round if necessary if (round < (numRounds - 1)) { memcpy(outbox_, inbox_, dataSizeBytes_); } // Send notification to node on the left that // this node is ready for an inbox write. sendNotificationBuf_->send(); // Wait for notification from node on the right recvNotificationBuf_->waitRecv(); } // Broadcast ptrs_[0] for (int i = 1; i < ptrs_.size(); i++) { memcpy(ptrs_[i], ptrs_[0], dataSizeBytes_); } } protected: std::vector<T*> ptrs_; int dataSize_; int dataSizeBytes_; std::unique_ptr<transport::Pair>& leftPair_; std::unique_ptr<transport::Pair>& rightPair_; T* inbox_; T* outbox_; std::unique_ptr<transport::Buffer> sendDataBuf_; std::unique_ptr<transport::Buffer> recvDataBuf_; int dummy_; std::unique_ptr<transport::Buffer> sendNotificationBuf_; std::unique_ptr<transport::Buffer> recvNotificationBuf_; }; } // namespace fbcollective
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
003907992f5fa3f454e66bbaceebb0fcd0b11db9
a1b98c95fb5361aa9a96ccefbbef3654509c59fd
/Chapter_05/exercise_16c.cpp
7d5eee8ec739dda30290f061617a0261950818c0
[]
no_license
ZoroOP/CppPrimer
121bcafd6852c583fd773c6c78dccfd5f6952f09
a28f0b3f2ffb57dc9c38b9a5c173e375f7944db6
refs/heads/master
2020-07-17T07:14:57.027588
2017-10-13T11:27:25
2017-10-13T11:27:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
943
cpp
// The `while` loop is particularly good at executing while some condition // holds; for example, when we need to read values until end-of-file. The // `for` loop is generally thought of as a step loop: An index steps through // a range of values in a collection. Write an idiomatic use of each loop // and then rewrite each using the other loop construct. If you could use // only one loop, which would you choose? Why? // `while` use case rewritten using `for` loop. #include <iostream> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; int main() { cout << "Enter some numbers: "; vector<int> buffer; int userInput; for (/* not required */; cin >> userInput; buffer.push_back(userInput)) { // not required } // Print buffer cout << "You entered: "; for (auto number : buffer) { cout << number << " "; } cout << endl; return 0; }
[ "adobrich@internode.on.net" ]
adobrich@internode.on.net
acb2c459c681ef0dd88c6b6f1ad3e2c8fb56d2c8
d13b7683011850824f955745bbe104e1fd1c3c4b
/small-and-simple-programs-in-qt/peoples-survival-qt/peoples-survival/people.h
e1b68debfec787048fe4a858e506fbca298d1aaf
[ "MIT" ]
permissive
gusenov/examples-qt
44a51f7a843ffcecc996392a812e2c026e9c706c
083a51feedf6cefe82b6de79d701da23d1da2a2f
refs/heads/master
2022-04-30T05:12:04.066992
2022-04-13T03:53:17
2022-04-13T03:53:17
129,376,220
6
0
null
null
null
null
UTF-8
C++
false
false
804
h
#ifndef PEOPLE_H #define PEOPLE_H #include "parameter.h" // Класс представляющий собой численность населения: class People : public Parameter // унаследован от Parameter. { // Публичные члены класса: public: People(int numberOfPeople); // Виртуальная функция, которая возвращает баллы: virtual float getScore(); // Виртуальная функция, которая определяет умрёт ли народ или нужно считать баллы: virtual bool willDie(); // Приватные члены класса: private: // Количество людей: int _numberOfPeople; }; #endif // PEOPLE_H
[ "gusenov@live.ru" ]
gusenov@live.ru
c8c72318448de8a5ee6c528655e6e6e695ce9993
c905612f0c6d618d7396ebfafda8fa878632d32a
/src/window.cc
0d68af7ec2a2717870a18cf5a1aabb0ed5870ef2
[ "MIT" ]
permissive
jube/std_hmi
2f3878d17e7ef9c91e5c49780b02a0f0cf3ffbd9
08b9cb61edeb048a6a2a0b24f5c7b12c9e377852
refs/heads/master
2020-03-11T20:36:09.224985
2018-04-26T12:08:02
2018-04-26T12:08:02
130,240,947
5
0
null
null
null
null
UTF-8
C++
false
false
10,537
cc
#include <bits/window.h> #include <cassert> #include <atomic> #include <iostream> #include <SDL.h> namespace hmi { namespace { Uint32 compute_sdl_flags(window_flags hints) { Uint32 flags = SDL_WINDOW_OPENGL; if ((hints & window_flags::resizable) != window_flags::none) { flags |= SDL_WINDOW_RESIZABLE; } if ((hints & window_flags::visible) != window_flags::none) { flags |= SDL_WINDOW_SHOWN; } else { flags |= SDL_WINDOW_HIDDEN; } if ((hints & window_flags::decorated) == window_flags::none) { flags |= SDL_WINDOW_BORDERLESS; } return flags; } window_flags compute_window_flags(Uint32 flags) { window_flags res = window_flags::none; if ((flags & SDL_WINDOW_RESIZABLE) != 0) { res |= window_flags::resizable; } if ((flags & SDL_WINDOW_SHOWN) != 0) { res |= window_flags::visible; } if ((flags & SDL_WINDOW_BORDERLESS) == 0) { res |= window_flags::decorated; } return res; } mouse_button compute_mouse_button(Uint8 button) { switch (button) { case SDL_BUTTON_LEFT: return mouse_button::left; case SDL_BUTTON_MIDDLE: return mouse_button::middle; case SDL_BUTTON_RIGHT: return mouse_button::right; case SDL_BUTTON_X1: return mouse_button::x1; case SDL_BUTTON_X2: return mouse_button::x2; } return mouse_button::other; } keyboard_modifiers compute_keyboard_modifiers(Uint16 mod) { keyboard_modifiers modifiers = keyboard_modifiers::none; if ((mod & KMOD_SHIFT) != 0) { modifiers |= keyboard_modifiers::shift; } if ((mod & KMOD_CTRL) != 0) { modifiers |= keyboard_modifiers::control; } if ((mod & KMOD_ALT) != 0) { modifiers |= keyboard_modifiers::alt; } if ((mod & KMOD_GUI) != 0) { modifiers |= keyboard_modifiers::super; } return modifiers; } std::atomic_int g_loaded{0}; } window::window(std::string_view title, vec2i size, window_flags hints) : m_window(nullptr) , m_should_close(false) { if (g_loaded.fetch_add(1) == 0) { // we are the first if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "Unable to initialize SDL: " << SDL_GetError() << '\n'; return; } // must be set before window creating SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); } std::string title_string(title); auto flags = compute_sdl_flags(hints); m_window = SDL_CreateWindow(title_string.data(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, size.width, size.height, flags); if (m_window == nullptr) { std::cerr << "Unable to create window: " << SDL_GetError() << '\n'; return; } } window::~window() { if (m_window != nullptr) { SDL_DestroyWindow(m_window); } if (g_loaded.fetch_sub(1) == 1) { // we are the last SDL_Quit(); } } window::window(window&& other) : m_window(std::exchange(other.m_window, nullptr)) , m_should_close(other.m_should_close) { g_loaded.fetch_add(1); } window& window::operator=(window&& other) { std::swap(m_window, other.m_window); std::swap(m_should_close, other.m_should_close); g_loaded.fetch_add(1); return *this; } // lifetime bool window::is_open() const { return !m_should_close; } void window::close() { m_should_close = true; } // properties std::string_view window::get_title() const { return SDL_GetWindowTitle(m_window); } void window::set_title(std::string_view title) { std::string title_string(title); SDL_SetWindowTitle(m_window, title_string.data()); } vec2i window::get_position() const { vec2i position; SDL_GetWindowPosition(m_window, &position.x, &position.y); return position; } void window::set_position(vec2i position) { SDL_SetWindowPosition(m_window, position.x, position.y); } vec2i window::get_size() const { vec2i size; SDL_GetWindowSize(m_window, &size.width, &size.height); return size; } void window::set_size(vec2i size) { SDL_SetWindowSize(m_window, size.width, size.height); } window_flags window::get_flags() const { auto flags = SDL_GetWindowFlags(m_window); return compute_window_flags(flags); } void window::set_resizable(bool resizable) { SDL_SetWindowResizable(m_window, resizable ? SDL_TRUE : SDL_FALSE); } void window::set_visible(bool visible) { if (visible) { SDL_ShowWindow(m_window); } else { SDL_HideWindow(m_window); } } void window::set_decorated(bool decorated) { SDL_SetWindowBordered(m_window, decorated ? SDL_TRUE : SDL_FALSE); } void window::set_fullscreen(bool fullscreen) { if (fullscreen) { SDL_SetWindowFullscreen(m_window, SDL_WINDOW_FULLSCREEN_DESKTOP); } else { SDL_SetWindowFullscreen(m_window, 0); } } // state bool window::is_minimized() const { auto flags = SDL_GetWindowFlags(m_window); return (flags & SDL_WINDOW_MINIMIZED) != 0; } void window::minimize() { SDL_MinimizeWindow(m_window); } bool window::is_maximized() const { auto flags = SDL_GetWindowFlags(m_window); return (flags & SDL_WINDOW_MAXIMIZED) != 0; } void window::mazimize() { SDL_MaximizeWindow(m_window); } void window::restore() { SDL_RestoreWindow(m_window); } // events namespace { std::optional<window_event> translate_event(Uint32 window_id, const SDL_Event& event) { switch (event.type) { case SDL_WINDOWEVENT: if (window_id != event.window.windowID) { return std::nullopt; } switch (event.window.event) { case SDL_WINDOWEVENT_SIZE_CHANGED: { window_events::resized data; data.size.width = event.window.data1; data.size.height = event.window.data2; return data; } case SDL_WINDOWEVENT_CLOSE: return window_events::closed{}; case SDL_WINDOWEVENT_FOCUS_GAINED: return window_events::focus_gained{}; case SDL_WINDOWEVENT_FOCUS_LOST: return window_events::focus_lost{}; case SDL_WINDOWEVENT_ENTER: return window_events::mouse_entered{}; case SDL_WINDOWEVENT_LEAVE: return window_events::mouse_left{}; default: return std::nullopt; } break; case SDL_QUIT: return window_events::closed{}; case SDL_KEYDOWN: assert(event.key.state == SDL_PRESSED); if (event.key.repeat == 0) { window_events::keyboard_key_pressed data; data.keycode = static_cast<keyboard_keycode>(event.key.keysym.sym); data.scancode = static_cast<keyboard_scancode>(event.key.keysym.scancode); data.modifiers = compute_keyboard_modifiers(event.key.keysym.mod); return data; } else { window_events::keyboard_key_repeated data; data.keycode = static_cast<keyboard_keycode>(event.key.keysym.sym); data.scancode = static_cast<keyboard_scancode>(event.key.keysym.scancode); data.modifiers = compute_keyboard_modifiers(event.key.keysym.mod); return data; } break; case SDL_KEYUP: { assert(event.key.state == SDL_RELEASED); window_events::keyboard_key_released data; data.keycode = static_cast<keyboard_keycode>(event.key.keysym.sym); data.scancode = static_cast<keyboard_scancode>(event.key.keysym.scancode); data.modifiers = compute_keyboard_modifiers(event.key.keysym.mod); return data; } case SDL_MOUSEWHEEL: { if (event.wheel.which == SDL_TOUCH_MOUSEID) { return std::nullopt; } window_events::mouse_wheel_scrolled data; data.offset.x = event.wheel.x; data.offset.y = event.wheel.y; return data; } case SDL_MOUSEBUTTONDOWN: { assert(event.button.state == SDL_PRESSED); if (event.button.which == SDL_TOUCH_MOUSEID) { return std::nullopt; } window_events::mouse_button_pressed data; data.button = compute_mouse_button(event.button.button); data.position.x = event.button.x; data.position.y = event.button.y; return data; } case SDL_MOUSEBUTTONUP: { assert(event.button.state == SDL_RELEASED); if (event.button.which == SDL_TOUCH_MOUSEID) { return std::nullopt; } window_events::mouse_button_released data; data.button = compute_mouse_button(event.button.button); data.position.x = event.button.x; data.position.y = event.button.y; return data; } case SDL_MOUSEMOTION: { if (event.motion.which == SDL_TOUCH_MOUSEID) { return std::nullopt; } window_events::mouse_moved data; data.position.x = event.motion.x; data.position.y = event.motion.y; return data; } default: break; } return std::nullopt; } } std::optional<window_event> window::poll_event() { Uint32 window_id = SDL_GetWindowID(m_window); for (;;) { SDL_Event event; int status = SDL_PollEvent(&event); if (status == 0) { return std::nullopt; } std::optional<window_event> event_maybe = translate_event(window_id, event); if (event_maybe) { return event_maybe; } } } std::optional<window_event> window::wait_event() { Uint32 window_id = SDL_GetWindowID(m_window); for (;;) { SDL_Event event; int status = SDL_WaitEvent(&event); if (status == 0) { return std::nullopt; } std::optional<window_event> event_maybe = translate_event(window_id, event); if (event_maybe) { return event_maybe; } } } // renderer renderer window::get_renderer() { return renderer(m_window); } } // namespace hmi
[ "julien.bernard@univ-fcomte.fr" ]
julien.bernard@univ-fcomte.fr
8da756ed26e414e5a083b73f811fb17ad3104183
7d3edd7f12e52839aa192a1b8fe89d1c050a2197
/HyperPlatform/vmm.cpp
b9fe5fc5b26d01a91e9750e636762ce1bceee5dc
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
JulianVolodia/HyperPlatform
af2c5e974667417afd30944ed9b164f217d806c9
b070cb648d30c64130a07a961a6270a946fd3ed5
refs/heads/master
2021-05-01T03:45:07.780326
2016-07-20T16:13:16
2016-07-20T16:13:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,345
cpp
// Copyright (c) 2015-2016, tandasat. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. /// @file /// Implements VMM functions. #include "vmm.h" #include <intrin.h> #include "asm.h" #include "common.h" #include "ept.h" #include "log.h" #include "util.h" #ifndef HYPERPLATFORM_PERFORMANCE_ENABLE_PERFCOUNTER #define HYPERPLATFORM_PERFORMANCE_ENABLE_PERFCOUNTER 1 #endif // HYPERPLATFORM_PERFORMANCE_ENABLE_PERFCOUNTER #include "performance.h" extern "C" { //////////////////////////////////////////////////////////////////////////////// // // macro utilities // //////////////////////////////////////////////////////////////////////////////// // // constants and macros // // Whether VM-exit recording is enabled static const long kVmmpEnableRecordVmExit = false; // How many events should be recorded per a processor static const long kVmmpNumberOfRecords = 100; // How many processors are supported for recording static const long kVmmpNumberOfProcessors = 2; //////////////////////////////////////////////////////////////////////////////// // // types // // Represents raw structure of stack of VMM when VmmVmExitHandler() is called struct VmmInitialStack { GpRegisters gp_regs; ULONG_PTR reserved; ProcessorData *processor_data; }; // Things need to be read and written by each VM-exit handler struct GuestContext { union { VmmInitialStack *stack; GpRegisters *gp_regs; }; FlagRegister flag_reg; ULONG_PTR ip; ULONG_PTR cr8; KIRQL irql; bool vm_continue; }; #if defined(_AMD64_) static_assert(sizeof(GuestContext) == 40, "Size check"); #else static_assert(sizeof(GuestContext) == 20, "Size check"); #endif // Context at the moment of vmexit struct VmExitHistory { GpRegisters gp_regs; ULONG_PTR ip; VmExitInformation exit_reason; ULONG_PTR exit_qualification; ULONG_PTR instruction_info; }; //////////////////////////////////////////////////////////////////////////////// // // prototypes // bool __stdcall VmmVmExitHandler(_Inout_ VmmInitialStack *stack); DECLSPEC_NORETURN void __stdcall VmmVmxFailureHandler( _Inout_ AllRegisters *all_regs); static void VmmpHandleVmExit(_Inout_ GuestContext *guest_context); DECLSPEC_NORETURN static void VmmpHandleTripleFault( _Inout_ GuestContext *guest_context); DECLSPEC_NORETURN static void VmmpHandleUnexpectedExit( _Inout_ GuestContext *guest_context); static void VmmpHandleMonitorTrap(_Inout_ GuestContext *guest_context); static void VmmpHandleException(_Inout_ GuestContext *guest_context); static void VmmpHandleCpuid(_Inout_ GuestContext *guest_context); static void VmmpHandleRdtsc(_Inout_ GuestContext *guest_context); static void VmmpHandleRdtscp(_Inout_ GuestContext *guest_context); static void VmmpHandleXsetbv(_Inout_ GuestContext *guest_context); static void VmmpHandleMsrReadAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleMsrWriteAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleMsrAccess(_Inout_ GuestContext *guest_context, _In_ bool read_access); static void VmmpHandleGdtrOrIdtrAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleLdtrOrTrAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleDrAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleIoPort(_Inout_ GuestContext *guest_context); static void VmmpHandleCrAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleVmx(_Inout_ GuestContext *guest_context); static void VmmpHandleVmCall(_Inout_ GuestContext *guest_context); static void VmmpHandleInvalidateInternalCaches( _Inout_ GuestContext *guest_context); static void VmmpHandleInvalidateTLBEntry(_Inout_ GuestContext *guest_context); static void VmmpHandleEptViolation(_Inout_ GuestContext *guest_context); static void VmmpHandleEptMisconfig(_Inout_ GuestContext *guest_context); static ULONG_PTR *VmmpSelectRegister(_In_ ULONG index, _In_ GuestContext *guest_context); static void VmmpDumpGuestSelectors(); static void VmmpAdjustGuestInstructionPointer(_In_ ULONG_PTR guest_ip); static void VmmpIoWrapper(_In_ bool to_memory, _In_ bool is_string, _In_ SIZE_T size_of_access, _In_ unsigned short port, _Inout_ void *address, _In_ unsigned long count); static void VmmpSaveExtendedProcessorState(_Inout_ GuestContext *guest_context); static void VmmpRestoreExtendedProcessorState(_In_ GuestContext *guest_context); static void VmmpIndicateSuccessfulVmcall(_In_ GuestContext *guest_context); static void VmmpHandleVmCallTermination(_In_ GuestContext *guest_context); //////////////////////////////////////////////////////////////////////////////// // // variables // // Those variables are all for diagnostic purpose static ULONG g_vmmp_next_history_index[kVmmpNumberOfProcessors]; static VmExitHistory g_vmmp_vm_exit_history[kVmmpNumberOfProcessors] [kVmmpNumberOfRecords]; //////////////////////////////////////////////////////////////////////////////// // // implementations // // A high level VMX handler called from AsmVmExitHandler(). // Return true for vmresume, or return false for vmxoff. #pragma warning(push) #pragma warning(disable : 28167) _Use_decl_annotations_ bool __stdcall VmmVmExitHandler(VmmInitialStack *stack) { // Save guest's context and raise IRQL as quick as possible const auto guest_irql = KeGetCurrentIrql(); const auto guest_cr8 = IsX64() ? __readcr8() : 0; if (guest_irql < DISPATCH_LEVEL) { KeRaiseIrqlToDpcLevel(); } NT_ASSERT(stack->reserved == MAXULONG_PTR); // Capture the current guest state GuestContext guest_context = {stack, UtilVmRead(VmcsField::kGuestRflags), UtilVmRead(VmcsField::kGuestRip), guest_cr8, guest_irql, true}; guest_context.gp_regs->sp = UtilVmRead(VmcsField::kGuestRsp); VmmpSaveExtendedProcessorState(&guest_context); // Dispatch the current VM-exit event VmmpHandleVmExit(&guest_context); VmmpRestoreExtendedProcessorState(&guest_context); // Restore guest's context if (guest_context.irql < DISPATCH_LEVEL) { KeLowerIrql(guest_context.irql); } // Apply possibly updated CR8 by the handler if (IsX64()) { __writecr8(guest_context.cr8); } return guest_context.vm_continue; } #pragma warning(pop) // Dispatches VM-exit to a corresponding handler _Use_decl_annotations_ static void VmmpHandleVmExit( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const VmExitInformation exit_reason = { static_cast<ULONG32>(UtilVmRead(VmcsField::kVmExitReason))}; if (kVmmpEnableRecordVmExit) { // Save them for ease of trouble shooting const auto processor = KeGetCurrentProcessorNumberEx(nullptr); auto &index = g_vmmp_next_history_index[processor]; auto &history = g_vmmp_vm_exit_history[processor][index]; history.gp_regs = *guest_context->gp_regs; history.ip = guest_context->ip; history.exit_reason = exit_reason; history.exit_qualification = UtilVmRead(VmcsField::kExitQualification); history.instruction_info = UtilVmRead(VmcsField::kVmxInstructionInfo); if (++index == kVmmpNumberOfRecords) { index = 0; } } switch (exit_reason.fields.reason) { case VmxExitReason::kExceptionOrNmi: VmmpHandleException(guest_context); break; case VmxExitReason::kTripleFault: VmmpHandleTripleFault(guest_context); break; case VmxExitReason::kCpuid: VmmpHandleCpuid(guest_context); break; case VmxExitReason::kInvd: VmmpHandleInvalidateInternalCaches(guest_context); break; case VmxExitReason::kInvlpg: VmmpHandleInvalidateTLBEntry(guest_context); break; case VmxExitReason::kRdtsc: VmmpHandleRdtsc(guest_context); break; case VmxExitReason::kCrAccess: VmmpHandleCrAccess(guest_context); break; case VmxExitReason::kDrAccess: VmmpHandleDrAccess(guest_context); break; case VmxExitReason::kIoInstruction: VmmpHandleIoPort(guest_context); break; case VmxExitReason::kMsrRead: VmmpHandleMsrReadAccess(guest_context); break; case VmxExitReason::kMsrWrite: VmmpHandleMsrWriteAccess(guest_context); break; case VmxExitReason::kMonitorTrapFlag: VmmpHandleMonitorTrap(guest_context); break; case VmxExitReason::kGdtrOrIdtrAccess: VmmpHandleGdtrOrIdtrAccess(guest_context); break; case VmxExitReason::kLdtrOrTrAccess: VmmpHandleLdtrOrTrAccess(guest_context); break; case VmxExitReason::kEptViolation: VmmpHandleEptViolation(guest_context); break; case VmxExitReason::kEptMisconfig: VmmpHandleEptMisconfig(guest_context); break; case VmxExitReason::kVmcall: VmmpHandleVmCall(guest_context); break; case VmxExitReason::kVmclear: case VmxExitReason::kVmlaunch: case VmxExitReason::kVmptrld: case VmxExitReason::kVmptrst: case VmxExitReason::kVmread: case VmxExitReason::kVmresume: case VmxExitReason::kVmwrite: case VmxExitReason::kVmoff: case VmxExitReason::kVmon: VmmpHandleVmx(guest_context); break; case VmxExitReason::kRdtscp: VmmpHandleRdtscp(guest_context); break; case VmxExitReason::kXsetbv: VmmpHandleXsetbv(guest_context); break; default: VmmpHandleUnexpectedExit(guest_context); break; } } // Triple fault VM-exit. Fatal error. _Use_decl_annotations_ static void VmmpHandleTripleFault( GuestContext *guest_context) { VmmpDumpGuestSelectors(); HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kTripleFaultVmExit, reinterpret_cast<ULONG_PTR>(guest_context), guest_context->ip, 0); } // Unexpected VM-exit. Fatal error. _Use_decl_annotations_ static void VmmpHandleUnexpectedExit( GuestContext *guest_context) { VmmpDumpGuestSelectors(); HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnexpectedVmExit, reinterpret_cast<ULONG_PTR>(guest_context), 0, 0); } // MTF VM-exit _Use_decl_annotations_ static void VmmpHandleMonitorTrap( GuestContext *guest_context) { VmmpDumpGuestSelectors(); HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnexpectedVmExit, reinterpret_cast<ULONG_PTR>(guest_context), 0, 0); } // Interrupt _Use_decl_annotations_ static void VmmpHandleException( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const VmExitInterruptionInformationField exception = { static_cast<ULONG32>(UtilVmRead(VmcsField::kVmExitIntrInfo))}; if (static_cast<interruption_type>(exception.fields.interruption_type) == interruption_type::kHardwareException) { // Hardware exception if (static_cast<InterruptionVector>(exception.fields.vector) == InterruptionVector::kPageFaultException) { // #PF const PageFaultErrorCode fault_code = { static_cast<ULONG32>(UtilVmRead(VmcsField::kVmExitIntrErrorCode))}; const auto fault_address = UtilVmRead(VmcsField::kExitQualification); VmEntryInterruptionInformationField inject = {}; inject.fields.interruption_type = exception.fields.interruption_type; inject.fields.vector = exception.fields.vector; inject.fields.deliver_error_code = true; inject.fields.valid = true; AsmWriteCR2(fault_address); UtilVmWrite(VmcsField::kVmEntryExceptionErrorCode, fault_code.all); UtilVmWrite(VmcsField::kVmEntryIntrInfoField, inject.all); HYPERPLATFORM_LOG_INFO_SAFE("GuestIp= %p, #PF Fault= %p Code= 0x%2x", guest_context->ip, fault_address, fault_code); } else if (static_cast<InterruptionVector>(exception.fields.vector) == InterruptionVector::kGeneralProtectionException) { // # GP const auto error_code = static_cast<ULONG32>(UtilVmRead(VmcsField::kVmExitIntrErrorCode)); VmEntryInterruptionInformationField inject = {}; inject.fields.interruption_type = exception.fields.interruption_type; inject.fields.vector = exception.fields.vector; inject.fields.deliver_error_code = true; inject.fields.valid = true; UtilVmWrite(VmcsField::kVmEntryExceptionErrorCode, error_code); UtilVmWrite(VmcsField::kVmEntryIntrInfoField, inject.all); HYPERPLATFORM_LOG_INFO_SAFE("GuestIp= %p, #GP Code= 0x%2x", guest_context->ip, error_code); } else { HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); } } else if (static_cast<interruption_type>( exception.fields.interruption_type) == interruption_type::kSoftwareException) { // Software exception if (static_cast<InterruptionVector>(exception.fields.vector) == InterruptionVector::kBreakpointException) { // #BP VmEntryInterruptionInformationField inject = {}; inject.fields.interruption_type = exception.fields.interruption_type; inject.fields.vector = exception.fields.vector; inject.fields.deliver_error_code = false; inject.fields.valid = true; UtilVmWrite(VmcsField::kVmEntryIntrInfoField, inject.all); UtilVmWrite(VmcsField::kVmEntryInstructionLen, 1); HYPERPLATFORM_LOG_INFO_SAFE("GuestIp= %p, #BP ", guest_context->ip); } else { HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); } } else { HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); } } // CPUID _Use_decl_annotations_ static void VmmpHandleCpuid( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); unsigned int cpu_info[4] = {}; const auto function_id = static_cast<int>(guest_context->gp_regs->ax); const auto sub_function_id = static_cast<int>(guest_context->gp_regs->cx); if (function_id == 0 && sub_function_id == kHyperPlatformVmmBackdoorCode) { // Say "Pong by VMM!" when the back-door code was given guest_context->gp_regs->bx = 'gnoP'; guest_context->gp_regs->dx = ' yb '; guest_context->gp_regs->cx = '!MMV'; } else { __cpuidex(reinterpret_cast<int *>(cpu_info), function_id, sub_function_id); guest_context->gp_regs->ax = cpu_info[0]; guest_context->gp_regs->bx = cpu_info[1]; guest_context->gp_regs->cx = cpu_info[2]; guest_context->gp_regs->dx = cpu_info[3]; } VmmpAdjustGuestInstructionPointer(guest_context->ip); } // RDTSC _Use_decl_annotations_ static void VmmpHandleRdtsc( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); ULARGE_INTEGER tsc = {}; tsc.QuadPart = __rdtsc(); guest_context->gp_regs->dx = tsc.HighPart; guest_context->gp_regs->ax = tsc.LowPart; VmmpAdjustGuestInstructionPointer(guest_context->ip); } // RDTSCP _Use_decl_annotations_ static void VmmpHandleRdtscp( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); unsigned int tsc_aux = 0; ULARGE_INTEGER tsc = {}; tsc.QuadPart = __rdtscp(&tsc_aux); guest_context->gp_regs->dx = tsc.HighPart; guest_context->gp_regs->ax = tsc.LowPart; guest_context->gp_regs->cx = tsc_aux; VmmpAdjustGuestInstructionPointer(guest_context->ip); } // XSETBV. It is executed at the time of system resuming _Use_decl_annotations_ static void VmmpHandleXsetbv( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); ULARGE_INTEGER value = {}; value.LowPart = static_cast<ULONG>(guest_context->gp_regs->ax); value.HighPart = static_cast<ULONG>(guest_context->gp_regs->dx); _xsetbv(static_cast<ULONG>(guest_context->gp_regs->cx), value.QuadPart); VmmpAdjustGuestInstructionPointer(guest_context->ip); } // RDMSR _Use_decl_annotations_ static void VmmpHandleMsrReadAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); VmmpHandleMsrAccess(guest_context, true); } // WRMSR _Use_decl_annotations_ static void VmmpHandleMsrWriteAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); VmmpHandleMsrAccess(guest_context, false); } // RDMSR and WRMSR _Use_decl_annotations_ static void VmmpHandleMsrAccess( GuestContext *guest_context, bool read_access) { // Apply it for VMCS instead of a real MSR if a speficied MSR is either of // them. const auto msr = static_cast<Msr>(guest_context->gp_regs->cx); bool transfer_to_vmcs = false; VmcsField vmcs_field = {}; switch (msr) { case Msr::kIa32SysenterCs: vmcs_field = VmcsField::kGuestSysenterCs; transfer_to_vmcs = true; break; case Msr::kIa32SysenterEsp: vmcs_field = VmcsField::kGuestSysenterEsp; transfer_to_vmcs = true; break; case Msr::kIa32SysenterEip: vmcs_field = VmcsField::kGuestSysenterEip; transfer_to_vmcs = true; break; case Msr::kIa32GsBase: vmcs_field = VmcsField::kGuestGsBase; transfer_to_vmcs = true; break; case Msr::kIa32FsBase: vmcs_field = VmcsField::kGuestFsBase; break; default: break; } // Do not shadow 64bit fields because the current implmentation for x86 is not // able to handle it due to a simple use of UtilVmWrite() below. NT_ASSERT(UtilIsInBounds(vmcs_field, VmcsField::kIoBitmapA, VmcsField::kHostIa32PerfGlobalCtrlHigh) == false); LARGE_INTEGER msr_value = {}; if (read_access) { if (transfer_to_vmcs) { msr_value.QuadPart = UtilVmRead(vmcs_field); } else { msr_value.QuadPart = UtilReadMsr64(msr); } guest_context->gp_regs->ax = msr_value.LowPart; guest_context->gp_regs->dx = msr_value.HighPart; } else { msr_value.LowPart = static_cast<ULONG>(guest_context->gp_regs->ax); msr_value.HighPart = static_cast<ULONG>(guest_context->gp_regs->dx); if (transfer_to_vmcs) { UtilVmWrite(vmcs_field, static_cast<ULONG_PTR>(msr_value.QuadPart)); } else { UtilWriteMsr64(msr, msr_value.QuadPart); } } VmmpAdjustGuestInstructionPointer(guest_context->ip); } // LIDT, SIDT, LGDT and SGDT _Use_decl_annotations_ static void VmmpHandleGdtrOrIdtrAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const GdtrOrIdtrInstInformation exit_qualification = { static_cast<ULONG32>(UtilVmRead(VmcsField::kVmxInstructionInfo))}; // Calculate an address to be used for the instruction const auto displacement = UtilVmRead(VmcsField::kExitQualification); // Base ULONG_PTR base_value = 0; if (!exit_qualification.fields.base_register_invalid) { const auto register_used = VmmpSelectRegister( exit_qualification.fields.base_register, guest_context); base_value = *register_used; } // Index ULONG_PTR index_value = 0; if (!exit_qualification.fields.index_register_invalid) { const auto register_used = VmmpSelectRegister( exit_qualification.fields.index_register, guest_context); index_value = *register_used; switch (static_cast<Scaling>(exit_qualification.fields.scalling)) { case Scaling::kNoScaling: index_value = index_value; break; case Scaling::kScaleBy2: index_value = index_value * 2; break; case Scaling::kScaleBy4: index_value = index_value * 4; break; case Scaling::kScaleBy8: index_value = index_value * 8; break; default: break; } } auto operation_address = base_value + index_value + displacement; if (static_cast<AddressSize>(exit_qualification.fields.address_size) == AddressSize::k32bit) { operation_address &= MAXULONG; } // Update CR3 with that of the guest since below code is going to access // memory. const auto guest_cr3 = UtilVmRead(VmcsField::kGuestCr3); const auto vmm_cr3 = __readcr3(); __writecr3(guest_cr3); // Emulate the instruction auto descriptor_table_reg = reinterpret_cast<Idtr *>(operation_address); switch (static_cast<GdtrOrIdtrInstructionIdentity>( exit_qualification.fields.instruction_identity)) { case GdtrOrIdtrInstructionIdentity::kSgdt: descriptor_table_reg->base = UtilVmRead(VmcsField::kGuestGdtrBase); descriptor_table_reg->limit = static_cast<unsigned short>(UtilVmRead(VmcsField::kGuestGdtrLimit)); break; case GdtrOrIdtrInstructionIdentity::kSidt: descriptor_table_reg->base = UtilVmRead(VmcsField::kGuestIdtrBase); descriptor_table_reg->limit = static_cast<unsigned short>(UtilVmRead(VmcsField::kGuestIdtrLimit)); break; case GdtrOrIdtrInstructionIdentity::kLgdt: UtilVmWrite(VmcsField::kGuestGdtrBase, descriptor_table_reg->base); UtilVmWrite(VmcsField::kGuestGdtrLimit, descriptor_table_reg->limit); break; case GdtrOrIdtrInstructionIdentity::kLidt: UtilVmWrite(VmcsField::kGuestIdtrBase, descriptor_table_reg->base); UtilVmWrite(VmcsField::kGuestIdtrLimit, descriptor_table_reg->limit); break; } __writecr3(vmm_cr3); VmmpAdjustGuestInstructionPointer(guest_context->ip); } // LLDT, LTR, SLDT, and STR _Use_decl_annotations_ static void VmmpHandleLdtrOrTrAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const LdtrOrTrInstInformation exit_qualification = { static_cast<ULONG32>(UtilVmRead(VmcsField::kVmxInstructionInfo))}; // Calculate an address or a register to be used for the instruction const auto displacement = UtilVmRead(VmcsField::kExitQualification); ULONG_PTR operation_address = 0; if (exit_qualification.fields.register_access) { // Register const auto register_used = VmmpSelectRegister(exit_qualification.fields.register1, guest_context); operation_address = reinterpret_cast<ULONG_PTR>(register_used); } else { // Base ULONG_PTR base_value = 0; if (!exit_qualification.fields.base_register_invalid) { const auto register_used = VmmpSelectRegister( exit_qualification.fields.base_register, guest_context); base_value = *register_used; } // Index ULONG_PTR index_value = 0; if (!exit_qualification.fields.index_register_invalid) { const auto register_used = VmmpSelectRegister( exit_qualification.fields.index_register, guest_context); index_value = *register_used; switch (static_cast<Scaling>(exit_qualification.fields.scalling)) { case Scaling::kNoScaling: index_value = index_value; break; case Scaling::kScaleBy2: index_value = index_value * 2; break; case Scaling::kScaleBy4: index_value = index_value * 4; break; case Scaling::kScaleBy8: index_value = index_value * 8; break; default: break; } } operation_address = base_value + index_value + displacement; if (static_cast<AddressSize>(exit_qualification.fields.address_size) == AddressSize::k32bit) { operation_address &= MAXULONG; } } // Update CR3 with that of the guest since below code is going to access // memory. const auto guest_cr3 = UtilVmRead(VmcsField::kGuestCr3); const auto vmm_cr3 = __readcr3(); __writecr3(guest_cr3); // Emulate the instruction auto selector = reinterpret_cast<USHORT *>(operation_address); switch (static_cast<LdtrOrTrInstructionIdentity>( exit_qualification.fields.instruction_identity)) { case LdtrOrTrInstructionIdentity::kSldt: *selector = static_cast<USHORT>(UtilVmRead(VmcsField::kGuestLdtrSelector)); break; case LdtrOrTrInstructionIdentity::kStr: *selector = static_cast<USHORT>(UtilVmRead(VmcsField::kGuestTrSelector)); break; case LdtrOrTrInstructionIdentity::kLldt: UtilVmWrite(VmcsField::kGuestLdtrSelector, *selector); break; case LdtrOrTrInstructionIdentity::kLtr: UtilVmWrite(VmcsField::kGuestTrSelector, *selector); break; } __writecr3(vmm_cr3); VmmpAdjustGuestInstructionPointer(guest_context->ip); } // MOV to / from DRx _Use_decl_annotations_ static void VmmpHandleDrAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const MovDrQualification exit_qualification = { UtilVmRead(VmcsField::kExitQualification)}; const auto register_used = VmmpSelectRegister(exit_qualification.fields.gp_register, guest_context); // Emulate the instruction switch (static_cast<MovDrDirection>(exit_qualification.fields.direction)) { case MovDrDirection::kMoveToDr: // clang-format off switch (exit_qualification.fields.debugl_register) { case 0: __writedr(0, *register_used); break; case 1: __writedr(1, *register_used); break; case 2: __writedr(2, *register_used); break; case 3: __writedr(3, *register_used); break; case 4: __writedr(4, *register_used); break; case 5: __writedr(5, *register_used); break; case 6: __writedr(6, *register_used); break; case 7: __writedr(7, *register_used); break; default: break; } // clang-format on break; case MovDrDirection::kMoveFromDr: // clang-format off switch (exit_qualification.fields.debugl_register) { case 0: *register_used = __readdr(0); break; case 1: *register_used = __readdr(1); break; case 2: *register_used = __readdr(2); break; case 3: *register_used = __readdr(3); break; case 4: *register_used = __readdr(4); break; case 5: *register_used = __readdr(5); break; case 6: *register_used = __readdr(6); break; case 7: *register_used = __readdr(7); break; default: break; } // clang-format on break; default: HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); break; } VmmpAdjustGuestInstructionPointer(guest_context->ip); } // IN, INS, OUT, OUTS _Use_decl_annotations_ static void VmmpHandleIoPort( GuestContext *guest_context) { const IoInstQualification exit_qualification = { UtilVmRead(VmcsField::kExitQualification)}; const auto is_in = exit_qualification.fields.direction == 1; // to memory? const auto is_string = exit_qualification.fields.string_instruction == 1; const auto is_rep = exit_qualification.fields.rep_prefixed == 1; const auto port = static_cast<USHORT>(exit_qualification.fields.port_number); const auto string_address = reinterpret_cast<void *>( (is_in) ? guest_context->gp_regs->di : guest_context->gp_regs->si); const auto count = static_cast<unsigned long>((is_rep) ? guest_context->gp_regs->cx : 1); const auto address = (is_string) ? string_address : &guest_context->gp_regs->ax; SIZE_T size_of_access = 0; switch (static_cast<IoInstSizeOfAccess>( exit_qualification.fields.size_of_access)) { case IoInstSizeOfAccess::k1Byte: size_of_access = 1; break; case IoInstSizeOfAccess::k2Byte: size_of_access = 2; break; case IoInstSizeOfAccess::k4Byte: size_of_access = 4; break; } HYPERPLATFORM_LOG_DEBUG_SAFE("GuestIp= %p, Port= %04x, %s%s", guest_context->ip, port, (is_in ? "IN" : "OUT"), (is_string ? "S" : "")); VmmpIoWrapper(is_in, is_string, size_of_access, port, address, count); // FIXME; Guest's ECX should be changed on is_rep == 1 // FIXME: EDI and ESI need to be changed on is_string == 1 VmmpAdjustGuestInstructionPointer(guest_context->ip); } // Perform IO instruction according with parameters _Use_decl_annotations_ static void VmmpIoWrapper(bool to_memory, bool is_string, SIZE_T size_of_access, unsigned short port, void *address, unsigned long count) { NT_ASSERT(size_of_access == 1 || size_of_access == 2 || size_of_access == 4); // Update CR3 with that of the guest since below code is going to access // memory. const auto guest_cr3 = UtilVmRead(VmcsField::kGuestCr3); const auto vmm_cr3 = __readcr3(); __writecr3(guest_cr3); // clang-format off if (to_memory) { if (is_string) { // IN switch (size_of_access) { case 1: *reinterpret_cast<UCHAR*>(address) = __inbyte(port); break; case 2: *reinterpret_cast<USHORT*>(address) = __inword(port); break; case 4: *reinterpret_cast<ULONG*>(address) = __indword(port); break; } } else { // INS switch (size_of_access) { case 1: __inbytestring(port, reinterpret_cast<UCHAR*>(address), count); break; case 2: __inwordstring(port, reinterpret_cast<USHORT*>(address), count); break; case 4: __indwordstring(port, reinterpret_cast<ULONG*>(address), count); break; } } } else { if (is_string) { // OUT switch (size_of_access) { case 1: __outbyte(port, *reinterpret_cast<UCHAR*>(address)); break; case 2: __outword(port, *reinterpret_cast<USHORT*>(address)); break; case 4: __outdword(port, *reinterpret_cast<ULONG*>(address)); break; } } else { // OUTS switch (size_of_access) { case 1: __outbytestring(port, reinterpret_cast<UCHAR*>(address), count); break; case 2: __outwordstring(port, reinterpret_cast<USHORT*>(address), count); break; case 4: __outdwordstring(port, reinterpret_cast<ULONG*>(address), count); break; } } } // clang-format on __writecr3(vmm_cr3); } // MOV to / from CRx _Use_decl_annotations_ static void VmmpHandleCrAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const MovCrQualification exit_qualification = { UtilVmRead(VmcsField::kExitQualification)}; const auto register_used = VmmpSelectRegister(exit_qualification.fields.gp_register, guest_context); switch (static_cast<MovCrAccessType>(exit_qualification.fields.access_type)) { case MovCrAccessType::kMoveToCr: switch (exit_qualification.fields.control_register) { // CR0 <- Reg case 0: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); if (UtilIsX86Pae()) { UtilLoadPdptes(UtilVmRead(VmcsField::kGuestCr3)); } UtilVmWrite(VmcsField::kGuestCr0, *register_used); UtilVmWrite(VmcsField::kCr0ReadShadow, *register_used); break; } // CR3 <- Reg case 3: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); if (UtilIsX86Pae()) { UtilLoadPdptes(*register_used); } UtilVmWrite(VmcsField::kGuestCr3, *register_used); break; } // CR4 <- Reg case 4: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); if (UtilIsX86Pae()) { UtilLoadPdptes(UtilVmRead(VmcsField::kGuestCr3)); } UtilVmWrite(VmcsField::kGuestCr4, *register_used); UtilVmWrite(VmcsField::kCr4ReadShadow, *register_used); break; } // CR8 <- Reg case 8: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); guest_context->cr8 = *register_used; break; } default: HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); break; } break; case MovCrAccessType::kMoveFromCr: switch (exit_qualification.fields.control_register) { // Reg <- CR3 case 3: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); *register_used = UtilVmRead(VmcsField::kGuestCr3); break; } // Reg <- CR8 case 8: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); *register_used = guest_context->cr8; break; } default: HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); break; } break; // Unimplemented case MovCrAccessType::kClts: case MovCrAccessType::kLmsw: default: HYPERPLATFORM_COMMON_DBG_BREAK(); break; } VmmpAdjustGuestInstructionPointer(guest_context->ip); } // VMX instructions except for VMCALL _Use_decl_annotations_ static void VmmpHandleVmx(GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); // See "CONVENTIONS" guest_context->flag_reg.fields.cf = true; // Error without status guest_context->flag_reg.fields.pf = false; guest_context->flag_reg.fields.af = false; guest_context->flag_reg.fields.zf = false; // Error without status guest_context->flag_reg.fields.sf = false; guest_context->flag_reg.fields.of = false; UtilVmWrite(VmcsField::kGuestRflags, guest_context->flag_reg.all); VmmpAdjustGuestInstructionPointer(guest_context->ip); } // VMCALL _Use_decl_annotations_ static void VmmpHandleVmCall( GuestContext *guest_context) { // VMCALL for Sushi expects that cx holds a command number, and dx holds an // address of a context parameter optionally const auto hypercall_number = static_cast<HypercallNumber>(guest_context->gp_regs->cx); switch (hypercall_number) { case HypercallNumber::kTerminateVmm: // Unloading requested VmmpHandleVmCallTermination(guest_context); break; case HypercallNumber::kPingVmm: HYPERPLATFORM_LOG_INFO_SAFE("Pong by VMM! (context = %p)", guest_context->gp_regs->dx); VmmpIndicateSuccessfulVmcall(guest_context); break; default: // Unsupported hypercall. Handle like other VMX instructions VmmpHandleVmx(guest_context); } } // INVD _Use_decl_annotations_ static void VmmpHandleInvalidateInternalCaches( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); AsmInvalidateInternalCaches(); VmmpAdjustGuestInstructionPointer(guest_context->ip); } // INVLPG _Use_decl_annotations_ static void VmmpHandleInvalidateTLBEntry( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const auto invalidate_address = reinterpret_cast<void *>(UtilVmRead(VmcsField::kExitQualification)); __invlpg(invalidate_address); VmmpAdjustGuestInstructionPointer(guest_context->ip); } // EXIT_REASON_EPT_VIOLATION _Use_decl_annotations_ static void VmmpHandleEptViolation( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); auto processor_data = guest_context->stack->processor_data; EptHandleEptViolation(processor_data->ept_data); } // EXIT_REASON_EPT_MISCONFIG _Use_decl_annotations_ static void VmmpHandleEptMisconfig( GuestContext *guest_context) { UNREFERENCED_PARAMETER(guest_context); const auto fault_address = UtilVmRead(VmcsField::kGuestPhysicalAddress); const auto ept_pt_entry = EptGetEptPtEntry( guest_context->stack->processor_data->ept_data, fault_address); HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kEptMisconfigVmExit, fault_address, reinterpret_cast<ULONG_PTR>(ept_pt_entry), 0); } // Selects a register to be used based on the index _Use_decl_annotations_ static ULONG_PTR *VmmpSelectRegister( ULONG index, GuestContext *guest_context) { ULONG_PTR *register_used = nullptr; // clang-format off switch (index) { case 0: register_used = &guest_context->gp_regs->ax; break; case 1: register_used = &guest_context->gp_regs->cx; break; case 2: register_used = &guest_context->gp_regs->dx; break; case 3: register_used = &guest_context->gp_regs->bx; break; case 4: register_used = &guest_context->gp_regs->sp; break; case 5: register_used = &guest_context->gp_regs->bp; break; case 6: register_used = &guest_context->gp_regs->si; break; case 7: register_used = &guest_context->gp_regs->di; break; #if defined(_AMD64_) case 8: register_used = &guest_context->gp_regs->r8; break; case 9: register_used = &guest_context->gp_regs->r9; break; case 10: register_used = &guest_context->gp_regs->r10; break; case 11: register_used = &guest_context->gp_regs->r11; break; case 12: register_used = &guest_context->gp_regs->r12; break; case 13: register_used = &guest_context->gp_regs->r13; break; case 14: register_used = &guest_context->gp_regs->r14; break; case 15: register_used = &guest_context->gp_regs->r15; break; #endif default: HYPERPLATFORM_COMMON_DBG_BREAK(); break; } // clang-format on return register_used; } // Dumps guest's selectors /*_Use_decl_annotations_*/ static void VmmpDumpGuestSelectors() { HYPERPLATFORM_LOG_DEBUG_SAFE( "es %04x %p %08x %08x", UtilVmRead(VmcsField::kGuestEsSelector), UtilVmRead(VmcsField::kGuestEsBase), UtilVmRead(VmcsField::kGuestEsLimit), UtilVmRead(VmcsField::kGuestEsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE( "cs %04x %p %08x %08x", UtilVmRead(VmcsField::kGuestCsSelector), UtilVmRead(VmcsField::kGuestCsBase), UtilVmRead(VmcsField::kGuestCsLimit), UtilVmRead(VmcsField::kGuestCsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE( "ss %04x %p %08x %08x", UtilVmRead(VmcsField::kGuestSsSelector), UtilVmRead(VmcsField::kGuestSsBase), UtilVmRead(VmcsField::kGuestSsLimit), UtilVmRead(VmcsField::kGuestSsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE( "ds %04x %p %08x %08x", UtilVmRead(VmcsField::kGuestDsSelector), UtilVmRead(VmcsField::kGuestDsBase), UtilVmRead(VmcsField::kGuestDsLimit), UtilVmRead(VmcsField::kGuestDsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE( "fs %04x %p %08x %08x", UtilVmRead(VmcsField::kGuestFsSelector), UtilVmRead(VmcsField::kGuestFsBase), UtilVmRead(VmcsField::kGuestFsLimit), UtilVmRead(VmcsField::kGuestFsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE( "gs %04x %p %08x %08x", UtilVmRead(VmcsField::kGuestGsSelector), UtilVmRead(VmcsField::kGuestGsBase), UtilVmRead(VmcsField::kGuestGsLimit), UtilVmRead(VmcsField::kGuestGsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE("ld %04x %p %08x %08x", UtilVmRead(VmcsField::kGuestLdtrSelector), UtilVmRead(VmcsField::kGuestLdtrBase), UtilVmRead(VmcsField::kGuestLdtrLimit), UtilVmRead(VmcsField::kGuestLdtrArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE( "tr %04x %p %08x %08x", UtilVmRead(VmcsField::kGuestTrSelector), UtilVmRead(VmcsField::kGuestTrBase), UtilVmRead(VmcsField::kGuestTrLimit), UtilVmRead(VmcsField::kGuestTrArBytes)); } // Sets rip to the next instruction _Use_decl_annotations_ static void VmmpAdjustGuestInstructionPointer( ULONG_PTR guest_ip) { const auto exit_instruction_length = UtilVmRead(VmcsField::kVmExitInstructionLen); UtilVmWrite(VmcsField::kGuestRip, guest_ip + exit_instruction_length); } // Handle VMRESUME or VMXOFF failure. Fatal error. _Use_decl_annotations_ void __stdcall VmmVmxFailureHandler( AllRegisters *all_regs) { const auto vmx_error = (all_regs->flags.fields.zf) ? UtilVmRead(VmcsField::kVmInstructionError) : 0; HYPERPLATFORM_COMMON_BUG_CHECK( HyperPlatformBugCheck::kCriticalVmxInstructionFailure, vmx_error, 0, 0); } // Saves all supported user state components (x87, SSE, AVX states) _Use_decl_annotations_ static void VmmpSaveExtendedProcessorState( GuestContext *guest_context) { // Clear the TS flag temporality since XSAVE/XRSTOR raise #NM Cr0 cr0 = {__readcr0()}; const auto old_cr0 = cr0; cr0.fields.ts = false; __writecr0(cr0.all); _xsave(guest_context->stack->processor_data->xsave_area, guest_context->stack->processor_data->xsave_inst_mask); __writecr0(old_cr0.all); } // Restores all supported user state components (x87, SSE, AVX states) _Use_decl_annotations_ static void VmmpRestoreExtendedProcessorState( GuestContext *guest_context) { // Clear the TS flag temporality since XSAVE/XRSTOR raise #NM Cr0 cr0 = {__readcr0()}; const auto old_cr0 = cr0; cr0.fields.ts = false; __writecr0(cr0.all); _xrstor(guest_context->stack->processor_data->xsave_area, guest_context->stack->processor_data->xsave_inst_mask); __writecr0(old_cr0.all); } // Indicates successful VMCALL _Use_decl_annotations_ static void VmmpIndicateSuccessfulVmcall( GuestContext *guest_context) { // See "CONVENTIONS" guest_context->flag_reg.fields.cf = false; guest_context->flag_reg.fields.pf = false; guest_context->flag_reg.fields.af = false; guest_context->flag_reg.fields.zf = false; guest_context->flag_reg.fields.sf = false; guest_context->flag_reg.fields.of = false; guest_context->flag_reg.fields.cf = false; guest_context->flag_reg.fields.zf = false; UtilVmWrite(VmcsField::kGuestRflags, guest_context->flag_reg.all); VmmpAdjustGuestInstructionPointer(guest_context->ip); } // Handles an unloading request _Use_decl_annotations_ static void VmmpHandleVmCallTermination( GuestContext *guest_context) { const auto context = reinterpret_cast<void *>(guest_context->gp_regs->dx); // HYPERPLATFORM_COMMON_DBG_BREAK(); // The processor sets ffff to limits of IDT and GDT when VM-exit occurred. // It is not correct value but fine to ignore since vmresume loads correct // values from VMCS. But here, we are going to skip vmresume and simply // return to where VMCALL is executed. It results in keeping those broken // values and ends up with bug check 109, so we should fix them manually. const auto gdt_limit = UtilVmRead(VmcsField::kGuestGdtrLimit); const auto gdt_base = UtilVmRead(VmcsField::kGuestGdtrBase); const auto idt_limit = UtilVmRead(VmcsField::kGuestIdtrLimit); const auto idt_base = UtilVmRead(VmcsField::kGuestIdtrBase); Gdtr gdtr = {static_cast<USHORT>(gdt_limit), gdt_base}; Idtr idtr = {static_cast<USHORT>(idt_limit), idt_base}; __lgdt(&gdtr); __lidt(&idtr); // Store an address of the management structure to the context parameter const auto result_ptr = reinterpret_cast<ProcessorData **>(context); *result_ptr = guest_context->stack->processor_data; HYPERPLATFORM_LOG_DEBUG_SAFE("Context at %p %p", context, guest_context->stack->processor_data); // Set rip to the next instruction of VMCALL const auto exit_instruction_length = UtilVmRead(VmcsField::kVmExitInstructionLen); const auto return_address = guest_context->ip + exit_instruction_length; // Since rflags is overwritten after VMXOFF, we should manually indicates // that VMCALL was successful by clearing those flags. // See "CONVENTIONS" guest_context->flag_reg.fields.cf = false; guest_context->flag_reg.fields.pf = false; guest_context->flag_reg.fields.af = false; guest_context->flag_reg.fields.zf = false; guest_context->flag_reg.fields.sf = false; guest_context->flag_reg.fields.of = false; guest_context->flag_reg.fields.cf = false; guest_context->flag_reg.fields.zf = false; // Set registers used after VMXOFF to recover the context. Volatile // registers must be used because those changes are reflected to the // guest's context after VMXOFF. guest_context->gp_regs->cx = return_address; guest_context->gp_regs->dx = guest_context->gp_regs->sp; guest_context->gp_regs->ax = guest_context->flag_reg.all; guest_context->vm_continue = false; } } // extern "C"
[ "tanda.sat@gmail.com" ]
tanda.sat@gmail.com
a37b60dbc706ca304a302392b4d360cd980ac515
2e613efc5a3b330f440a2d90bb758dafbdf8f6b1
/src/rect.cpp
1e2e8cb79aa9c6fb72964a03eedb82f0bbdf6cb9
[]
no_license
zhaoweisonake/qfplot
4a76d446aebfddce4bf8a51c709a815f35ca76d2
e30d851261f3987a42319ff98def23771adb24bd
refs/heads/master
2021-01-18T12:31:07.049737
2010-05-17T09:29:11
2010-05-17T09:29:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
#include "rect.h" void Rect::expand( const QPoint& point ) { setLeft ( qMin(point.x(), left() ) ); setRight ( qMax(point.x(), right() ) ); setTop ( qMax(point.y(), top() ) ); setBottom( qMin(point.y(), bottom()) ); };
[ "akhokhlov@localhost" ]
akhokhlov@localhost
b87cfd7b7b085221fc14dd8833c09d3e95c6d70e
7a0faa9b4c654fc8ca9d7b432cc56ef0f4102339
/XBee/setup/bearing.cpp
a10f11438ef85f26df0159ba4c92a479fc7bc6ee
[]
no_license
linoor/MecatroMouve
e47db1981b39d9fcf444e9decc157d63553ddccc
a5398f11818fe4d1b691ed21abef7b59836fa7c9
refs/heads/dev
2020-05-18T05:09:09.852098
2015-12-26T13:40:56
2015-12-26T13:40:56
25,122,445
0
0
null
2015-05-28T14:56:42
2014-10-12T14:57:46
Arduino
UTF-8
C++
false
false
2,220
cpp
// #define PI 3.141592654 // this is not the real angle but a cache of the last result from computeBearing double bearingOrig; // each turn should be multiply by 360 int cameraTurns = 0; // compute the bearing angle of loc1 and loc2 // loc1: received gps = target // loc2: my gps = camera double computeBearing(int32_t loc1[], int32_t loc2[]) { double lat1 = (double)loc1[0] / 10000000.0; double lng1 = (double)loc1[1] / 10000000.0; double lat2 = (double)loc2[0] / 10000000.0; double lng2 = (double)loc2[1] / 10000000.0; // Serial.print("--");Serial.println(atan2((lng1-lng2), (lat1-lat2)) * 180 / PI); return atan2((lng1 - lng2), (lat1 - lat2)) * 180 / PI; // return atan((lng2-lng1)/cos(lng1*PI/180)/(lat2-lat1)) * 180 / PI; } double computeVertical(int32_t loc1[], int32_t loc2[], float alti1, float alti2) { double lat1 = (double)loc1[0] / 10000000.0; double lng1 = (double)loc1[1] / 10000000.0; double lat2 = (double)loc2[0] / 10000000.0; double lng2 = (double)loc2[1] / 10000000.0; double dist = sqrt(pow(lat2 - lat1, 2) + pow(lng2 - lng1, 2)); return atan((alti1 - alti2) / dist) * 180 / PI; } double realAngle(double bearingDelta) { if (bearingDelta < -180) { cameraTurns++; } else if (bearingDelta >= -180 && bearingDelta < 0) { } else if (bearingDelta >= 0 && bearingDelta < 180) { } else if (bearingDelta >= 180) { cameraTurns--; } else {} double bearingDeltaReal = bearingDelta + cameraTurns * 360; return bearingOrig + bearingDeltaReal; } double updateBearing(int32_t loc1[], int32_t loc2[]) { double bearing = computeBearing(loc1, loc2); // real bearing angle to move the motor double bearingReal; if (!isBearingInit) { bearingReal = bearingOrig = bearing; isBearingInit = true; // Serial.print("Bearing initialized"); } else { // Serial.print(bearing); Serial.print(" "); Serial.println(bearingOrig); double bearingDelta = bearing - bearingOrig; bearingReal = realAngle(bearingDelta); bearingOrig = bearing; Serial.println(bearingReal); } return bearingReal; }
[ "wf870125@gmail.com" ]
wf870125@gmail.com
25d3b41b7c27db0936b159ad00436d4881bc8625
4643c73ef1a3da091f61dc6a189fee897b015ca5
/include/nekit/utils/http_message_rewriter_interface.h
a1fc9239173a0728ce82191e29376a2207314091
[ "MIT" ]
permissive
edsburke/libnekit
604123b8a53a291c7d50b063fdebd3ec49266885
19e6767c522a20f678ab73f31aab7504c42013a6
refs/heads/master
2020-04-11T02:01:36.124112
2018-10-10T16:01:11
2018-10-10T16:01:11
161,433,129
1
0
MIT
2018-12-12T04:33:12
2018-12-12T04:33:12
null
UTF-8
C++
false
false
1,369
h
// MIT License // Copyright (c) 2018 Zhuhao Wang // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include "buffer.h" #include "result.h" namespace nekit { namespace utils { class HttpMessageRewriterInterface { public: virtual utils::Result<void> RewriteBuffer(Buffer* buffer) = 0; }; } // namespace utils } // namespace nekit
[ "zhuhaow@gmail.com" ]
zhuhaow@gmail.com
e0e5ece1d094cd8f0c83e4c59a73ee695dffcc01
842f2372a8f62f10e7b5f6a96a25899a08d29acd
/servers/visual/visual_server_raster.cpp
6b74b34ba17c5a62ad7f2093df01b13132de1538
[ "MIT" ]
permissive
DonkeyWs/godot
1abf7ae3c4bcd23937450be548d71dc463edb967
fa58fcb51ab784811b158658221b62ccc40f5738
refs/heads/master
2021-01-18T12:14:57.507900
2014-05-28T12:43:39
2014-05-28T12:43:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
154,136
cpp
/*************************************************************************/ /* visual_server_raster.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "visual_server_raster.h" #include "os/os.h" #include "globals.h" #include "default_mouse_cursor.xpm" #include "sort.h" // careful, these may run in different threads than the visual server BalloonAllocator<> *VisualServerRaster::OctreeAllocator::allocator=NULL; #define VS_CHANGED\ changes++;\ // print_line(__FUNCTION__); RID VisualServerRaster::texture_create() { return rasterizer->texture_create(); } void VisualServerRaster::texture_allocate(RID p_texture, int p_width, int p_height,Image::Format p_format,uint32_t p_flags) { rasterizer->texture_allocate(p_texture,p_width,p_height,p_format,p_flags); } void VisualServerRaster::texture_set_flags(RID p_texture,uint32_t p_flags) { VS_CHANGED; rasterizer->texture_set_flags(p_texture,p_flags); } void VisualServerRaster::texture_set_data(RID p_texture,const Image& p_image,CubeMapSide p_cube_side) { VS_CHANGED; rasterizer->texture_set_data(p_texture,p_image,p_cube_side); } Image VisualServerRaster::texture_get_data(RID p_texture,CubeMapSide p_cube_side) const { return rasterizer->texture_get_data(p_texture,p_cube_side); } uint32_t VisualServerRaster::texture_get_flags(RID p_texture) const { return rasterizer->texture_get_flags(p_texture); } Image::Format VisualServerRaster::texture_get_format(RID p_texture) const { return rasterizer->texture_get_format(p_texture); } uint32_t VisualServerRaster::texture_get_width(RID p_texture) const { return rasterizer->texture_get_width(p_texture); } uint32_t VisualServerRaster::texture_get_height(RID p_texture) const { return rasterizer->texture_get_height(p_texture); } void VisualServerRaster::texture_set_size_override(RID p_texture,int p_width, int p_height) { rasterizer->texture_set_size_override(p_texture,p_width,p_height); } bool VisualServerRaster::texture_can_stream(RID p_texture) const { return false; } void VisualServerRaster::texture_set_reload_hook(RID p_texture,ObjectID p_owner,const StringName& p_function) const { rasterizer->texture_set_reload_hook(p_texture,p_owner,p_function); } /* SHADER API */ RID VisualServerRaster::shader_create(ShaderMode p_mode) { return rasterizer->shader_create(p_mode); } void VisualServerRaster::shader_set_mode(RID p_shader,ShaderMode p_mode){ VS_CHANGED; rasterizer->shader_set_mode(p_shader,p_mode); } VisualServer::ShaderMode VisualServerRaster::shader_get_mode(RID p_shader) const{ return rasterizer->shader_get_mode(p_shader); } void VisualServerRaster::shader_set_code(RID p_shader, const String& p_vertex, const String& p_fragment,int p_vertex_ofs,int p_fragment_ofs) { VS_CHANGED; rasterizer->shader_set_code(p_shader,p_vertex,p_fragment,p_vertex_ofs,p_fragment_ofs); } String VisualServerRaster::shader_get_vertex_code(RID p_shader) const{ return rasterizer->shader_get_vertex_code(p_shader); } String VisualServerRaster::shader_get_fragment_code(RID p_shader) const{ return rasterizer->shader_get_fragment_code(p_shader); } void VisualServerRaster::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const { return rasterizer->shader_get_param_list(p_shader,p_param_list); } /* Material */ RID VisualServerRaster::material_create() { return rasterizer->material_create(); } void VisualServerRaster::material_set_shader(RID p_material, RID p_shader) { VS_CHANGED; rasterizer->material_set_shader(p_material, p_shader ); } RID VisualServerRaster::material_get_shader(RID p_material) const { return rasterizer->material_get_shader(p_material); } void VisualServerRaster::material_set_param(RID p_material, const StringName& p_param, const Variant& p_value) { VS_CHANGED; rasterizer->material_set_param(p_material, p_param,p_value ); } Variant VisualServerRaster::material_get_param(RID p_material, const StringName& p_param) const { return rasterizer->material_get_param(p_material,p_param); } void VisualServerRaster::material_set_flag(RID p_material, MaterialFlag p_flag,bool p_enabled) { VS_CHANGED; rasterizer->material_set_flag(p_material,p_flag,p_enabled); } void VisualServerRaster::material_set_hint(RID p_material, MaterialHint p_hint,bool p_enabled) { VS_CHANGED; rasterizer->material_set_hint(p_material,p_hint,p_enabled); } bool VisualServerRaster::material_get_hint(RID p_material,MaterialHint p_hint) const { return rasterizer->material_get_hint(p_material,p_hint); } void VisualServerRaster::material_set_shade_model(RID p_material, MaterialShadeModel p_model) { VS_CHANGED; rasterizer->material_set_shade_model(p_material,p_model); } VisualServer::MaterialShadeModel VisualServerRaster::material_get_shade_model(RID p_material) const { return rasterizer->material_get_shade_model(p_material); } bool VisualServerRaster::material_get_flag(RID p_material,MaterialFlag p_flag) const { return rasterizer->material_get_flag(p_material,p_flag); } void VisualServerRaster::material_set_blend_mode(RID p_material,MaterialBlendMode p_mode) { VS_CHANGED; rasterizer->material_set_blend_mode(p_material,p_mode); } VS::MaterialBlendMode VisualServerRaster::material_get_blend_mode(RID p_material) const { return rasterizer->material_get_blend_mode(p_material); } void VisualServerRaster::material_set_line_width(RID p_material,float p_line_width) { VS_CHANGED; rasterizer->material_set_line_width(p_material,p_line_width); } float VisualServerRaster::material_get_line_width(RID p_material) const { return rasterizer->material_get_line_width(p_material); } /* FIXED MATERIAL */ RID VisualServerRaster::fixed_material_create() { return rasterizer->fixed_material_create(); } void VisualServerRaster::fixed_material_set_flag(RID p_material, FixedMaterialFlags p_flag, bool p_enabled) { rasterizer->fixed_material_set_flag(p_material,p_flag,p_enabled); } bool VisualServerRaster::fixed_material_get_flag(RID p_material, FixedMaterialFlags p_flag) const { return rasterizer->fixed_material_get_flag(p_material,p_flag); } void VisualServerRaster::fixed_material_set_param(RID p_material, FixedMaterialParam p_parameter, const Variant& p_value) { VS_CHANGED; rasterizer->fixed_material_set_parameter(p_material,p_parameter,p_value); } Variant VisualServerRaster::fixed_material_get_param(RID p_material,FixedMaterialParam p_parameter) const { return rasterizer->fixed_material_get_parameter(p_material,p_parameter); } void VisualServerRaster::fixed_material_set_texture(RID p_material,FixedMaterialParam p_parameter, RID p_texture) { VS_CHANGED; rasterizer->fixed_material_set_texture(p_material,p_parameter,p_texture); } RID VisualServerRaster::fixed_material_get_texture(RID p_material,FixedMaterialParam p_parameter) const { return rasterizer->fixed_material_get_texture(p_material,p_parameter); } void VisualServerRaster::fixed_material_set_detail_blend_mode(RID p_material,MaterialBlendMode p_mode) { VS_CHANGED; rasterizer->fixed_material_set_detail_blend_mode(p_material,p_mode); } VS::MaterialBlendMode VisualServerRaster::fixed_material_get_detail_blend_mode(RID p_material) const { return rasterizer->fixed_material_get_detail_blend_mode(p_material); } void VisualServerRaster::fixed_material_set_texcoord_mode(RID p_material,FixedMaterialParam p_parameter, FixedMaterialTexCoordMode p_mode) { VS_CHANGED; rasterizer->fixed_material_set_texcoord_mode(p_material,p_parameter,p_mode); } VS::FixedMaterialTexCoordMode VisualServerRaster::fixed_material_get_texcoord_mode(RID p_material,FixedMaterialParam p_parameter) const { return rasterizer->fixed_material_get_texcoord_mode(p_material,p_parameter); } void VisualServerRaster::fixed_material_set_point_size(RID p_material,float p_size) { VS_CHANGED rasterizer->fixed_material_set_point_size(p_material,p_size); } float VisualServerRaster::fixed_material_get_point_size(RID p_material) const{ return rasterizer->fixed_material_get_point_size(p_material); } void VisualServerRaster::fixed_material_set_uv_transform(RID p_material,const Transform& p_transform) { VS_CHANGED; rasterizer->fixed_material_set_uv_transform(p_material,p_transform); } Transform VisualServerRaster::fixed_material_get_uv_transform(RID p_material) const { return rasterizer->fixed_material_get_uv_transform(p_material); } /* MESH API */ RID VisualServerRaster::mesh_create() { return rasterizer->mesh_create(); } void VisualServerRaster::mesh_set_morph_target_count(RID p_mesh,int p_amount) { rasterizer->mesh_set_morph_target_count(p_mesh,p_amount); int amount = rasterizer->mesh_get_morph_target_count(p_mesh); Map< RID, Set<RID> >::Element * E = instance_dependency_map.find( p_mesh ); if (!E) return; Set<RID>::Element *I = E->get().front(); while(I) { Instance *ins = instance_owner.get( I->get() ); ins->data.morph_values.resize(amount); I = I->next(); } } int VisualServerRaster::mesh_get_morph_target_count(RID p_mesh) const { return rasterizer->mesh_get_morph_target_count(p_mesh); } void VisualServerRaster::mesh_set_morph_target_mode(RID p_mesh,MorphTargetMode p_mode) { rasterizer->mesh_set_morph_target_mode(p_mesh,p_mode); } VisualServer::MorphTargetMode VisualServerRaster::mesh_get_morph_target_mode(RID p_mesh) const{ return rasterizer->mesh_get_morph_target_mode(p_mesh); } void VisualServerRaster::mesh_add_custom_surface(RID p_mesh,const Variant& p_dat) { } void VisualServerRaster::mesh_add_surface(RID p_mesh,PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes,bool p_alpha_sort) { VS_CHANGED; _dependency_queue_update(p_mesh,true); rasterizer->mesh_add_surface(p_mesh,p_primitive,p_arrays,p_blend_shapes,p_alpha_sort); } Array VisualServerRaster::mesh_get_surface_arrays(RID p_mesh,int p_surface) const { return rasterizer->mesh_get_surface_arrays(p_mesh,p_surface); } Array VisualServerRaster::mesh_get_surface_morph_arrays(RID p_mesh,int p_surface) const { return rasterizer->mesh_get_surface_morph_arrays(p_mesh,p_surface); } void VisualServerRaster::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material,bool p_owned){ VS_CHANGED; rasterizer->mesh_surface_set_material(p_mesh,p_surface,p_material,p_owned); } RID VisualServerRaster::mesh_surface_get_material(RID p_mesh,int p_surface) const { return rasterizer->mesh_surface_get_material(p_mesh,p_surface); } int VisualServerRaster::mesh_surface_get_array_len(RID p_mesh, int p_surface) const{ return rasterizer->mesh_surface_get_array_len(p_mesh,p_surface); } int VisualServerRaster::mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const{ return rasterizer->mesh_surface_get_array_index_len(p_mesh,p_surface); } uint32_t VisualServerRaster::mesh_surface_get_format(RID p_mesh, int p_surface) const{ return rasterizer->mesh_surface_get_format(p_mesh,p_surface); } VisualServer::PrimitiveType VisualServerRaster::mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const{ return rasterizer->mesh_surface_get_primitive_type(p_mesh,p_surface); } void VisualServerRaster::mesh_remove_surface(RID p_mesh,int p_surface){ rasterizer->mesh_remove_surface(p_mesh,p_surface); } int VisualServerRaster::mesh_get_surface_count(RID p_mesh) const{ return rasterizer->mesh_get_surface_count(p_mesh); } void VisualServerRaster::mesh_set_custom_aabb(RID p_mesh,const AABB& p_aabb) { VS_CHANGED; _dependency_queue_update(p_mesh,true); rasterizer->mesh_set_custom_aabb(p_mesh,p_aabb); } AABB VisualServerRaster::mesh_get_custom_aabb(RID p_mesh) const { return rasterizer->mesh_get_custom_aabb(p_mesh); } /* MULTIMESH */ RID VisualServerRaster::multimesh_create() { return rasterizer->multimesh_create(); } void VisualServerRaster::multimesh_set_instance_count(RID p_multimesh,int p_count) { VS_CHANGED; rasterizer->multimesh_set_instance_count(p_multimesh,p_count); } int VisualServerRaster::multimesh_get_instance_count(RID p_multimesh) const { return rasterizer->multimesh_get_instance_count(p_multimesh); } void VisualServerRaster::multimesh_set_mesh(RID p_multimesh,RID p_mesh) { VS_CHANGED; rasterizer->multimesh_set_mesh(p_multimesh,p_mesh); } void VisualServerRaster::multimesh_set_aabb(RID p_multimesh,const AABB& p_aabb) { VS_CHANGED; rasterizer->multimesh_set_aabb(p_multimesh,p_aabb); _dependency_queue_update(p_multimesh,true); } void VisualServerRaster::multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform) { VS_CHANGED; rasterizer->multimesh_instance_set_transform(p_multimesh,p_index,p_transform); } void VisualServerRaster::multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color) { VS_CHANGED; rasterizer->multimesh_instance_set_color(p_multimesh,p_index,p_color); } RID VisualServerRaster::multimesh_get_mesh(RID p_multimesh) const { return rasterizer->multimesh_get_mesh(p_multimesh); } AABB VisualServerRaster::multimesh_get_aabb(RID p_multimesh,const AABB& p_aabb) const { return rasterizer->multimesh_get_aabb(p_multimesh); } Transform VisualServerRaster::multimesh_instance_get_transform(RID p_multimesh,int p_index) const { return rasterizer->multimesh_instance_get_transform(p_multimesh,p_index); } Color VisualServerRaster::multimesh_instance_get_color(RID p_multimesh,int p_index) const { return rasterizer->multimesh_instance_get_color(p_multimesh,p_index); } void VisualServerRaster::multimesh_set_visible_instances(RID p_multimesh,int p_visible) { rasterizer->multimesh_set_visible_instances(p_multimesh,p_visible); } int VisualServerRaster::multimesh_get_visible_instances(RID p_multimesh) const { return rasterizer->multimesh_get_visible_instances(p_multimesh); } /* PARTICLES API */ RID VisualServerRaster::particles_create() { return rasterizer->particles_create(); } void VisualServerRaster::particles_set_amount(RID p_particles, int p_amount) { VS_CHANGED; rasterizer->particles_set_amount(p_particles,p_amount); } int VisualServerRaster::particles_get_amount(RID p_particles) const { return rasterizer->particles_get_amount(p_particles); } void VisualServerRaster::particles_set_emitting(RID p_particles, bool p_emitting) { VS_CHANGED; rasterizer->particles_set_emitting(p_particles,p_emitting); } bool VisualServerRaster::particles_is_emitting(RID p_particles) const { return rasterizer->particles_is_emitting(p_particles); } void VisualServerRaster::particles_set_visibility_aabb(RID p_particles, const AABB& p_visibility) { VS_CHANGED; rasterizer->particles_set_visibility_aabb(p_particles, p_visibility); } AABB VisualServerRaster::particles_get_visibility_aabb(RID p_particles) const { return rasterizer->particles_get_visibility_aabb(p_particles); } void VisualServerRaster::particles_set_emission_half_extents(RID p_particles, const Vector3& p_half_extents) { VS_CHANGED; rasterizer->particles_set_emission_half_extents(p_particles,p_half_extents); } Vector3 VisualServerRaster::particles_get_emission_half_extents(RID p_particles) const { return rasterizer->particles_get_emission_half_extents(p_particles); } void VisualServerRaster::particles_set_emission_base_velocity(RID p_particles, const Vector3& p_base_velocity) { VS_CHANGED; rasterizer->particles_set_emission_base_velocity(p_particles,p_base_velocity); } Vector3 VisualServerRaster::particles_get_emission_base_velocity(RID p_particles) const { return rasterizer->particles_get_emission_base_velocity(p_particles); } void VisualServerRaster::particles_set_emission_points(RID p_particles, const DVector<Vector3>& p_points) { VS_CHANGED; rasterizer->particles_set_emission_points(p_particles,p_points); } DVector<Vector3> VisualServerRaster::particles_get_emission_points(RID p_particles) const { return rasterizer->particles_get_emission_points(p_particles); } void VisualServerRaster::particles_set_gravity_normal(RID p_particles, const Vector3& p_normal) { VS_CHANGED; rasterizer->particles_set_gravity_normal(p_particles,p_normal); } Vector3 VisualServerRaster::particles_get_gravity_normal(RID p_particles) const { return rasterizer->particles_get_gravity_normal(p_particles); } void VisualServerRaster::particles_set_variable(RID p_particles, ParticleVariable p_variable,float p_value) { VS_CHANGED; rasterizer->particles_set_variable(p_particles,p_variable,p_value); } float VisualServerRaster::particles_get_variable(RID p_particles, ParticleVariable p_variable) const { return rasterizer->particles_get_variable(p_particles,p_variable); } void VisualServerRaster::particles_set_randomness(RID p_particles, ParticleVariable p_variable,float p_randomness) { VS_CHANGED; rasterizer->particles_set_randomness(p_particles,p_variable,p_randomness); } float VisualServerRaster::particles_get_randomness(RID p_particles, ParticleVariable p_variable) const { return rasterizer->particles_get_randomness(p_particles,p_variable); } void VisualServerRaster::particles_set_color_phases(RID p_particles, int p_phases) { VS_CHANGED; rasterizer->particles_set_color_phases(p_particles,p_phases); } int VisualServerRaster::particles_get_color_phases(RID p_particles) const { return rasterizer->particles_get_color_phases(p_particles); } void VisualServerRaster::particles_set_color_phase_pos(RID p_particles, int p_phase, float p_pos) { VS_CHANGED; rasterizer->particles_set_color_phase_pos(p_particles,p_phase,p_pos); } float VisualServerRaster::particles_get_color_phase_pos(RID p_particles, int p_phase) const { return rasterizer->particles_get_color_phase_pos(p_particles,p_phase); } void VisualServerRaster::particles_set_attractors(RID p_particles, int p_attractors) { VS_CHANGED; rasterizer->particles_set_attractors(p_particles,p_attractors); } int VisualServerRaster::particles_get_attractors(RID p_particles) const { return rasterizer->particles_get_attractors(p_particles); } void VisualServerRaster::particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3& p_pos) { VS_CHANGED; rasterizer->particles_set_attractor_pos(p_particles,p_attractor,p_pos); } Vector3 VisualServerRaster::particles_get_attractor_pos(RID p_particles,int p_attractor) const { return rasterizer->particles_get_attractor_pos(p_particles,p_attractor); } void VisualServerRaster::particles_set_attractor_strength(RID p_particles, int p_attractor, float p_force) { VS_CHANGED; rasterizer->particles_set_attractor_strength(p_particles,p_attractor,p_force); } float VisualServerRaster::particles_get_attractor_strength(RID p_particles,int p_attractor) const { return rasterizer->particles_get_attractor_strength(p_particles,p_attractor); } void VisualServerRaster::particles_set_color_phase_color(RID p_particles, int p_phase, const Color& p_color) { VS_CHANGED; rasterizer->particles_set_color_phase_color(p_particles,p_phase,p_color); } Color VisualServerRaster::particles_get_color_phase_color(RID p_particles, int p_phase) const { return rasterizer->particles_get_color_phase_color(p_particles,p_phase); } void VisualServerRaster::particles_set_material(RID p_particles, RID p_material,bool p_owned) { VS_CHANGED; rasterizer->particles_set_material(p_particles,p_material,p_owned); } RID VisualServerRaster::particles_get_material(RID p_particles) const { return rasterizer->particles_get_material(p_particles); } void VisualServerRaster::particles_set_height_from_velocity(RID p_particles, bool p_enable) { VS_CHANGED; rasterizer->particles_set_height_from_velocity(p_particles,p_enable); } bool VisualServerRaster::particles_has_height_from_velocity(RID p_particles) const { return rasterizer->particles_has_height_from_velocity(p_particles); } void VisualServerRaster::particles_set_use_local_coordinates(RID p_particles, bool p_enable) { rasterizer->particles_set_use_local_coordinates(p_particles,p_enable); } bool VisualServerRaster::particles_is_using_local_coordinates(RID p_particles) const { return rasterizer->particles_is_using_local_coordinates(p_particles); } /* Light API */ RID VisualServerRaster::light_create(LightType p_type) { return rasterizer->light_create(p_type); } VisualServer::LightType VisualServerRaster::light_get_type(RID p_light) const { return rasterizer->light_get_type(p_light); } void VisualServerRaster::light_set_color(RID p_light,LightColor p_type, const Color& p_color) { VS_CHANGED; rasterizer->light_set_color(p_light,p_type,p_color); } Color VisualServerRaster::light_get_color(RID p_light,LightColor p_type) const { return rasterizer->light_get_color(p_light,p_type); } void VisualServerRaster::light_set_shadow(RID p_light,bool p_enabled) { VS_CHANGED; rasterizer->light_set_shadow(p_light,p_enabled); } bool VisualServerRaster::light_has_shadow(RID p_light) const { return rasterizer->light_has_shadow(p_light); } void VisualServerRaster::light_set_volumetric(RID p_light,bool p_enabled) { VS_CHANGED; rasterizer->light_set_volumetric(p_light,p_enabled); } bool VisualServerRaster::light_is_volumetric(RID p_light) const { return rasterizer->light_is_volumetric(p_light); } void VisualServerRaster::light_set_projector(RID p_light,RID p_texture) { VS_CHANGED; rasterizer->light_set_projector(p_light,p_texture); } RID VisualServerRaster::light_get_projector(RID p_light) const { return rasterizer->light_get_projector(p_light); } void VisualServerRaster::light_set_param(RID p_light, LightParam p_var, float p_value) { VS_CHANGED; rasterizer->light_set_var(p_light,p_var,p_value); _dependency_queue_update(p_light,true); } float VisualServerRaster::light_get_param(RID p_light, LightParam p_var) const { return rasterizer->light_get_var(p_light,p_var); } void VisualServerRaster::light_set_operator(RID p_light,LightOp p_op) { VS_CHANGED; rasterizer->light_set_operator(p_light,p_op); } VisualServerRaster::LightOp VisualServerRaster::light_get_operator(RID p_light) const { return rasterizer->light_get_operator(p_light); } void VisualServerRaster::light_omni_set_shadow_mode(RID p_light,LightOmniShadowMode p_mode) { VS_CHANGED; rasterizer->light_omni_set_shadow_mode(p_light,p_mode); } VisualServerRaster::LightOmniShadowMode VisualServerRaster::light_omni_get_shadow_mode(RID p_light) const { return rasterizer->light_omni_get_shadow_mode(p_light); } void VisualServerRaster::light_directional_set_shadow_mode(RID p_light,LightDirectionalShadowMode p_mode){ VS_CHANGED; rasterizer->light_directional_set_shadow_mode(p_light,p_mode); } VS::LightDirectionalShadowMode VisualServerRaster::light_directional_get_shadow_mode(RID p_light) const{ return rasterizer->light_directional_get_shadow_mode(p_light); } void VisualServerRaster::light_directional_set_shadow_param(RID p_light,LightDirectionalShadowParam p_param, float p_value) { VS_CHANGED; rasterizer->light_directional_set_shadow_param(p_light,p_param,p_value); } float VisualServerRaster::light_directional_get_shadow_param(RID p_light,LightDirectionalShadowParam p_param) const { return rasterizer->light_directional_get_shadow_param(p_light,p_param); } RID VisualServerRaster::skeleton_create() { return rasterizer->skeleton_create(); } void VisualServerRaster::skeleton_resize(RID p_skeleton,int p_bones) { VS_CHANGED; rasterizer->skeleton_resize(p_skeleton,p_bones); } int VisualServerRaster::skeleton_get_bone_count(RID p_skeleton) const { return rasterizer->skeleton_get_bone_count(p_skeleton); } void VisualServerRaster::skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform) { VS_CHANGED; return rasterizer->skeleton_bone_set_transform(p_skeleton,p_bone,p_transform); } Transform VisualServerRaster::skeleton_bone_get_transform(RID p_skeleton,int p_bone) { return rasterizer->skeleton_bone_get_transform(p_skeleton,p_bone); } /* VISIBILITY API */ /* ROOM API */ RID VisualServerRaster::room_create() { Room *room = memnew( Room ); ERR_FAIL_COND_V(!room,RID()); return room_owner.make_rid( room ); } void VisualServerRaster::room_set_bounds(RID p_room, const BSP_Tree& p_bounds) { VS_CHANGED; Room *room = room_owner.get(p_room); ERR_FAIL_COND(!room); room->bounds=p_bounds; } BSP_Tree VisualServerRaster::room_get_bounds(RID p_room) const { Room *room = room_owner.get(p_room); ERR_FAIL_COND_V(!room, BSP_Tree()); return room->bounds; } /* PORTAL API */ RID VisualServerRaster::portal_create() { VS_CHANGED; Portal *portal = memnew( Portal ); ERR_FAIL_COND_V(!portal,RID()); return portal_owner.make_rid( portal ); } void VisualServerRaster::portal_set_shape(RID p_portal, const Vector<Point2>& p_shape) { VS_CHANGED; Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND(!portal); portal->shape=p_shape; portal->bounds=Rect2(); for(int i=0;i<p_shape.size();i++) { if (i==0) portal->bounds.pos=p_shape[i]; else portal->bounds.expand_to(p_shape[i]); } _dependency_queue_update(p_portal,true); } Vector<Point2> VisualServerRaster::portal_get_shape(RID p_portal) const { Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND_V(!portal, Vector<Point2>()); return portal->shape; } void VisualServerRaster::portal_set_enabled(RID p_portal, bool p_enabled) { VS_CHANGED; Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND(!portal); portal->enabled=p_enabled; } bool VisualServerRaster::portal_is_enabled(RID p_portal) const { Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND_V(!portal, false); return portal->enabled; } void VisualServerRaster::portal_set_disable_distance(RID p_portal, float p_distance) { VS_CHANGED; Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND(!portal); portal->disable_distance=p_distance; } float VisualServerRaster::portal_get_disable_distance(RID p_portal) const { Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND_V(!portal, -1); return portal->disable_distance; } void VisualServerRaster::portal_set_disabled_color(RID p_portal, const Color& p_color) { VS_CHANGED; Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND(!portal); portal->disable_color=p_color; } Color VisualServerRaster::portal_get_disabled_color(RID p_portal) const { Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND_V(!portal, Color()); return portal->disable_color; } void VisualServerRaster::portal_set_connect_range(RID p_portal, float p_range) { VS_CHANGED; Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND(!portal); portal->connect_range=p_range; _dependency_queue_update(p_portal,true); } float VisualServerRaster::portal_get_connect_range(RID p_portal) const { Portal *portal = portal_owner.get(p_portal); ERR_FAIL_COND_V(!portal,0); return portal->connect_range; } /* CAMERA API */ RID VisualServerRaster::camera_create() { Camera * camera = memnew( Camera ); return camera_owner.make_rid( camera ); } void VisualServerRaster::camera_set_perspective(RID p_camera,float p_fovy_degrees, float p_z_near, float p_z_far) { VS_CHANGED; Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->type=Camera::PERSPECTIVE; camera->fov=p_fovy_degrees; camera->znear=p_z_near; camera->zfar=p_z_far; } void VisualServerRaster::camera_set_orthogonal(RID p_camera,float p_size, float p_z_near, float p_z_far) { VS_CHANGED; Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->type=Camera::ORTHOGONAL; camera->size=p_size; camera->znear=p_z_near; camera->zfar=p_z_far; } void VisualServerRaster::camera_set_transform(RID p_camera,const Transform& p_transform) { VS_CHANGED; Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->transform=p_transform; } void VisualServerRaster::camera_set_visible_layers(RID p_camera,uint32_t p_layers) { VS_CHANGED; Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->visible_layers=p_layers; } uint32_t VisualServerRaster::camera_get_visible_layers(RID p_camera) const{ const Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND_V(!camera,0); return camera->visible_layers; } void VisualServerRaster::camera_set_environment(RID p_camera,RID p_env) { Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->env=p_env; } RID VisualServerRaster::camera_get_environment(RID p_camera) const { const Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND_V(!camera,RID()); return camera->env; } void VisualServerRaster::camera_set_use_vertical_aspect(RID p_camera,bool p_enable) { Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->vaspect=p_enable; } bool VisualServerRaster::camera_is_using_vertical_aspect(RID p_camera,bool p_enable) const{ const Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND_V(!camera,false); return camera->vaspect; } /* VIEWPORT API */ RID VisualServerRaster::viewport_create() { Viewport *viewport = memnew( Viewport ); RID rid = viewport_owner.make_rid( viewport ); ERR_FAIL_COND_V( !rid.is_valid(), rid ); viewport->self=rid; viewport->hide_scenario=false; viewport->hide_canvas=false; viewport->viewport_data=rasterizer->viewport_data_create(); return rid; } void VisualServerRaster::viewport_attach_to_screen(RID p_viewport,int p_screen) { VS_CHANGED; Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); screen_viewports[p_viewport]=p_screen; } void VisualServerRaster::viewport_detach(RID p_viewport) { VS_CHANGED; Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); ERR_FAIL_COND(!screen_viewports.has(p_viewport)); screen_viewports.erase(p_viewport); } void VisualServerRaster::viewport_set_as_render_target(RID p_viewport,bool p_enable) { VS_CHANGED; Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); if (viewport->render_target.is_valid()==p_enable) return; if (!p_enable) { rasterizer->free(viewport->render_target); viewport->render_target=RID(); viewport->render_target_texture=RID(); if (viewport->update_list.in_list()) viewport_update_list.remove(&viewport->update_list); } else { viewport->render_target=rasterizer->render_target_create(); rasterizer->render_target_set_size(viewport->render_target,viewport->rect.width,viewport->rect.height); viewport->render_target_texture=rasterizer->render_target_get_texture(viewport->render_target); if (viewport->render_target_update_mode!=RENDER_TARGET_UPDATE_DISABLED) viewport_update_list.add(&viewport->update_list); } } void VisualServerRaster::viewport_set_render_target_update_mode(RID p_viewport,RenderTargetUpdateMode p_mode){ VS_CHANGED; Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); if (viewport->render_target.is_valid() && viewport->update_list.in_list()) viewport_update_list.remove(&viewport->update_list); viewport->render_target_update_mode=p_mode; if (viewport->render_target.is_valid() &&viewport->render_target_update_mode!=RENDER_TARGET_UPDATE_DISABLED) viewport_update_list.add(&viewport->update_list); } VisualServer::RenderTargetUpdateMode VisualServerRaster::viewport_get_render_target_update_mode(RID p_viewport) const{ const Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport,RENDER_TARGET_UPDATE_DISABLED); return viewport->render_target_update_mode; } RID VisualServerRaster::viewport_get_render_target_texture(RID p_viewport) const{ Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport,RID()); return viewport->render_target_texture; } void VisualServerRaster::viewport_set_render_target_vflip(RID p_viewport,bool p_enable) { Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); viewport->render_target_vflip=p_enable; } void VisualServerRaster::viewport_set_render_target_to_screen_rect(RID p_viewport,const Rect2& p_rect) { Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); viewport->rt_to_screen_rect=p_rect; } bool VisualServerRaster::viewport_get_render_target_vflip(RID p_viewport) const{ const Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport,false); return viewport->render_target_vflip; } void VisualServerRaster::viewport_queue_screen_capture(RID p_viewport) { VS_CHANGED; Viewport *viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); viewport->queue_capture=true; } Image VisualServerRaster::viewport_get_screen_capture(RID p_viewport) const { Viewport *viewport = (Viewport*)viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport,Image()); Image ret = viewport->capture; viewport->capture=Image(); return ret; } void VisualServerRaster::viewport_set_rect(RID p_viewport,const ViewportRect& p_rect) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); viewport->rect=p_rect; if (viewport->render_target.is_valid()) { rasterizer->render_target_set_size(viewport->render_target,viewport->rect.width,viewport->rect.height); } } VisualServer::ViewportRect VisualServerRaster::viewport_get_rect(RID p_viewport) const { const Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport, ViewportRect()); return viewport->rect; } void VisualServerRaster::viewport_set_hide_scenario(RID p_viewport,bool p_hide) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); viewport->hide_scenario=p_hide; } void VisualServerRaster::viewport_set_hide_canvas(RID p_viewport,bool p_hide) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); viewport->hide_canvas=p_hide; } void VisualServerRaster::viewport_attach_camera(RID p_viewport,RID p_camera) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); if (p_camera.is_valid()) { ERR_FAIL_COND(!camera_owner.owns(p_camera)); // a camera viewport->camera=p_camera; } else { viewport->camera=RID(); } } void VisualServerRaster::viewport_set_scenario(RID p_viewport,RID p_scenario) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); if (p_scenario.is_valid()) { ERR_FAIL_COND(!scenario_owner.owns(p_scenario)); // a camera viewport->scenario=p_scenario; } else { viewport->scenario=RID(); } } RID VisualServerRaster::viewport_get_attached_camera(RID p_viewport) const { const Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport, RID()); return viewport->camera; } void VisualServerRaster::viewport_attach_canvas(RID p_viewport,RID p_canvas) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); Canvas *canvas = canvas_owner.get( p_canvas ); ERR_FAIL_COND(!canvas); ERR_EXPLAIN("Canvas already attached."); ERR_FAIL_COND(viewport->canvas_map.has(p_canvas)); Viewport::CanvasData cd; cd.canvas=canvas; cd.layer=0; viewport->canvas_map[p_canvas]=cd; canvas->viewports.insert(p_viewport); } void VisualServerRaster::viewport_set_canvas_transform(RID p_viewport,RID p_canvas,const Matrix32& p_transform) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); Map<RID,Viewport::CanvasData>::Element *E=viewport->canvas_map.find(p_canvas); if (!E) { ERR_EXPLAIN("Viewport does not contain the canvas"); ERR_FAIL_COND(!E); } E->get().transform=p_transform; } Matrix32 VisualServerRaster::viewport_get_canvas_transform(RID p_viewport,RID p_canvas) const { Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport,Matrix32()); Map<RID,Viewport::CanvasData>::Element *E=viewport->canvas_map.find(p_canvas); if (!E) { ERR_EXPLAIN("Viewport does not contain the canvas"); ERR_FAIL_COND_V(!E,Matrix32()); } return E->get().transform; } void VisualServerRaster::viewport_set_global_canvas_transform(RID p_viewport,const Matrix32& p_transform) { VS_CHANGED Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); viewport->global_transform=p_transform; } Matrix32 VisualServerRaster::viewport_get_global_canvas_transform(RID p_viewport) const{ Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport,Matrix32()); return viewport->global_transform; } void VisualServerRaster::viewport_remove_canvas(RID p_viewport,RID p_canvas) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); Canvas *canvas = canvas_owner.get( p_canvas ); ERR_FAIL_COND(!canvas); Map<RID,Viewport::CanvasData>::Element *E=viewport->canvas_map.find(p_canvas); if (!E) { ERR_EXPLAIN("Viewport does not contain the canvas"); ERR_FAIL_COND(!E); } canvas->viewports.erase(p_viewport); viewport->canvas_map.erase(E); } void VisualServerRaster::viewport_set_canvas_layer(RID p_viewport,RID p_canvas,int p_layer) { VS_CHANGED; Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); Map<RID,Viewport::CanvasData>::Element *E=viewport->canvas_map.find(p_canvas); if (!E) { ERR_EXPLAIN("Viewport does not contain the canvas"); ERR_FAIL_COND(!E); } E->get().layer=p_layer; } void VisualServerRaster::viewport_set_transparent_background(RID p_viewport,bool p_enabled) { VS_CHANGED; Viewport *viewport=viewport_owner.get( p_viewport ); ERR_FAIL_COND(!viewport); viewport->transparent_bg=p_enabled; } bool VisualServerRaster::viewport_has_transparent_background(RID p_viewport) const { Viewport *viewport=viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport, false); return viewport->transparent_bg; } RID VisualServerRaster::viewport_get_scenario(RID p_viewport) const { const Viewport *viewport=NULL; viewport = viewport_owner.get( p_viewport ); ERR_FAIL_COND_V(!viewport, RID()); return viewport->scenario; } RID VisualServerRaster::environment_create() { return rasterizer->environment_create(); } void VisualServerRaster::environment_set_background(RID p_env,EnvironmentBG p_bg){ rasterizer->environment_set_background(p_env,p_bg); } VisualServer::EnvironmentBG VisualServerRaster::environment_get_background(RID p_env) const{ return rasterizer->environment_get_background(p_env); } void VisualServerRaster::environment_set_background_param(RID p_env,EnvironmentBGParam p_param, const Variant& p_value){ rasterizer->environment_set_background_param(p_env,p_param,p_value); } Variant VisualServerRaster::environment_get_background_param(RID p_env,EnvironmentBGParam p_param) const{ return rasterizer->environment_get_background_param(p_env,p_param); } void VisualServerRaster::environment_set_enable_fx(RID p_env,EnvironmentFx p_effect,bool p_enabled){ rasterizer->environment_set_enable_fx(p_env,p_effect,p_enabled); } bool VisualServerRaster::environment_is_fx_enabled(RID p_env,EnvironmentFx p_effect) const{ return rasterizer->environment_is_fx_enabled(p_env,p_effect); } void VisualServerRaster::environment_fx_set_param(RID p_env,EnvironmentFxParam p_param,const Variant& p_value){ rasterizer->environment_fx_set_param(p_env,p_param,p_value); } Variant VisualServerRaster::environment_fx_get_param(RID p_env,EnvironmentFxParam p_param) const { return environment_fx_get_param(p_env,p_param); } /* SCENARIO API */ void VisualServerRaster::_dependency_queue_update(RID p_rid,bool p_update_aabb) { Map< RID, Set<RID> >::Element * E = instance_dependency_map.find( p_rid ); if (!E) return; Set<RID>::Element *I = E->get().front(); while(I) { Instance *ins = instance_owner.get( I->get() ); _instance_queue_update( ins , p_update_aabb ); I = I->next(); } } void VisualServerRaster::_instance_queue_update(Instance *p_instance,bool p_update_aabb) { if (p_update_aabb) p_instance->update_aabb=true; if (p_instance->update) return; p_instance->update_next=instance_update_list; instance_update_list=p_instance; p_instance->update=true; } RID VisualServerRaster::scenario_create() { Scenario *scenario = memnew( Scenario ); ERR_FAIL_COND_V(!scenario,RID()); RID scenario_rid = scenario_owner.make_rid( scenario ); scenario->self=scenario_rid; scenario->octree.set_pair_callback(instance_pair,this); scenario->octree.set_unpair_callback(instance_unpair,this); return scenario_rid; } void VisualServerRaster::scenario_set_debug(RID p_scenario,ScenarioDebugMode p_debug_mode) { VS_CHANGED; Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); scenario->debug=p_debug_mode; } void VisualServerRaster::scenario_set_environment(RID p_scenario, RID p_environment) { VS_CHANGED; Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); scenario->environment=p_environment; } RID VisualServerRaster::scenario_get_environment(RID p_scenario, RID p_environment) const{ const Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND_V(!scenario,RID()); return scenario->environment; } /* INSTANCING API */ RID VisualServerRaster::instance_create() { Instance *instance = memnew( Instance ); ERR_FAIL_COND_V(!instance,RID()); RID instance_rid = instance_owner.make_rid(instance); instance->self=instance_rid; instance->base_type=INSTANCE_NONE; instance->scenario=NULL; return instance_rid; } void VisualServerRaster::instance_set_base(RID p_instance, RID p_base) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->base_type!=INSTANCE_NONE) { //free anything related to that base Map< RID, Set<RID> >::Element * E = instance_dependency_map.find( instance->base_rid ); if (E) { // wtf, no E? E->get().erase( instance->self ); } else { ERR_PRINT("no base E? Bug?"); } if ( instance->room ) { instance_set_room(p_instance,RID()); /* if((1<<instance->base_type)&INSTANCE_GEOMETRY_MASK) instance->room->room_info->owned_geometry_instances.erase(instance->RE); else if (instance->base_type==INSTANCE_PORTAL) { print_line("freeing portal, is it there? "+itos(instance->room->room_info->owned_portal_instances.(instance->RE))); instance->room->room_info->owned_portal_instances.erase(instance->RE); } else if (instance->base_type==INSTANCE_ROOM) instance->room->room_info->owned_room_instances.erase(instance->RE); else if (instance->base_type==INSTANCE_LIGHT) instance->room->room_info->owned_light_instances.erase(instance->RE); instance->RE=NULL;*/ } if (instance->light_info) { if (instance->scenario && instance->light_info->D) instance->scenario->directional_lights.erase( instance->light_info->D ); rasterizer->free(instance->light_info->instance); memdelete(instance->light_info); instance->light_info=NULL; } if (instance->portal_info) { _portal_disconnect(instance,true); memdelete(instance->portal_info); instance->portal_info=NULL; } if (instance->scenario && instance->octree_id) { instance->scenario->octree.erase( instance->octree_id ); instance->octree_id=0; } if (instance->room_info) { for(List<Instance*>::Element *E=instance->room_info->owned_geometry_instances.front();E;E=E->next()) { Instance *owned = E->get(); owned->room=NULL; owned->RE=NULL; } for(List<Instance*>::Element *E=instance->room_info->owned_portal_instances.front();E;E=E->next()) { _portal_disconnect(E->get(),true); Instance *owned = E->get(); owned->room=NULL; owned->RE=NULL; } for(List<Instance*>::Element *E=instance->room_info->owned_room_instances.front();E;E=E->next()) { Instance *owned = E->get(); owned->room=NULL; owned->RE=NULL; } if (instance->room_info->disconnected_child_portals.size()) { ERR_PRINT("BUG: Disconnected portals remain!"); } memdelete(instance->room_info); instance->room_info=NULL; } if (instance->particles_info) { rasterizer->free( instance->particles_info->instance ); memdelete(instance->particles_info); instance->particles_info=NULL; } instance->data.morph_values.clear(); } instance->base_type=INSTANCE_NONE; instance->base_rid=RID(); if (p_base.is_valid()) { if (rasterizer->is_mesh(p_base)) { instance->base_type=INSTANCE_MESH; instance->data.morph_values.resize( rasterizer->mesh_get_morph_target_count(p_base)); } else if (rasterizer->is_multimesh(p_base)) { instance->base_type=INSTANCE_MULTIMESH; } else if (rasterizer->is_particles(p_base)) { instance->base_type=INSTANCE_PARTICLES; instance->particles_info=memnew( Instance::ParticlesInfo ); instance->particles_info->instance = rasterizer->particles_instance_create( p_base ); } else if (rasterizer->is_light(p_base)) { instance->base_type=INSTANCE_LIGHT; instance->light_info = memnew( Instance::LightInfo ); instance->light_info->instance = rasterizer->light_instance_create(p_base); if (instance->scenario && rasterizer->light_get_type(p_base)==LIGHT_DIRECTIONAL) { instance->light_info->D = instance->scenario->directional_lights.push_back(instance->self); } } else if (room_owner.owns(p_base)) { instance->base_type=INSTANCE_ROOM; instance->room_info = memnew( Instance::RoomInfo ); instance->room_info->room=room_owner.get(p_base); } else if (portal_owner.owns(p_base)) { instance->base_type=INSTANCE_PORTAL; instance->portal_info = memnew(Instance::PortalInfo); instance->portal_info->portal=portal_owner.get(p_base); } else { ERR_EXPLAIN("Invalid base RID for instance!") ERR_FAIL(); } instance_dependency_map[ p_base ].insert( instance->self ); instance->base_rid=p_base; if (instance->scenario) _instance_queue_update(instance,true); } } RID VisualServerRaster::instance_get_base(RID p_instance) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, RID() ); return instance->base_rid; } void VisualServerRaster::instance_set_scenario(RID p_instance, RID p_scenario) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->scenario) { Map< RID, Set<RID> >::Element *E = instance_dependency_map.find( instance->scenario->self ); if (E) { // wtf, no E? E->get().erase( instance->self ); } else { ERR_PRINT("no scenario E? Bug?"); } if (instance->light_info) { if (instance->light_info->D) instance->scenario->directional_lights.erase( instance->light_info->D ); } if (instance->portal_info) { _portal_disconnect(instance,true); } if (instance->octree_id) { instance->scenario->octree.erase( instance->octree_id ); instance->octree_id=0; } instance->scenario=NULL; } if (p_scenario.is_valid()) { Scenario *scenario = scenario_owner.get( p_scenario ); ERR_FAIL_COND(!scenario); instance->scenario=scenario; instance_dependency_map[ p_scenario ].insert( instance->self ); instance->scenario=scenario; if (instance->base_type==INSTANCE_LIGHT && rasterizer->light_get_type(instance->base_rid)==LIGHT_DIRECTIONAL) { instance->light_info->D = instance->scenario->directional_lights.push_back(instance->self); } _instance_queue_update(instance,true); } } RID VisualServerRaster::instance_get_scenario(RID p_instance) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, RID() ); if (instance->scenario) return instance->scenario->self; else return RID(); } void VisualServerRaster::instance_set_layer_mask(RID p_instance, uint32_t p_mask) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); instance->layer_mask=p_mask; } uint32_t VisualServerRaster::instance_get_layer_mask(RID p_instance) const{ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, 0 ); return instance->layer_mask; } AABB VisualServerRaster::instance_get_base_aabb(RID p_instance) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, AABB() ); return instance->aabb; } void VisualServerRaster::instance_attach_object_instance_ID(RID p_instance,uint32_t p_ID) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); instance->object_ID=p_ID; } uint32_t VisualServerRaster::instance_get_object_instance_ID(RID p_instance) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, 0 ); return instance->object_ID; } void VisualServerRaster::instance_attach_skeleton(RID p_instance,RID p_skeleton) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); instance->data.skeleton=p_skeleton; } RID VisualServerRaster::instance_get_skeleton(RID p_instance) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, RID() ); return instance->data.skeleton; } void VisualServerRaster::instance_set_morph_target_weight(RID p_instance,int p_shape, float p_weight) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); ERR_FAIL_INDEX( p_shape, instance->data.morph_values.size() ); instance->data.morph_values[p_shape]=p_weight; } float VisualServerRaster::instance_get_morph_target_weight(RID p_instance,int p_shape) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, 0 ); ERR_FAIL_INDEX_V( p_shape, instance->data.morph_values.size(), 0 ); return instance->data.morph_values[p_shape]; } void VisualServerRaster::instance_set_transform(RID p_instance, const Transform& p_transform) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (p_transform==instance->data.transform) // must improve somehow return; instance->data.transform=p_transform; if (instance->base_type==INSTANCE_LIGHT) instance->data.transform.orthonormalize(); _instance_queue_update(instance); } Transform VisualServerRaster::instance_get_transform(RID p_instance) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, Transform() ); return instance->data.transform; } void VisualServerRaster::instance_set_exterior( RID p_instance, bool p_enabled ) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); ERR_EXPLAIN("Portals can't be assigned to be exterior"); ERR_FAIL_COND( instance->base_type == INSTANCE_PORTAL ); if (instance->exterior==p_enabled) return; instance->exterior=p_enabled; _instance_queue_update( instance ); } bool VisualServerRaster::instance_is_exterior( RID p_instance) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, false ); return instance->exterior; } void VisualServerRaster::instance_set_room( RID p_instance, RID p_room ) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->room && instance->RE) { //instance already havs a room, remove it from there if ( (1<<instance->base_type) & INSTANCE_GEOMETRY_MASK ) { instance->room->room_info->owned_geometry_instances.erase(instance->RE); if (!p_room.is_valid() && instance->octree_id) { //remove from the octree, so it's re-added with different flags instance->scenario->octree.erase( instance->octree_id ); instance->octree_id=0; _instance_queue_update( instance,true ); } } else if ( instance->base_type==INSTANCE_ROOM ) { instance->room->room_info->owned_room_instances.erase(instance->RE); for(List<Instance*>::Element *E=instance->room_info->owned_portal_instances.front();E;E=E->next()) { _portal_disconnect(E->get()); _instance_queue_update( E->get(),false ); } } else if ( instance->base_type==INSTANCE_PORTAL ) { _portal_disconnect(instance,true); bool ss = instance->room->room_info->owned_portal_instances.erase(instance->RE); } else if ( instance->base_type==INSTANCE_LIGHT ) { instance->room->room_info->owned_light_instances.erase(instance->RE); } else { ERR_FAIL(); } instance->RE=NULL; instance->room=NULL; } else { if (p_room.is_valid() && instance->octree_id) { //remove from the octree, so it's re-added with different flags instance->scenario->octree.erase( instance->octree_id ); instance->octree_id=0; _instance_queue_update( instance,true ); } } if (!p_room.is_valid()) return; // just clearning the room Instance *room = instance_owner.get( p_room ); ERR_FAIL_COND( !room ); ERR_FAIL_COND( room->base_type!=INSTANCE_ROOM ); if (instance->base_type==INSTANCE_ROOM) { //perform cycle test Instance *parent = instance; while(parent) { ERR_EXPLAIN("Cycle in room assignment"); ERR_FAIL_COND( parent == room ); parent=parent->room; } } if ( (1<<instance->base_type) & INSTANCE_GEOMETRY_MASK ) { instance->RE = room->room_info->owned_geometry_instances.push_back(instance); } else if ( instance->base_type==INSTANCE_ROOM ) { instance->RE = room->room_info->owned_room_instances.push_back(instance); for(List<Instance*>::Element *E=instance->room_info->owned_portal_instances.front();E;E=E->next()) _instance_queue_update( E->get(),false ); } else if ( instance->base_type==INSTANCE_PORTAL ) { instance->RE = room->room_info->owned_portal_instances.push_back(instance); } else if ( instance->base_type==INSTANCE_LIGHT ) { instance->RE = room->room_info->owned_light_instances.push_back(instance); } else { ERR_FAIL(); } instance->room=room; } RID VisualServerRaster::instance_get_room( RID p_instance ) const { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, RID() ); if (instance->room) return instance->room->self; else return RID(); } void VisualServerRaster::instance_set_extra_visibility_margin( RID p_instance, real_t p_margin ) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); instance->extra_margin=p_margin; } real_t VisualServerRaster::instance_get_extra_visibility_margin( RID p_instance ) const{ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, 0 ); return instance->extra_margin; } Vector<RID> VisualServerRaster::instances_cull_aabb(const AABB& p_aabb, RID p_scenario) const { Vector<RID> instances; Scenario *scenario=scenario_owner.get(p_scenario); ERR_FAIL_COND_V(!scenario,instances); const_cast<VisualServerRaster*>(this)->_update_instances(); // check dirty instances before culling int culled=0; Instance *cull[1024]; culled=scenario->octree.cull_AABB(p_aabb,cull,1024); for (int i=0;i<culled;i++) { Instance *instance=cull[i]; ERR_CONTINUE(!instance); instances.push_back(instance->self); } return instances; } Vector<RID> VisualServerRaster::instances_cull_ray(const Vector3& p_from, const Vector3& p_to, RID p_scenario) const{ Vector<RID> instances; Scenario *scenario=scenario_owner.get(p_scenario); ERR_FAIL_COND_V(!scenario,instances); const_cast<VisualServerRaster*>(this)->_update_instances(); // check dirty instances before culling int culled=0; Instance *cull[1024]; culled=scenario->octree.cull_segment(p_from,p_to*10000,cull,1024); for (int i=0;i<culled;i++) { Instance *instance=cull[i]; ERR_CONTINUE(!instance); instances.push_back(instance->self); } return instances; } Vector<RID> VisualServerRaster::instances_cull_convex(const Vector<Plane>& p_convex, RID p_scenario) const{ Vector<RID> instances; Scenario *scenario=scenario_owner.get(p_scenario); ERR_FAIL_COND_V(!scenario,instances); const_cast<VisualServerRaster*>(this)->_update_instances(); // check dirty instances before culling int culled=0; Instance *cull[1024]; culled=scenario->octree.cull_convex(p_convex,cull,1024); for (int i=0;i<culled;i++) { Instance *instance=cull[i]; ERR_CONTINUE(!instance); instances.push_back(instance->self); } return instances; } void VisualServerRaster::instance_geometry_set_flag(RID p_instance,InstanceFlags p_flags,bool p_enabled) { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); // ERR_FAIL_COND( ! ( (1<<instance->base_type) & INSTANCE_GEOMETRY_MASK) ); switch(p_flags) { case INSTANCE_FLAG_VISIBLE: { instance->visible=p_enabled; } break; case INSTANCE_FLAG_BILLBOARD: { instance->data.billboard=p_enabled; } break; case INSTANCE_FLAG_BILLBOARD_FIX_Y: { instance->data.billboard_y=p_enabled; } break; case INSTANCE_FLAG_CAST_SHADOW: { instance->cast_shadows=p_enabled; } break; case INSTANCE_FLAG_RECEIVE_SHADOWS: { instance->receive_shadows=p_enabled; } break; case INSTANCE_FLAG_DEPH_SCALE: { instance->data.depth_scale=p_enabled; } break; case INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS: { instance->visible_in_all_rooms=p_enabled; } break; } } bool VisualServerRaster::instance_geometry_get_flag(RID p_instance,InstanceFlags p_flags) const{ const Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, false ); // ERR_FAIL_COND_V( ! ( (1<<instance->base_type) & INSTANCE_GEOMETRY_MASK), false ); switch(p_flags) { case INSTANCE_FLAG_VISIBLE: { return instance->visible; } break; case INSTANCE_FLAG_BILLBOARD: { return instance->data.billboard; } break; case INSTANCE_FLAG_BILLBOARD_FIX_Y: { return instance->data.billboard_y; } break; case INSTANCE_FLAG_CAST_SHADOW: { return instance->cast_shadows; } break; case INSTANCE_FLAG_RECEIVE_SHADOWS: { return instance->receive_shadows; } break; case INSTANCE_FLAG_DEPH_SCALE: { return instance->data.depth_scale; } break; case INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS: { return instance->visible_in_all_rooms; } break; } return false; } void VisualServerRaster::instance_geometry_set_material_override(RID p_instance, RID p_material) { VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); instance->data.material_override=p_material; } RID VisualServerRaster::instance_geometry_get_material_override(RID p_instance) const{ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance, RID() ); return instance->data.material_override; } void VisualServerRaster::instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max){ VS_CHANGED; Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); instance->draw_range_begin=p_min; instance->draw_range_end=p_max; } float VisualServerRaster::instance_geometry_get_draw_range_min(RID p_instance) const{ const Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance,0 ); return instance->draw_range_begin; } float VisualServerRaster::instance_geometry_get_draw_range_max(RID p_instance) const{ const Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND_V( !instance,0 ); return instance->draw_range_end; } void VisualServerRaster::_update_instance(Instance *p_instance) { p_instance->version++; if (p_instance->base_type == INSTANCE_LIGHT) { rasterizer->light_instance_set_transform( p_instance->light_info->instance, p_instance->data.transform ); } if (p_instance->aabb.has_no_surface()) return; if (p_instance->base_type == INSTANCE_PARTICLES) { rasterizer->particles_instance_set_transform( p_instance->particles_info->instance, p_instance->data.transform ); } if (p_instance->base_type&INSTANCE_GEOMETRY_MASK) { //make sure lights are updated InstanceSet::Element *E=p_instance->lights.front(); while(E) { E->get()->version++; E=E->next(); } } if (p_instance->base_type == INSTANCE_ROOM) { p_instance->room_info->affine_inverse=p_instance->data.transform.affine_inverse(); } p_instance->data.mirror = p_instance->data.transform.basis.determinant() < 0.0; AABB new_aabb; if (p_instance->base_type==INSTANCE_PORTAL) { //portals need to be transformed in a special way, so they don't become too wide if they have scale.. Transform portal_xform = p_instance->data.transform; portal_xform.basis.set_axis(2,portal_xform.basis.get_axis(2).normalized()); p_instance->portal_info->plane_cache=Plane( p_instance->data.transform.origin, portal_xform.basis.get_axis(2)); int point_count=p_instance->portal_info->portal->shape.size(); p_instance->portal_info->transformed_point_cache.resize(point_count); AABB portal_aabb; for(int i=0;i<point_count;i++) { Point2 src = p_instance->portal_info->portal->shape[i]; Vector3 point = portal_xform.xform(Vector3(src.x,src.y,0)); p_instance->portal_info->transformed_point_cache[i]=point; if (i==0) portal_aabb.pos=point; else portal_aabb.expand_to(point); } portal_aabb.grow_by(p_instance->portal_info->portal->connect_range); new_aabb = portal_aabb; } else { new_aabb = p_instance->data.transform.xform(p_instance->aabb); } for(InstanceSet::Element *E=p_instance->lights.front();E;E=E->next()) { Instance *light = E->get(); light->version++; } p_instance->transformed_aabb=new_aabb; if (!p_instance->scenario) { return; } if (p_instance->octree_id==0) { uint32_t base_type = 1<<p_instance->base_type; uint32_t pairable_mask=0; bool pairable=false; if (p_instance->base_type == INSTANCE_LIGHT) { pairable_mask=INSTANCE_GEOMETRY_MASK; pairable=true; } if (p_instance->base_type == INSTANCE_PORTAL) { pairable_mask=(1<<INSTANCE_PORTAL); pairable=true; } if (!p_instance->room && (1<<p_instance->base_type)&INSTANCE_GEOMETRY_MASK) { base_type|=INSTANCE_ROOMLESS_MASK; } if (p_instance->base_type == INSTANCE_ROOM) { pairable_mask=INSTANCE_ROOMLESS_MASK; pairable=true; } // not inside octree p_instance->octree_id = p_instance->scenario->octree.create(p_instance,new_aabb,0,pairable,base_type,pairable_mask); } else { // if (new_aabb==p_instance->data.transformed_aabb) // return; p_instance->scenario->octree.move(p_instance->octree_id,new_aabb); } if (p_instance->base_type==INSTANCE_PORTAL) { _portal_attempt_connect(p_instance); } if (!p_instance->room && (1<<p_instance->base_type)&INSTANCE_GEOMETRY_MASK) { _instance_validate_autorooms(p_instance); } if (p_instance->base_type == INSTANCE_ROOM) { for(Set<Instance*>::Element *E=p_instance->room_info->owned_autoroom_geometry.front();E;E=E->next()) _instance_validate_autorooms(E->get()); } } void VisualServerRaster::_update_instance_aabb(Instance *p_instance) { AABB new_aabb; ERR_FAIL_COND(p_instance->base_type!=INSTANCE_NONE && !p_instance->base_rid.is_valid()); switch(p_instance->base_type) { case VisualServer::INSTANCE_NONE: { // do nothing } break; case VisualServer::INSTANCE_MESH: { new_aabb = rasterizer->mesh_get_aabb(p_instance->base_rid); } break; case VisualServer::INSTANCE_MULTIMESH: { new_aabb = rasterizer->multimesh_get_aabb(p_instance->base_rid); } break; case VisualServer::INSTANCE_PARTICLES: { new_aabb = rasterizer->particles_get_aabb(p_instance->base_rid); } break; case VisualServer::INSTANCE_LIGHT: { new_aabb = rasterizer->light_get_aabb(p_instance->base_rid); } break; case VisualServer::INSTANCE_ROOM: { Room *room = room_owner.get( p_instance->base_rid ); ERR_FAIL_COND(!room); new_aabb=room->bounds.get_aabb(); } break; case VisualServer::INSTANCE_PORTAL: { Portal *portal = portal_owner.get( p_instance->base_rid ); ERR_FAIL_COND(!portal); for (int i=0;i<portal->shape.size();i++) { Vector3 point( portal->shape[i].x, portal->shape[i].y, 0 ); if (i==0) { new_aabb.pos=point; new_aabb.size.z=0.01; // make it not flat for octree } else { new_aabb.expand_to(point); } } } break; default: {} } if (p_instance->extra_margin) new_aabb.grow_by(p_instance->extra_margin); p_instance->aabb=new_aabb; } void VisualServerRaster::_update_instances() { while(instance_update_list) { Instance *instance=instance_update_list; instance_update_list=instance_update_list->update_next; if (instance->update_aabb) _update_instance_aabb(instance); _update_instance(instance); instance->update=false; instance->update_aabb=false; instance->update_next=0; } } /****** CANVAS *********/ RID VisualServerRaster::canvas_create() { Canvas * canvas = memnew( Canvas ); ERR_FAIL_COND_V(!canvas,RID()); RID rid = canvas_owner.make_rid( canvas ); return rid; } void VisualServerRaster::canvas_set_item_mirroring(RID p_canvas,RID p_item,const Point2& p_mirroring) { Canvas * canvas = canvas_owner.get(p_canvas); ERR_FAIL_COND(!canvas); CanvasItem *canvas_item = canvas_item_owner.get(p_item); ERR_FAIL_COND(!canvas_item); int idx = canvas->find_item(canvas_item); ERR_FAIL_COND(idx==-1); canvas->child_items[idx].mirror=p_mirroring; } Point2 VisualServerRaster::canvas_get_item_mirroring(RID p_canvas,RID p_item) const { Canvas * canvas = canvas_owner.get(p_canvas); ERR_FAIL_COND_V(!canvas,Point2()); CanvasItem *canvas_item = memnew( CanvasItem ); ERR_FAIL_COND_V(!canvas_item,Point2()); int idx = canvas->find_item(canvas_item); ERR_FAIL_COND_V(idx==-1,Point2()); return canvas->child_items[idx].mirror; } RID VisualServerRaster::canvas_item_create() { CanvasItem *canvas_item = memnew( CanvasItem ); ERR_FAIL_COND_V(!canvas_item,RID()); return canvas_item_owner.make_rid( canvas_item ); } void VisualServerRaster::canvas_item_set_parent(RID p_item,RID p_parent) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); if (canvas_item->parent.is_valid()) { if (canvas_owner.owns(canvas_item->parent)) { Canvas *canvas = canvas_owner.get(canvas_item->parent); canvas->erase_item(canvas_item); } else if (canvas_item_owner.owns(canvas_item->parent)) { CanvasItem *item_owner = canvas_item_owner.get(canvas_item->parent); item_owner->child_items.erase(canvas_item); } canvas_item->parent=RID(); } if (p_parent.is_valid()) { if (canvas_owner.owns(p_parent)) { Canvas *canvas = canvas_owner.get(p_parent); Canvas::ChildItem ci; ci.item=canvas_item; canvas->child_items.push_back(ci); } else if (canvas_item_owner.owns(p_parent)) { CanvasItem *item_owner = canvas_item_owner.get(p_parent); item_owner->child_items.push_back(canvas_item); } else { ERR_EXPLAIN("Invalid parent"); ERR_FAIL(); } } canvas_item->parent=p_parent; } RID VisualServerRaster::canvas_item_get_parent(RID p_canvas_item) const { CanvasItem *canvas_item = canvas_item_owner.get( p_canvas_item ); ERR_FAIL_COND_V(!canvas_item,RID()); return canvas_item->parent; } void VisualServerRaster::canvas_item_set_visible(RID p_item,bool p_visible) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->visible=p_visible; } bool VisualServerRaster::canvas_item_is_visible(RID p_item) const { CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND_V(!canvas_item,RID()); return canvas_item->visible; } void VisualServerRaster::canvas_item_set_blend_mode(RID p_canvas_item,MaterialBlendMode p_blend) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_canvas_item ); if (!canvas_item) { printf("!canvas_item\n"); }; ERR_FAIL_COND(!canvas_item); if (canvas_item->blend_mode==p_blend) return; VS_CHANGED; canvas_item->blend_mode=p_blend; } void VisualServerRaster::canvas_item_attach_viewport(RID p_canvas_item, RID p_viewport) { CanvasItem *canvas_item = canvas_item_owner.get( p_canvas_item ); ERR_FAIL_COND(!canvas_item); VS_CHANGED; canvas_item->viewport=p_viewport; } /* void VisualServerRaster::canvas_item_set_rect(RID p_item, const Rect2& p_rect) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->rect=p_rect; }*/ void VisualServerRaster::canvas_item_set_clip(RID p_item, bool p_clip) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->clip=p_clip; } const Rect2& VisualServerRaster::CanvasItem::get_rect() const { if (custom_rect || !rect_dirty) return rect; //must update rect int s=commands.size(); if (s==0) { rect=Rect2(); rect_dirty=false; return rect; } Matrix32 xf; bool found_xform=false; bool first=true; const CanvasItem::Command * const *cmd = &commands[0]; for (int i=0;i<s;i++) { const CanvasItem::Command *c=cmd[i]; Rect2 r; switch(c->type) { case CanvasItem::Command::TYPE_LINE: { const CanvasItem::CommandLine* line = static_cast< const CanvasItem::CommandLine*>(c); r.pos=line->from; r.expand_to(line->to); } break; case CanvasItem::Command::TYPE_RECT: { const CanvasItem::CommandRect* crect = static_cast< const CanvasItem::CommandRect*>(c); r=crect->rect; } break; case CanvasItem::Command::TYPE_STYLE: { const CanvasItem::CommandStyle* style = static_cast< const CanvasItem::CommandStyle*>(c); r=style->rect; } break; case CanvasItem::Command::TYPE_PRIMITIVE: { const CanvasItem::CommandPrimitive* primitive = static_cast< const CanvasItem::CommandPrimitive*>(c); r.pos=primitive->points[0]; for(int i=1;i<primitive->points.size();i++) { r.expand_to(primitive->points[i]); } } break; case CanvasItem::Command::TYPE_POLYGON: { const CanvasItem::CommandPolygon* polygon = static_cast< const CanvasItem::CommandPolygon*>(c); int l = polygon->points.size(); const Point2*pp=&polygon->points[0]; r.pos=pp[0]; for(int i=1;i<l;i++) { r.expand_to(pp[i]); } } break; case CanvasItem::Command::TYPE_POLYGON_PTR: { const CanvasItem::CommandPolygonPtr* polygon = static_cast< const CanvasItem::CommandPolygonPtr*>(c); int l = polygon->count; if (polygon->indices != NULL) { r.pos=polygon->points[polygon->indices[0]]; for (int i=1; i<polygon->count; i++) { r.expand_to(polygon->points[polygon->indices[i]]); }; } else { r.pos=polygon->points[0]; for (int i=1; i<polygon->count; i++) { r.expand_to(polygon->points[i]); }; }; } break; case CanvasItem::Command::TYPE_CIRCLE: { const CanvasItem::CommandCircle* circle = static_cast< const CanvasItem::CommandCircle*>(c); r.pos=Point2(-circle->radius,-circle->radius)+circle->pos; r.size=Point2(circle->radius*2.0,circle->radius*2.0); } break; case CanvasItem::Command::TYPE_TRANSFORM: { const CanvasItem::CommandTransform* transform = static_cast<const CanvasItem::CommandTransform*>(c); xf=transform->xform; found_xform=true; continue; } break; case CanvasItem::Command::TYPE_BLEND_MODE: { } break; case CanvasItem::Command::TYPE_CLIP_IGNORE: { } break; } if (found_xform) { r = xf.xform(r); found_xform=false; } if (first) { rect=r; first=false; } else rect=rect.merge(r); } rect_dirty=false; return rect; } void VisualServerRaster::canvas_item_set_transform(RID p_item, const Matrix32& p_transform) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->xform=p_transform; } void VisualServerRaster::canvas_item_set_custom_rect(RID p_item, bool p_custom_rect,const Rect2& p_rect) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->custom_rect=p_custom_rect; if (p_custom_rect) canvas_item->rect=p_rect; } void VisualServerRaster::canvas_item_set_opacity(RID p_item, float p_opacity) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->opacity=p_opacity; } float VisualServerRaster::canvas_item_get_opacity(RID p_item, float p_opacity) const { CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND_V(!canvas_item,-1); return canvas_item->opacity; } void VisualServerRaster::canvas_item_set_on_top(RID p_item, bool p_on_top) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->ontop=p_on_top; } bool VisualServerRaster::canvas_item_is_on_top(RID p_item) const{ const CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND_V(!canvas_item,false); return canvas_item->ontop; } void VisualServerRaster::canvas_item_set_self_opacity(RID p_item, float p_self_opacity) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->self_opacity=p_self_opacity; } float VisualServerRaster::canvas_item_get_self_opacity(RID p_item, float p_self_opacity) const { CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND_V(!canvas_item,-1); return canvas_item->self_opacity; } void VisualServerRaster::canvas_item_add_line(RID p_item, const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandLine * line = memnew( CanvasItem::CommandLine ); ERR_FAIL_COND(!line); line->color=p_color; line->from=p_from; line->to=p_to; line->width=p_width; canvas_item->rect_dirty=true; canvas_item->commands.push_back(line); } void VisualServerRaster::canvas_item_add_rect(RID p_item, const Rect2& p_rect, const Color& p_color) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandRect * rect = memnew( CanvasItem::CommandRect ); ERR_FAIL_COND(!rect); rect->modulate=p_color; rect->rect=p_rect; canvas_item->rect_dirty=true; canvas_item->commands.push_back(rect); } void VisualServerRaster::canvas_item_add_circle(RID p_item, const Point2& p_pos, float p_radius,const Color& p_color) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandCircle * circle = memnew( CanvasItem::CommandCircle ); ERR_FAIL_COND(!circle); circle->color=p_color; circle->pos=p_pos; circle->radius=p_radius; canvas_item->commands.push_back(circle); } void VisualServerRaster::canvas_item_add_texture_rect(RID p_item, const Rect2& p_rect, RID p_texture,bool p_tile,const Color& p_modulate) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandRect * rect = memnew( CanvasItem::CommandRect ); ERR_FAIL_COND(!rect); rect->modulate=p_modulate; rect->rect=p_rect; rect->flags=0; if (p_tile) rect->flags|=Rasterizer::CANVAS_RECT_TILE; if (p_rect.size.x<0) { rect->flags|=Rasterizer::CANVAS_RECT_FLIP_H; rect->rect.size.x = -rect->rect.size.x; } if (p_rect.size.y<0) { rect->flags|=Rasterizer::CANVAS_RECT_FLIP_V; rect->rect.size.y = -rect->rect.size.y; } rect->texture=p_texture; canvas_item->rect_dirty=true; canvas_item->commands.push_back(rect); } void VisualServerRaster::canvas_item_add_texture_rect_region(RID p_item, const Rect2& p_rect, RID p_texture,const Rect2& p_src_rect,const Color& p_modulate) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandRect * rect = memnew( CanvasItem::CommandRect ); ERR_FAIL_COND(!rect); rect->modulate=p_modulate; rect->rect=p_rect; rect->texture=p_texture; rect->source=p_src_rect; rect->flags=Rasterizer::CANVAS_RECT_REGION; if (p_rect.size.x<0) { rect->flags|=Rasterizer::CANVAS_RECT_FLIP_H; rect->rect.size.x = -rect->rect.size.x; } if (p_rect.size.y<0) { rect->flags|=Rasterizer::CANVAS_RECT_FLIP_V; rect->rect.size.y = -rect->rect.size.y; } canvas_item->rect_dirty=true; canvas_item->commands.push_back(rect); } void VisualServerRaster::canvas_item_add_style_box(RID p_item, const Rect2& p_rect, RID p_texture,const Vector2& p_topleft, const Vector2& p_bottomright, bool p_draw_center,const Color& p_modulate) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandStyle * style = memnew( CanvasItem::CommandStyle ); ERR_FAIL_COND(!style); style->texture=p_texture; style->rect=p_rect; style->draw_center=p_draw_center; style->color=p_modulate; style->margin[MARGIN_LEFT]=p_topleft.x; style->margin[MARGIN_TOP]=p_topleft.y; style->margin[MARGIN_RIGHT]=p_bottomright.x; style->margin[MARGIN_BOTTOM]=p_bottomright.y; canvas_item->rect_dirty=true; canvas_item->commands.push_back(style); } void VisualServerRaster::canvas_item_add_primitive(RID p_item,const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandPrimitive * prim = memnew( CanvasItem::CommandPrimitive ); ERR_FAIL_COND(!prim); prim->texture=p_texture; prim->points=p_points; prim->uvs=p_uvs; prim->colors=p_colors; prim->width=p_width; canvas_item->rect_dirty=true; canvas_item->commands.push_back(prim); } void VisualServerRaster::canvas_item_add_polygon(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); #ifdef DEBUG_ENABLED int pointcount = p_points.size(); ERR_FAIL_COND(pointcount<3); int color_size=p_colors.size(); int uv_size=p_uvs.size(); ERR_FAIL_COND(color_size!=0 && color_size!=1 && color_size!=pointcount); ERR_FAIL_COND(uv_size!=0 && (uv_size!=pointcount || !p_texture.is_valid())); #endif Vector<int> indices = Geometry::triangulate_polygon(p_points); if (indices.empty()) { ERR_EXPLAIN("Bad Polygon!"); ERR_FAIL_V(); } CanvasItem::CommandPolygon * polygon = memnew( CanvasItem::CommandPolygon ); ERR_FAIL_COND(!polygon); polygon->texture=p_texture; polygon->points=p_points; polygon->uvs=p_uvs; polygon->colors=p_colors; polygon->indices=indices; polygon->count=indices.size(); canvas_item->rect_dirty=true; canvas_item->commands.push_back(polygon); } void VisualServerRaster::canvas_item_add_triangle_array_ptr(RID p_item, int p_count, const int* p_indices, const Point2* p_points, const Color* p_colors,const Point2* p_uvs, RID p_texture) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); ERR_FAIL_COND(p_count <= 0); ERR_FAIL_COND(p_points == NULL); CanvasItem::CommandPolygonPtr * polygon = memnew( CanvasItem::CommandPolygonPtr ); ERR_FAIL_COND(!polygon); polygon->texture=p_texture; polygon->points=p_points; polygon->uvs=p_uvs; polygon->colors=p_colors; polygon->indices=p_indices; polygon->count = p_count * 3; canvas_item->rect_dirty=true; canvas_item->commands.push_back(polygon); }; void VisualServerRaster::canvas_item_add_triangle_array(RID p_item, const Vector<int>& p_indices, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture, int p_count) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); int ps = p_points.size(); ERR_FAIL_COND(!p_colors.empty() && p_colors.size()!=ps); ERR_FAIL_COND(!p_uvs.empty() && p_uvs.size()!=ps); Vector<int> indices = p_indices; int count = p_count * 3; if (indices.empty()) { ERR_FAIL_COND( ps % 3 != 0 ); if (p_count == -1) count = ps; } else { ERR_FAIL_COND( indices.size() % 3 != 0 ); if (p_count == -1) count = indices.size(); } CanvasItem::CommandPolygon * polygon = memnew( CanvasItem::CommandPolygon ); ERR_FAIL_COND(!polygon); polygon->texture=p_texture; polygon->points=p_points; polygon->uvs=p_uvs; polygon->colors=p_colors; polygon->indices=indices; polygon->count = count; canvas_item->rect_dirty=true; canvas_item->commands.push_back(polygon); } void VisualServerRaster::canvas_item_add_set_transform(RID p_item,const Matrix32& p_transform) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandTransform * tr = memnew( CanvasItem::CommandTransform ); ERR_FAIL_COND(!tr); tr->xform=p_transform; canvas_item->commands.push_back(tr); } void VisualServerRaster::canvas_item_add_set_blend_mode(RID p_item, MaterialBlendMode p_blend) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandBlendMode * bm = memnew( CanvasItem::CommandBlendMode ); ERR_FAIL_COND(!bm); bm->blend_mode = p_blend; canvas_item->commands.push_back(bm); }; void VisualServerRaster::canvas_item_add_clip_ignore(RID p_item, bool p_ignore) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); CanvasItem::CommandClipIgnore * ci = memnew( CanvasItem::CommandClipIgnore); ERR_FAIL_COND(!ci); ci->ignore=p_ignore; canvas_item->commands.push_back(ci); } void VisualServerRaster::canvas_item_clear(RID p_item) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->clear(); } void VisualServerRaster::canvas_item_raise(RID p_item) { VS_CHANGED; CanvasItem *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); if (canvas_item->parent.is_valid()) { if (canvas_owner.owns(canvas_item->parent)) { Canvas *canvas = canvas_owner.get(canvas_item->parent); int idx = canvas->find_item(canvas_item); ERR_FAIL_COND(idx<0); Canvas::ChildItem ci = canvas->child_items[idx]; canvas->child_items.remove(idx); canvas->child_items.push_back(ci); } else if (canvas_item_owner.owns(canvas_item->parent)) { CanvasItem *item_owner = canvas_item_owner.get(canvas_item->parent); int idx = item_owner->child_items.find(canvas_item); ERR_FAIL_COND(idx<0); item_owner->child_items.remove(idx); item_owner->child_items.push_back(canvas_item); } } } /******** CANVAS *********/ void VisualServerRaster::cursor_set_rotation(float p_rotation, int p_cursor) { VS_CHANGED; ERR_FAIL_INDEX(p_cursor, MAX_CURSORS); cursors[p_cursor].rot = p_rotation; }; void VisualServerRaster::cursor_set_texture(RID p_texture, const Point2 &p_center_offset, int p_cursor) { VS_CHANGED; ERR_FAIL_INDEX(p_cursor, MAX_CURSORS); cursors[p_cursor].texture = p_texture; cursors[p_cursor].center = p_center_offset; }; void VisualServerRaster::cursor_set_visible(bool p_visible, int p_cursor) { VS_CHANGED; ERR_FAIL_INDEX(p_cursor, MAX_CURSORS); cursors[p_cursor].visible = p_visible; }; void VisualServerRaster::cursor_set_pos(const Point2& p_pos, int p_cursor) { ERR_FAIL_INDEX(p_cursor, MAX_CURSORS); if (cursors[p_cursor].pos==p_pos) return; VS_CHANGED; cursors[p_cursor].pos = p_pos; }; void VisualServerRaster::black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom) { black_margin[MARGIN_LEFT]=p_left; black_margin[MARGIN_TOP]=p_top; black_margin[MARGIN_RIGHT]=p_right; black_margin[MARGIN_BOTTOM]=p_bottom; } void VisualServerRaster::_free_attached_instances(RID p_rid,bool p_free_scenario) { Map< RID, Set<RID> >::Element * E = instance_dependency_map.find( p_rid ); if (E) { // has instances while( E->get().size() ) { // erase all attached instances if (p_free_scenario) instance_set_scenario( E->get().front()->get(), RID() ); else instance_set_base( E->get().front()->get(), RID() ); } } instance_dependency_map.erase(p_rid); } void VisualServerRaster::custom_shade_model_set_shader(int p_model, RID p_shader) { VS_CHANGED; // rasterizer->custom_shade_model_set_shader(p_model,p_shader); } RID VisualServerRaster::custom_shade_model_get_shader(int p_model) const { //return rasterizer->custom_shade_model_get_shader(p_model); return RID(); } void VisualServerRaster::custom_shade_model_set_name(int p_model, const String& p_name) { //rasterizer->custom_shade_model_set_name(p_model,p_name); } String VisualServerRaster::custom_shade_model_get_name(int p_model) const { //return rasterizer->custom_shade_model_get_name(p_model); return ""; } void VisualServerRaster::custom_shade_model_set_param_info(int p_model, const List<PropertyInfo>& p_info) { VS_CHANGED; //rasterizer->custom_shade_model_set_param_info(p_model,p_info); } void VisualServerRaster::custom_shade_model_get_param_info(int p_model, List<PropertyInfo>* p_info) const { //rasterizer->custom_shade_model_get_param_info(p_model,p_info); } void VisualServerRaster::free( RID p_rid ) { VS_CHANGED; if (rasterizer->is_texture(p_rid) || rasterizer->is_material(p_rid) || rasterizer->is_skeleton(p_rid) || rasterizer->is_shader(p_rid)) { rasterizer->free(p_rid); } else if (rasterizer->is_mesh(p_rid) || rasterizer->is_multimesh(p_rid) || rasterizer->is_light(p_rid) || rasterizer->is_particles(p_rid) ) { //delete the resource _free_attached_instances(p_rid); rasterizer->free(p_rid); } else if (room_owner.owns(p_rid)) { _free_attached_instances(p_rid); Room *room = room_owner.get(p_rid); ERR_FAIL_COND(!room); room_owner.free(p_rid); memdelete(room); } else if (portal_owner.owns(p_rid)) { _free_attached_instances(p_rid); Portal *portal = portal_owner.get(p_rid); ERR_FAIL_COND(!portal); portal_owner.free(p_rid); memdelete(portal); } else if (camera_owner.owns(p_rid)) { // delete te camera Camera *camera = camera_owner.get(p_rid); ERR_FAIL_COND(!camera); camera_owner.free( p_rid ); memdelete(camera); } else if (viewport_owner.owns(p_rid)) { // delete the viewport Viewport *viewport = viewport_owner.get( p_rid ); ERR_FAIL_COND(!viewport); // Viewport *parent=NULL; rasterizer->free(viewport->viewport_data); if (viewport->render_target.is_valid()) { rasterizer->free(viewport->render_target); } if (viewport->update_list.in_list()) viewport_update_list.remove(&viewport->update_list); if (screen_viewports.has(p_rid)) screen_viewports.erase(p_rid); while(viewport->canvas_map.size()) { Canvas *c = viewport->canvas_map.front()->get().canvas; c->viewports.erase(p_rid); viewport->canvas_map.erase(viewport->canvas_map.front()); } viewport_owner.free(p_rid); memdelete(viewport); } else if (instance_owner.owns(p_rid)) { // delete the instance _update_instances(); // be sure Instance *instance = instance_owner.get(p_rid); ERR_FAIL_COND(!instance); instance_set_room(p_rid,RID()); instance_set_scenario(p_rid,RID()); instance_set_base(p_rid,RID()); instance_owner.free(p_rid); memdelete(instance); } else if (canvas_owner.owns(p_rid)) { Canvas *canvas = canvas_owner.get(p_rid); ERR_FAIL_COND(!canvas); while(canvas->viewports.size()) { Viewport *vp = viewport_owner.get(canvas->viewports.front()->get()); ERR_FAIL_COND(!vp); Map<RID,Viewport::CanvasData>::Element *E=vp->canvas_map.find(p_rid); ERR_FAIL_COND(!E); vp->canvas_map.erase(p_rid); canvas->viewports.erase( canvas->viewports.front() ); } for (int i=0;i<canvas->child_items.size();i++) { canvas->child_items[i].item->parent=RID(); } canvas_owner.free( p_rid ); memdelete( canvas ); } else if (canvas_item_owner.owns(p_rid)) { CanvasItem *canvas_item = canvas_item_owner.get(p_rid); ERR_FAIL_COND(!canvas_item); if (canvas_item->parent.is_valid()) { if (canvas_owner.owns(canvas_item->parent)) { Canvas *canvas = canvas_owner.get(canvas_item->parent); canvas->erase_item(canvas_item); } else if (canvas_item_owner.owns(canvas_item->parent)) { CanvasItem *item_owner = canvas_item_owner.get(canvas_item->parent); item_owner->child_items.erase(canvas_item); } } for (int i=0;i<canvas_item->child_items.size();i++) { canvas_item->child_items[i]->parent=RID(); } canvas_item_owner.free( p_rid ); memdelete( canvas_item ); } else if (scenario_owner.owns(p_rid)) { Scenario *scenario=scenario_owner.get(p_rid); ERR_FAIL_COND(!scenario); _update_instances(); // be sure _free_attached_instances(p_rid,true); //rasterizer->free( scenario->environment ); scenario_owner.free(p_rid); memdelete(scenario); } else { ERR_FAIL(); } } void VisualServerRaster::_instance_draw(Instance *p_instance) { if (p_instance->light_cache_dirty) { int l=0; //add positional lights InstanceSet::Element *LE=p_instance->lights.front(); p_instance->data.light_instances.resize(p_instance->lights.size()); while(LE) { p_instance->data.light_instances[l++]=LE->get()->light_info->instance; LE=LE->next(); } p_instance->light_cache_dirty=false; } switch(p_instance->base_type) { case INSTANCE_MESH: { const float *morphs = NULL; if (!p_instance->data.morph_values.empty()) { morphs=&p_instance->data.morph_values[0]; } rasterizer->add_mesh(p_instance->base_rid, &p_instance->data); } break; case INSTANCE_MULTIMESH: { rasterizer->add_multimesh(p_instance->base_rid, &p_instance->data); } break; case INSTANCE_PARTICLES: { rasterizer->add_particles(p_instance->particles_info->instance, &p_instance->data); } break; default: {}; } } Vector<Vector3> VisualServerRaster::_camera_generate_endpoints(Instance *p_light,Camera *p_camera,float p_range_min, float p_range_max) { // setup a camera matrix for that range! CameraMatrix camera_matrix; switch(p_camera->type) { case Camera::ORTHOGONAL: { camera_matrix.set_orthogonal(p_camera->size,viewport_rect.width / (float)viewport_rect.height,p_range_min,p_range_max,p_camera->vaspect); } break; case Camera::PERSPECTIVE: { camera_matrix.set_perspective( p_camera->fov, viewport_rect.width / (float)viewport_rect.height, p_range_min, p_range_max, p_camera->vaspect ); } break; } //obtain the frustum endpoints Vector<Vector3> endpoints; endpoints.resize(8); bool res = camera_matrix.get_endpoints(p_camera->transform,&endpoints[0]); ERR_FAIL_COND_V(!res,Vector<Vector3>()); return endpoints; } Vector<Plane> VisualServerRaster::_camera_generate_orthogonal_planes(Instance *p_light,Camera *p_camera,float p_range_min, float p_range_max) { Vector<Vector3> endpoints=_camera_generate_endpoints(p_light,p_camera,p_range_min,p_range_max); // frustum plane endpoints ERR_FAIL_COND_V(endpoints.empty(),Vector<Plane>()); // obtain the light frustm ranges (given endpoints) Vector3 x_vec=p_light->data.transform.basis.get_axis( Vector3::AXIS_X ).normalized(); Vector3 y_vec=p_light->data.transform.basis.get_axis( Vector3::AXIS_Y ).normalized(); Vector3 z_vec=p_light->data.transform.basis.get_axis( Vector3::AXIS_Z ).normalized(); float x_min,x_max; float y_min,y_max; float z_min,z_max; for(int j=0;j<8;j++) { float d_x=x_vec.dot(endpoints[j]); float d_y=y_vec.dot(endpoints[j]); float d_z=z_vec.dot(endpoints[j]); if (j==0 || d_x<x_min) x_min=d_x; if (j==0 || d_x>x_max) x_max=d_x; if (j==0 || d_y<y_min) y_min=d_y; if (j==0 || d_y>y_max) y_max=d_y; if (j==0 || d_z<z_min) z_min=d_z; if (j==0 || d_z>z_max) z_max=d_z; } //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree Vector<Plane> light_frustum_planes; light_frustum_planes.resize(6); //right/left light_frustum_planes[0]=Plane( x_vec, x_max ); light_frustum_planes[1]=Plane( -x_vec, -x_min ); //top/bottom light_frustum_planes[2]=Plane( y_vec, y_max ); light_frustum_planes[3]=Plane( -y_vec, -y_min ); //near/far light_frustum_planes[4]=Plane( z_vec, z_max+1e6 ); light_frustum_planes[5]=Plane( -z_vec, -z_min ); // z_min is ok, since casters further than far-light plane are not needed //TODO@ add more actual frustum planes to minimize get return light_frustum_planes; } void VisualServerRaster::_light_instance_update_pssm_shadow(Instance *p_light,Scenario *p_scenario,Camera *p_camera,const CullRange& p_cull_range) { int splits = rasterizer->light_instance_get_shadow_passes( p_light->light_info->instance ); float split_weight=rasterizer->light_directional_get_shadow_param(p_light->base_rid,LIGHT_DIRECTIONAL_SHADOW_PARAM_PSSM_SPLIT_WEIGHT); float distances[5]; float texsize=rasterizer->light_instance_get_shadow_size( p_light->light_info->instance ); // float cull_min=p_cull_range.min; //float cull_max=p_cull_range.max; float cull_min=p_camera->znear; float cull_max=p_camera->zfar; float max_dist = rasterizer->light_directional_get_shadow_param(p_light->base_rid,VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_MAX_DISTANCE); if (max_dist>0.0) cull_max=MIN(cull_max,max_dist); for(int i = 0; i < splits; i++) { float idm = i / (float)splits; float lg = cull_min * Math::pow(cull_max/cull_min, idm); float uniform = cull_min + (cull_max - cull_min) * idm; distances[i] = lg * split_weight + uniform * (1.0 - split_weight); } distances[0]=cull_min; distances[splits]=cull_max; for (int i=0;i<splits;i++) { // setup a camera matrix for that range! CameraMatrix camera_matrix; switch(p_camera->type) { case Camera::ORTHOGONAL: { camera_matrix.set_orthogonal( p_camera->size, viewport_rect.width / (float)viewport_rect.height, distances[i], distances[i+1], p_camera->vaspect ); } break; case Camera::PERSPECTIVE: { camera_matrix.set_perspective( p_camera->fov, viewport_rect.width / (float)viewport_rect.height, distances[i], distances[i+1], p_camera->vaspect ); } break; } //obtain the frustum endpoints Vector3 endpoints[8]; // frustum plane endpoints bool res = camera_matrix.get_endpoints(p_camera->transform,endpoints); ERR_CONTINUE(!res); // obtain the light frustm ranges (given endpoints) Vector3 x_vec=p_light->data.transform.basis.get_axis( Vector3::AXIS_X ).normalized(); Vector3 y_vec=p_light->data.transform.basis.get_axis( Vector3::AXIS_Y ).normalized(); Vector3 z_vec=p_light->data.transform.basis.get_axis( Vector3::AXIS_Z ).normalized(); //z_vec points agsint the camera, like in default opengl float x_min,x_max; float y_min,y_max; float z_min,z_max; float x_min_cam,x_max_cam; float y_min_cam,y_max_cam; float z_min_cam,z_max_cam; //used for culling for(int j=0;j<8;j++) { float d_x=x_vec.dot(endpoints[j]); float d_y=y_vec.dot(endpoints[j]); float d_z=z_vec.dot(endpoints[j]); if (j==0 || d_x<x_min) x_min=d_x; if (j==0 || d_x>x_max) x_max=d_x; if (j==0 || d_y<y_min) y_min=d_y; if (j==0 || d_y>y_max) y_max=d_y; if (j==0 || d_z<z_min) z_min=d_z; if (j==0 || d_z>z_max) z_max=d_z; } { //camera viewport stuff //this trick here is what stabilizes the shadow (make potential jaggies to not move) //at the cost of some wasted resolution. Still the quality increase is very well worth it Vector3 center; for(int j=0;j<8;j++) { center+=endpoints[j]; } center/=8.0; //center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5; float radius=0; for(int j=0;j<8;j++) { float d = center.distance_to(endpoints[j]); if (d>radius) radius=d; } radius *= texsize/(texsize-2.0); //add a texel by each side, so stepified texture will always fit x_max_cam=x_vec.dot(center)+radius; x_min_cam=x_vec.dot(center)-radius; y_max_cam=y_vec.dot(center)+radius; y_min_cam=y_vec.dot(center)-radius; z_max_cam=z_vec.dot(center)+radius; z_min_cam=z_vec.dot(center)-radius; float unit = radius*2.0/texsize; x_max_cam=Math::stepify(x_max_cam,unit); x_min_cam=Math::stepify(x_min_cam,unit); y_max_cam=Math::stepify(y_max_cam,unit); y_min_cam=Math::stepify(y_min_cam,unit); } //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree Vector<Plane> light_frustum_planes; light_frustum_planes.resize(6); //right/left light_frustum_planes[0]=Plane( x_vec, x_max ); light_frustum_planes[1]=Plane( -x_vec, -x_min ); //top/bottom light_frustum_planes[2]=Plane( y_vec, y_max ); light_frustum_planes[3]=Plane( -y_vec, -y_min ); //near/far light_frustum_planes[4]=Plane( z_vec, z_max+1e6 ); light_frustum_planes[5]=Plane( -z_vec, -z_min ); // z_min is ok, since casters further than far-light plane are not needed int caster_cull_count = p_scenario->octree.cull_convex(light_frustum_planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,INSTANCE_GEOMETRY_MASK); // a pre pass will need to be needed to determine the actual z-near to be used for(int j=0;j<caster_cull_count;j++) { float min,max; Instance *ins=instance_shadow_cull_result[j]; if (!ins->visible || !ins->cast_shadows) continue; ins->transformed_aabb.project_range_in_plane(Plane(z_vec,0),min,max); if (max>z_max) z_max=max; } { CameraMatrix ortho_camera; real_t half_x = (x_max_cam-x_min_cam) * 0.5; real_t half_y = (y_max_cam-y_min_cam) * 0.5; ortho_camera.set_orthogonal( -half_x, half_x,-half_y,half_y, 0, (z_max-z_min_cam) ); Transform ortho_transform; ortho_transform.basis=p_light->data.transform.basis; ortho_transform.origin=x_vec*(x_min_cam+half_x)+y_vec*(y_min_cam+half_y)+z_vec*z_max; rasterizer->light_instance_set_shadow_transform(p_light->light_info->instance, i, ortho_camera, ortho_transform,distances[i],distances[i+1] ); } rasterizer->begin_shadow_map( p_light->light_info->instance, i ); for (int j=0;j<caster_cull_count;j++) { Instance *instance = instance_shadow_cull_result[j]; if (!instance->visible || !instance->cast_shadows) continue; _instance_draw(instance); } rasterizer->end_shadow_map(); } } CameraMatrix _lispm_look( const Vector3 pos, const Vector3 dir, const Vector3 up) { Vector3 dirN; Vector3 upN; Vector3 lftN; lftN=dir.cross(up); lftN.normalize(); upN=lftN.cross(dir); upN.normalize(); dirN=dir.normalized(); CameraMatrix cmout; float *output=&cmout.matrix[0][0]; output[ 0] = lftN[0]; output[ 1] = upN[0]; output[ 2] = -dirN[0]; output[ 3] = 0.0; output[ 4] = lftN[1]; output[ 5] = upN[1]; output[ 6] = -dirN[1]; output[ 7] = 0.0; output[ 8] = lftN[2]; output[ 9] = upN[2]; output[10] = -dirN[2]; output[11] = 0.0; output[12] = -lftN.dot(pos); output[13] = -upN.dot(pos); output[14] = dirN.dot(pos); output[15] = 1.0; return cmout; } #if 1 void VisualServerRaster::_light_instance_update_lispsm_shadow(Instance *p_light,Scenario *p_scenario,Camera *p_camera,const CullRange& p_cull_range) { Vector3 light_vec = -p_light->data.transform.basis.get_axis(2); Vector3 view_vec = -p_camera->transform.basis.get_axis(2); float viewdot = light_vec.normalized().dot(view_vec.normalized()); float near_dist=1; Vector<Plane> light_frustum_planes = _camera_generate_orthogonal_planes(p_light,p_camera,p_cull_range.min,p_cull_range.max); int caster_count = p_scenario->octree.cull_convex(light_frustum_planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,INSTANCE_GEOMETRY_MASK); // this could be faster by just getting supports from the AABBs.. // but, safer to do as the original implementation explains for now.. Vector<Vector3> caster_pointcloud; caster_pointcloud.resize(caster_count*8); int caster_pointcloud_size=0; { //fill pointcloud Vector3* caster_pointcloud_ptr=&caster_pointcloud[0]; for(int i=0;i<caster_count;i++) { Instance *ins = instance_shadow_cull_result[i]; if (!ins->visible || !ins->cast_shadows) continue; for(int j=0;j<8;j++) { Vector3 v = ins->aabb.get_endpoint(j); v = ins->data.transform.xform(v); caster_pointcloud_ptr[caster_pointcloud_size+j]=v; } caster_pointcloud_size+=8; } } // now generate a pointcloud that contains the maximum bound (camera extruded by light) Vector<Vector3> camera_pointcloud = _camera_generate_endpoints(p_light,p_camera,p_cull_range.min,p_cull_range.max); int cpcsize=camera_pointcloud.size(); camera_pointcloud.resize( cpcsize*2 ); for(int i=0;i<cpcsize;i++) { camera_pointcloud[i+cpcsize]=camera_pointcloud[i]-light_vec*1000; } // Vector<Vector3> frustum_points=_camera_generate_endpoints(p_light,p_camera,p_cull_range.min,p_cull_range.max); // compute the "light-space" basis, using the algorithm described in the paper // note: since bodyB is defined in eye space, all of these vectors should also be defined in eye space Vector3 eye = p_camera->transform.origin; Vector3 up = light_vec.cross(view_vec).cross(light_vec).normalized(); CameraMatrix light_space_basis = _lispm_look(eye,light_vec,up); AABB light_space_aabb; { //create an optimal AABB from both the camera pointcloud and the objects pointcloud AABB light_space_pointcloud_aabb; AABB light_space_camera_aabb; //xform pointcloud const Vector3* caster_pointcloud_ptr=&caster_pointcloud[0]; for(int i=0;i<caster_pointcloud_size;i++) { Vector3 p = light_space_basis.xform(caster_pointcloud_ptr[i]); if (i==0) { light_space_pointcloud_aabb.pos=p; } else { light_space_pointcloud_aabb.expand_to(p); } } for(int i=0;i<camera_pointcloud.size();i++) { Vector3 p = light_space_basis.xform(camera_pointcloud[i]); if (i==0) { light_space_camera_aabb.pos=p; } else { light_space_camera_aabb.expand_to(p); } } light_space_aabb=light_space_pointcloud_aabb.intersection(light_space_camera_aabb); } float lvdp = light_vec.dot(view_vec); float sin_gamma = Math::sqrt(1.0-lvdp*lvdp); //use the formulas of the paper to get n (and f) float factor = 1.0/sin_gamma; float z_n = factor*near_dist; //often 1 float d = Math::abs(light_space_aabb.size.y); //perspective transform depth //light space y extents float z_f = z_n + d*sin_gamma; float n = (z_n+Math::sqrt(z_f*z_n))/sin_gamma; float f = n+d; Vector3 pos = eye - up*(n-near_dist); CameraMatrix light_space_basis2 = _lispm_look(pos,light_vec,up); //Transform light_space_basis2; //light_space_basis2.set_look_at(pos,light_vec-pos,up); //light_space_basis2.affine_invert(); //one possibility for a simple perspective transformation matrix //with the two parameters n(near) and f(far) in y direction CameraMatrix lisp_matrix; lisp_matrix.matrix[1][1]=(f+n)/(f-n); lisp_matrix.matrix[3][1]=-2*f*n/(f-n); lisp_matrix.matrix[1][3]=1; lisp_matrix.matrix[3][3]=0; CameraMatrix projection = lisp_matrix * light_space_basis2; //CameraMatrix projection = light_space_basis2 * lisp_matrix; AABB proj_space_aabb; float max_d,min_d; { AABB proj_space_pointcloud_aabb; AABB proj_space_camera_aabb; //xform pointcloud Vector3* caster_pointcloud_ptr=&caster_pointcloud[0]; for(int i=0;i<caster_pointcloud_size;i++) { Vector3 p = projection.xform(caster_pointcloud_ptr[i]); if (i==0) { proj_space_pointcloud_aabb.pos=p; } else { proj_space_pointcloud_aabb.expand_to(p); } } for(int i=0;i<camera_pointcloud.size();i++) { Vector3 p = projection.xform(camera_pointcloud[i]); if (i==0) { proj_space_camera_aabb.pos=p; } else { proj_space_camera_aabb.expand_to(p); } } //proj_space_aabb=proj_space_pointcloud_aabb.intersection_with(proj_space_camera_aabb); proj_space_aabb=proj_space_pointcloud_aabb; } projection.scale_translate_to_fit(proj_space_aabb); projection=projection * lisp_matrix; CameraMatrix scale; scale.make_scale(Vector3(1.0,1.0,-1.0)); // transform to left handed projection=scale * projection; rasterizer->light_instance_set_shadow_transform(p_light->light_info->instance,0, projection , light_space_basis2.inverse() ); rasterizer->begin_shadow_map( p_light->light_info->instance, 0 ); for(int i=0;i<caster_count;i++) { Instance *instance = instance_shadow_cull_result[i]; if (!instance->visible || !instance->cast_shadows) continue; _instance_draw(instance); } rasterizer->end_shadow_map(); } #else void VisualServerRaster::_light_instance_update_lispsm_shadow(Instance *p_light,Scenario *p_scenario,Camera *p_camera,const CullRange& p_cull_range) { /* STEP 1: GENERATE LIGHT TRANSFORM */ Vector3 light_vec = -p_light->data.transform.basis.get_axis(2); Vector3 view_vec = -p_camera->transform.basis.get_axis(2); float viewdot = Math::absf(light_vec.dot(view_vec)); Vector3 up = light_vec.cross(view_vec).cross(light_vec).normalized(); Transform light_transform; light_transform.set_look_at(Vector3(),light_vec,up); /* STEP 2: GENERATE WORDLSPACE PLANES AND VECTORS*/ float range_min=0.01; //p_cull_range.min float range_max=20;//p_cull_range.max; Vector<Vector3> camera_endpoints=_camera_generate_endpoints(p_light,p_camera,range_min,range_max); // frustum plane endpoints ERR_FAIL_COND(camera_endpoints.empty()); // obtain the light frustm ranges (given endpoints) Vector3 light_x_vec=light_transform.basis.get_axis( Vector3::AXIS_X ).normalized(); Vector3 light_y_vec=light_transform.basis.get_axis( Vector3::AXIS_Y ).normalized(); Vector3 light_z_vec=light_transform.basis.get_axis( Vector3::AXIS_Z ).normalized(); Vector3 light_axis_max; Vector3 light_axis_min; for(int j=0;j<8;j++) { float d_x=light_x_vec.dot(camera_endpoints[j]); float d_y=light_y_vec.dot(camera_endpoints[j]); float d_z=light_z_vec.dot(camera_endpoints[j]); if (j==0 || d_x<light_axis_min.x) light_axis_min.x=d_x; if (j==0 || d_x>light_axis_max.x) light_axis_max.x=d_x; if (j==0 || d_y<light_axis_min.y) light_axis_min.y=d_y; if (j==0 || d_y>light_axis_max.y) light_axis_max.y=d_y; if (j==0 || d_z<light_axis_min.z) light_axis_min.z=d_z; if (j==0 || d_z>light_axis_max.z) light_axis_max.z=d_z; } //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree Vector<Plane> light_cull_planes; light_cull_planes.resize(6); //right/left light_cull_planes[0]=Plane( light_x_vec, light_axis_max.x ); light_cull_planes[1]=Plane( -light_x_vec, -light_axis_min.x ); //top/bottom light_cull_planes[2]=Plane( light_y_vec, light_axis_max.y ); light_cull_planes[3]=Plane( -light_y_vec, -light_axis_min.y ); //near/far light_cull_planes[4]=Plane( light_z_vec, light_axis_max.z+1e6 ); light_cull_planes[5]=Plane( -light_z_vec, -light_axis_min.z ); // z_min is ok, since casters further than far-light plane are not needed /* STEP 3: CULL CASTERS */ int caster_count = p_scenario->octree.cull_convex(light_cull_planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,INSTANCE_GEOMETRY_MASK); /* STEP 4: ADJUST FAR Z PLANE */ float caster_max_z=1e-1; for(int i=0;i<caster_count;i++) { Instance *ins=instance_shadow_cull_result[i]; if (!ins->visible || !ins->cast_shadows) continue; //@TODO optimize using support mapping for(int j=0;j<8;j++) { Vector3 v=ins->data.transform.xform(ins->aabb.get_endpoint(j)); float d = light_z_vec.dot(v); if (d>caster_max_z) caster_max_z=d; } } float expand = caster_max_z-light_axis_max.z; if (expand<0) expand=0; light_axis_max.z=MAX(caster_max_z,light_axis_max.z); /* STEP 5: CREATE ORTHOGONAL PROJECTION */ CameraMatrix light_projection; real_t half_x = (light_axis_max.x-light_axis_min.x) * 0.5; real_t half_y = (light_axis_max.y-light_axis_min.y) * 0.5; light_projection.set_orthogonal( -half_x, half_x,half_y, -half_y, 0, (light_axis_max.z-light_axis_min.z) ); light_transform.origin=light_x_vec*(light_axis_min.x+half_x)+light_y_vec*(light_axis_min.y+half_y)+light_z_vec*light_axis_max.z; if (/*false &&*/ viewdot<0.96) { float lvdp = light_vec.dot(view_vec); float near_dist=1.0; float sin_gamma = Math::sqrt(1.0-lvdp*lvdp); //use the formulas of the paper to get n (and f) float factor = 1.0/sin_gamma; float z_n = factor*near_dist; //often 1 float d = Math::abs(light_axis_max.y-light_axis_min.y); //perspective transform depth //light space y extents float z_f = z_n + d*sin_gamma; float n = (z_n+Math::sqrt(z_f*z_n))/sin_gamma; float f = n+d; CameraMatrix lisp_matrix; lisp_matrix.matrix[1][1]=(f+n)/(f-n); lisp_matrix.matrix[3][1]=-2*f*n/(f-n); lisp_matrix.matrix[1][3]=1; lisp_matrix.matrix[3][3]=0; Vector3 pos = p_camera->transform.origin - up*(n-near_dist); CameraMatrix world2light = _lispm_look(pos,light_vec,up); CameraMatrix projection = lisp_matrix * world2light; AABB projection_bounds; for(int i=0;i<camera_endpoints.size();i++) { Vector3 p=camera_endpoints[i]; if (i==0) projection_bounds.pos=projection.xform(p); else projection_bounds.expand_to(projection.xform(p)); projection_bounds.expand_to(projection.xform(p+light_vec*-expand)); } CameraMatrix scaletrans; scaletrans.scale_translate_to_fit(projection_bounds); projection=scaletrans * lisp_matrix; CameraMatrix scale; scale.make_scale(Vector3(1.0,1.0,-1.0)); // transform to left handed projection=scale * projection; rasterizer->light_instance_set_shadow_transform(p_light->light_info->instance,0, projection, world2light.inverse(), viewdot); } else { //orthogonal rasterizer->light_instance_set_shadow_transform(p_light->light_info->instance,0, light_projection , light_transform, viewdot); } rasterizer->begin_shadow_map( p_light->light_info->instance, 0 ); for(int i=0;i<caster_count;i++) { Instance *instance = instance_shadow_cull_result[i]; if (!instance->visible || !instance->cast_shadows) continue; _instance_draw(instance); } rasterizer->end_shadow_map(); } #endif void VisualServerRaster::_light_instance_update_shadow(Instance *p_light,Scenario *p_scenario,Camera *p_camera,const CullRange& p_cull_range) { if (!rasterizer->shadow_allocate_near( p_light->light_info->instance )) return; // shadow could not be updated /* VisualServerRaster supports for many shadow techniques, using the one the rasterizer requests */ Rasterizer::ShadowType shadow_type = rasterizer->light_instance_get_shadow_type(p_light->light_info->instance); switch(shadow_type) { case Rasterizer::SHADOW_SIMPLE: { /* SPOT SHADOW */ rasterizer->begin_shadow_map( p_light->light_info->instance, 0 ); //using this one ensures that raster deferred will have it float far = rasterizer->light_get_var( p_light->base_rid, VS::LIGHT_PARAM_RADIUS); float angle = rasterizer->light_get_var( p_light->base_rid, VS::LIGHT_PARAM_SPOT_ANGLE ); CameraMatrix cm; cm.set_perspective( angle*2.0, 1.0, 0.001, far ); Vector<Plane> planes = cm.get_projection_planes(p_light->data.transform); int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,INSTANCE_GEOMETRY_MASK); for (int i=0;i<cull_count;i++) { Instance *instance = instance_shadow_cull_result[i]; if (!instance->visible || !instance->cast_shadows) continue; _instance_draw(instance); } rasterizer->end_shadow_map(); } break; case Rasterizer::SHADOW_DUAL_PARABOLOID: { /* OMNI SHADOW */ int passes = rasterizer->light_instance_get_shadow_passes( p_light->light_info->instance ); if (passes==2) { for(int i=0;i<2;i++) { rasterizer->begin_shadow_map( p_light->light_info->instance, i ); //using this one ensures that raster deferred will have it float radius = rasterizer->light_get_var( p_light->base_rid, VS::LIGHT_PARAM_RADIUS); float z =i==0?-1:1; Vector<Plane> planes; planes.resize(5); planes[0]=p_light->data.transform.xform(Plane(Vector3(0,0,z),radius)); planes[1]=p_light->data.transform.xform(Plane(Vector3(1,0,z).normalized(),radius)); planes[2]=p_light->data.transform.xform(Plane(Vector3(-1,0,z).normalized(),radius)); planes[3]=p_light->data.transform.xform(Plane(Vector3(0,1,z).normalized(),radius)); planes[4]=p_light->data.transform.xform(Plane(Vector3(0,-1,z).normalized(),radius)); int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,INSTANCE_GEOMETRY_MASK); for (int j=0;j<cull_count;j++) { Instance *instance = instance_shadow_cull_result[j]; if (!instance->visible || !instance->cast_shadows) continue; _instance_draw(instance); } rasterizer->end_shadow_map(); } } else if (passes==1) { //one go } } break; case Rasterizer::SHADOW_CUBE: { // todo } break; case Rasterizer::SHADOW_ORTHOGONAL: { _light_instance_update_pssm_shadow(p_light,p_scenario,p_camera,p_cull_range); } break; case Rasterizer::SHADOW_PSSM: { _light_instance_update_pssm_shadow(p_light,p_scenario,p_camera,p_cull_range); } break; case Rasterizer::SHADOW_PSM: { _light_instance_update_lispsm_shadow(p_light,p_scenario,p_camera,p_cull_range); // todo } break; default: {} } } void VisualServerRaster::_portal_disconnect(Instance *p_portal,bool p_cleanup) { if (p_portal->portal_info->connected) { //disconnect first p_portal->portal_info->connected->portal_info->connected=NULL; p_portal->portal_info->connected=NULL; } if (p_portal->room && p_portal->room->room) { if (p_cleanup) { p_portal->room->room->room_info->disconnected_child_portals.erase(p_portal); //p_portal->room->room->room_info->disconnected_child_portals.erase(p_portal); } else { p_portal->room->room->room_info->disconnected_child_portals.insert(p_portal); } } } void VisualServerRaster::_instance_validate_autorooms(Instance *p_geometry) { if (p_geometry->auto_rooms.size()==0) return; p_geometry->valid_auto_rooms.clear(); int point_count = aabb_random_points.size(); const Vector3 * src_points = &aabb_random_points[0]; for(Set<Instance*>::Element *E=p_geometry->valid_auto_rooms.front();E;E=E->next()) { Instance *room = E->get(); Vector3 *dst_points=&transformed_aabb_random_points[0]; //generate points for(int i=0;i<point_count;i++) { dst_points[i] = room->room_info->affine_inverse.xform(p_geometry->data.transform.xform((src_points[i]*p_geometry->transformed_aabb.size)+p_geometry->transformed_aabb.pos)); } int pass = room->room_info->room->bounds.get_points_inside(dst_points,point_count); float ratio = (float)pass / point_count; if (ratio>0.5) // should make some constant p_geometry->valid_auto_rooms.insert(room); } } void VisualServerRaster::_portal_attempt_connect(Instance *p_portal) { _portal_disconnect(p_portal); Vector3 A_norm = p_portal->data.transform.basis.get_axis(Vector3::AXIS_Z).normalized(); Plane A_plane( p_portal->data.transform.origin, A_norm ); float A_surface = p_portal->portal_info->portal->bounds.get_area(); if (A_surface==0) return; //wtf Instance *found=NULL; Transform affine_inverse = p_portal->data.transform.affine_inverse(); for(Set<Instance*>::Element *E=p_portal->portal_info->candidate_set.front();E;E=E->next()) { Instance *B = E->get(); if (B->portal_info->connected) continue; // in use Vector3 B_norm = B->data.transform.basis.get_axis(Vector3::AXIS_Z).normalized(); // check that they are in front of another float dot = A_norm.dot(-B_norm); if (dot<0.707) // 45 degrees, TODO unharcode this continue; // check the max distance to the other portal bool valid=true; Rect2 local_bounds; for(int i=0;i<B->portal_info->portal->shape.size();i++) { Point2 point2 = B->portal_info->portal->shape[i]; Vector3 point = B->data.transform.xform( Vector3( point2.x, point2.y, 0 ) ); float dist = Math::abs(A_plane.distance_to(point)); if ( dist>p_portal->portal_info->portal->connect_range || dist>B->portal_info->portal->connect_range ) { valid=false; break; } Vector3 point_local = affine_inverse.xform(A_plane.project(point)); point2 = Point2(point_local.x,point_local.y); if (i==0) local_bounds.pos=point2; else local_bounds.expand_to(point2); } if (!valid) continue; float B_surface = B->portal_info->portal->bounds.get_area(); if (B_surface==0) continue; //wtf float clip_area = p_portal->portal_info->portal->bounds.clip(local_bounds).get_area(); //check that most of the area is shared if ( (clip_area/A_surface) < 0.5 || (clip_area/B_surface) < 0.5) // TODO change for something else continue; found=B; break; } if (!found) { if (p_portal->room && p_portal->room->room) { p_portal->room->room->room_info->disconnected_child_portals.insert(p_portal); } return; } p_portal->portal_info->connected=found; found->portal_info->connected=p_portal; } void* VisualServerRaster::instance_pair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int) { VisualServerRaster *self = (VisualServerRaster*)p_self; Instance *A = p_A; Instance *B = p_B; if (A->base_type==INSTANCE_PORTAL) { ERR_FAIL_COND_V( B->base_type!=INSTANCE_PORTAL,NULL ); A->portal_info->candidate_set.insert(B); B->portal_info->candidate_set.insert(A); self->_portal_attempt_connect(A); //attempt to conncet portal A (will go through B anyway) //this is a little hackish, but works fine in practice } else if (A->base_type==INSTANCE_ROOM || B->base_type==INSTANCE_ROOM) { if (B->base_type==INSTANCE_ROOM) SWAP(A,B); ERR_FAIL_COND_V(! ((1<<B->base_type)&INSTANCE_GEOMETRY_MASK ),NULL); B->auto_rooms.insert(A); A->room_info->owned_autoroom_geometry.insert(B); self->_instance_validate_autorooms(B); } else { if (B->base_type==INSTANCE_LIGHT) { SWAP(A,B); } else if (A->base_type!=INSTANCE_LIGHT) { return NULL; } A->light_info->affected.insert(B); B->lights.insert(A); B->light_cache_dirty=true; } return NULL; } void VisualServerRaster::instance_unpair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int,void*) { VisualServerRaster *self = (VisualServerRaster*)p_self; Instance *A = p_A; Instance *B = p_B; if (A->base_type==INSTANCE_PORTAL) { ERR_FAIL_COND( B->base_type!=INSTANCE_PORTAL ); A->portal_info->candidate_set.erase(B); B->portal_info->candidate_set.erase(A); //after disconnecting them, see if they can connect again self->_portal_attempt_connect(A); self->_portal_attempt_connect(B); } else if (A->base_type==INSTANCE_ROOM || B->base_type==INSTANCE_ROOM) { if (B->base_type==INSTANCE_ROOM) SWAP(A,B); ERR_FAIL_COND(! ((1<<B->base_type)&INSTANCE_GEOMETRY_MASK )); B->auto_rooms.erase(A); B->valid_auto_rooms.erase(A); A->room_info->owned_autoroom_geometry.erase(B); }else { if (B->base_type==INSTANCE_LIGHT) { SWAP(A,B); } else if (A->base_type!=INSTANCE_LIGHT) { return; } A->light_info->affected.erase(B); B->lights.erase(A); B->light_cache_dirty=true; } } bool VisualServerRaster::_test_portal_cull(Camera *p_camera, Instance *p_from_portal, Instance *p_to_portal) { int src_point_count=p_from_portal->portal_info->transformed_point_cache.size(); int dst_point_count=p_to_portal->portal_info->transformed_point_cache.size(); if (src_point_count<2 || dst_point_count<2) return false; const Vector3 *src_points=&p_from_portal->portal_info->transformed_point_cache[0]; const Vector3 *dst_points=&p_to_portal->portal_info->transformed_point_cache[0]; bool outside=false; bool clockwise = !p_from_portal->portal_info->plane_cache.is_point_over(p_camera->transform.origin); for(int i=0;i<src_point_count;i++) { const Vector3& point_prev = src_points[i?(i-1):(src_point_count-1)]; const Vector3& point = src_points[i]; Plane p = clockwise?Plane(p_camera->transform.origin,point,point_prev):Plane(p_camera->transform.origin,point_prev,point); bool all_over=true; for(int j=0;j<dst_point_count;j++) { if (!p.is_point_over(dst_points[j])) { all_over=false; break; } } if (all_over) { outside=true; break; } } return !outside; } void VisualServerRaster::_cull_portal(Camera *p_camera, Instance *p_portal,Instance *p_from_portal) { ERR_FAIL_COND(!p_portal->scenario); //scenario outside Instance *portal = p_portal; if (!portal->room) { return; //portals need all to belong to a room, it may be unconfigured yet } else if (portal->last_render_pass!=render_pass) { return; //invalid portal, ignore } else if (portal->portal_info->last_visited_pass==render_pass) { return; //portal already visited } else if (portal==p_from_portal) { return; // came from this portal, don't even bother testing } /* TEST DISABLE DISTANCE */ float disable_distance = p_portal->portal_info->portal->disable_distance; if (disable_distance) { //has disable distance.. float distance = p_camera->transform.origin.distance_to(portal->data.transform.origin); if (disable_distance < distance) { return; } } /* TEST PORTAL NOT FACING OPTIMIZATION */ if (p_portal->portal_info->connected) { //connected portal means, it must face against the camera to be seen if (p_portal->portal_info->plane_cache.is_point_over(p_camera->transform.origin)) { //portal facing against camera (exterior) return; } } else { //disconencted portals (go from room to parent room or exterior) must face towards the canera if (!p_portal->portal_info->plane_cache.is_point_over(p_camera->transform.origin)) { //portal facing against camera (exterior) return; } } if (p_from_portal && !_test_portal_cull(p_camera, p_from_portal, portal)) { return; // portal not visible (culled) } portal->portal_info->last_visited_pass=render_pass; if (portal->portal_info->connected) { //interior<->interior portal Instance *to_room = portal->portal_info->connected->room; if (!to_room) { return; //wtf.. oh well, connected to a roomless (invalid) portal } _cull_room(p_camera, to_room, portal->portal_info->connected); } else { //to exterior/to parent roomportal Instance *parent_room = portal->room->room; _cull_room(p_camera, parent_room, portal); } } void VisualServerRaster::_cull_room(Camera *p_camera, Instance *p_room,Instance *p_from_portal) { if (p_room==NULL) { //exterior exterior_visited=true; for(int i=0;i<exterior_portal_cull_count;i++) { _cull_portal(p_camera, exterior_portal_cull_result[i],p_from_portal); } } else { ERR_FAIL_COND(!p_room->scenario); if (p_room->last_render_pass!=render_pass) return; //this room is invalid //interior //first of all, validate the room p_room->room_info->last_visited_pass=render_pass; //see about going around portals if (!p_room->room_info->room->occlude_exterior) exterior_visited=true; for(List<Instance*>::Element * E=p_room->room_info->owned_portal_instances.front();E;E=E->next()) { _cull_portal(p_camera, E->get(),p_from_portal); } for(Set<Instance*>::Element * E=p_room->room_info->disconnected_child_portals.front();E;E=E->next()) { _cull_portal(p_camera, E->get(),p_from_portal); } } } void VisualServerRaster::_render_camera(Viewport *p_viewport,Camera *p_camera, Scenario *p_scenario) { uint64_t t = OS::get_singleton()->get_ticks_usec(); render_pass++; uint32_t camera_layer_mask=p_camera->visible_layers; /* STEP 1 - SETUP CAMERA */ CameraMatrix camera_matrix; switch(p_camera->type) { case Camera::ORTHOGONAL: { camera_matrix.set_orthogonal( p_camera->size, viewport_rect.width / (float)viewport_rect.height, p_camera->znear, p_camera->zfar, p_camera->vaspect ); } break; case Camera::PERSPECTIVE: { camera_matrix.set_perspective( p_camera->fov, viewport_rect.width / (float)viewport_rect.height, p_camera->znear, p_camera->zfar, p_camera->vaspect ); } break; } rasterizer->set_camera(p_camera->transform, camera_matrix); Vector<Plane> planes = camera_matrix.get_projection_planes(p_camera->transform); CullRange cull_range; // cull range is used for PSSM, and having an idea of the rendering depth cull_range.nearp=Plane(p_camera->transform.origin,-p_camera->transform.basis.get_axis(2).normalized()); cull_range.z_near=camera_matrix.get_z_near(); cull_range.z_far=camera_matrix.get_z_far(); cull_range.min=cull_range.z_far; cull_range.max=cull_range.z_near; /* STEP 2 - CULL */ int cull_count = p_scenario->octree.cull_convex(planes,instance_cull_result,MAX_INSTANCE_CULL); light_cull_count=0; /* print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0)); print_line("OTO: "+itos(p_scenario->octree.get_octant_count())); // print_line("OTE: "+itos(p_scenario->octree.get_elem_count())); print_line("OTP: "+itos(p_scenario->octree.get_pair_count())); */ /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */ // compute portals exterior_visited=false; exterior_portal_cull_count=0; if (room_cull_enabled) { for(int i=0;i<cull_count;i++) { Instance *ins = instance_cull_result[i]; ins->last_render_pass=render_pass; if (ins->base_type!=INSTANCE_PORTAL) continue; if (ins->room) continue; ERR_CONTINUE(exterior_portal_cull_count>=MAX_EXTERIOR_PORTALS); exterior_portal_cull_result[exterior_portal_cull_count++]=ins; } room_cull_count = p_scenario->octree.cull_point(p_camera->transform.origin,room_cull_result,MAX_ROOM_CULL,NULL,(1<<INSTANCE_ROOM)|(1<<INSTANCE_PORTAL)); Set<Instance*> current_rooms; Set<Instance*> portal_rooms; //add to set for(int i=0;i<room_cull_count;i++) { if (room_cull_result[i]->base_type==INSTANCE_ROOM) { current_rooms.insert(room_cull_result[i]); } if (room_cull_result[i]->base_type==INSTANCE_PORTAL) { //assume inside that room if also inside the portal.. if (room_cull_result[i]->room) { portal_rooms.insert(room_cull_result[i]->room); } SWAP(room_cull_result[i],room_cull_result[room_cull_count-1]); room_cull_count--; i--; } } //remove from set if it has a parent room or BSP doesn't contain for(int i=0;i<room_cull_count;i++) { Instance *r = room_cull_result[i]; //check inside BSP Vector3 room_local_point = r->room_info->affine_inverse.xform( p_camera->transform.origin ); if (!portal_rooms.has(r) && !r->room_info->room->bounds.point_is_inside(room_local_point)) { current_rooms.erase(r); continue; } //check parent while (r->room) {// has parent room current_rooms.erase(r); r=r->room; } } if (current_rooms.size()) { //camera is inside a room // go through rooms for(Set<Instance*>::Element *E=current_rooms.front();E;E=E->next()) { _cull_room(p_camera,E->get()); } } else { //start from exterior _cull_room(p_camera,NULL); } } /* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */ for(int i=0;i<cull_count;i++) { Instance *ins = instance_cull_result[i]; bool keep=false; if ((camera_layer_mask&ins->layer_mask)==0) { //failure } else if (ins->base_type==INSTANCE_LIGHT) { if (light_cull_count<MAX_LIGHTS_CULLED) { light_cull_result[light_cull_count++]=ins; // rasterizer->light_instance_set_active_hint(ins->light_info->instance); { //compute distance to camera using aabb support Vector3 n = ins->data.transform.basis.xform_inv(cull_range.nearp.normal).normalized(); Vector3 s = ins->data.transform.xform(ins->aabb.get_support(n)); ins->light_info->dtc=cull_range.nearp.distance_to(s); } } } else if ((1<<ins->base_type)&INSTANCE_GEOMETRY_MASK && ins->visible) { bool discarded=false; if (ins->draw_range_end>0) { float d = cull_range.nearp.distance_to(ins->data.transform.origin); if (d<0) d=0; discarded=(d<ins->draw_range_begin || d>=ins->draw_range_end); } if (!discarded) { // test if this geometry should be visible if (room_cull_enabled) { if (ins->visible_in_all_rooms) { keep=true; } else if (ins->room) { if (ins->room->room_info->last_visited_pass==render_pass) keep=true; } else if (ins->auto_rooms.size()) { for(Set<Instance*>::Element *E=ins->auto_rooms.front();E;E=E->next()) { if (E->get()->room_info->last_visited_pass==render_pass) { keep=true; break; } } } else if(exterior_visited) keep=true; } else { keep=true; } } if (keep) { // update cull range float min,max; ins->transformed_aabb.project_range_in_plane(cull_range.nearp,min,max); if (min<cull_range.min) cull_range.min=min; if (max>cull_range.max) cull_range.max=max; } } if (!keep) { // remove, no reason to keep cull_count--; SWAP( instance_cull_result[i], instance_cull_result[ cull_count ] ); i--; ins->last_render_pass=0; // make invalid } else { ins->last_render_pass=render_pass; } } if (cull_range.max > cull_range.z_far ) cull_range.max=cull_range.z_far; if (cull_range.min < cull_range.z_near ) cull_range.min=cull_range.z_near; /* STEP 5 - PROCESS LIGHTS */ rasterizer->shadow_clear_near(); //clear near shadows, will be recreated // directional lights { List<RID>::Element *E=p_scenario->directional_lights.front(); while(E) { Instance *light = E->get().is_valid()?instance_owner.get(E->get()):NULL; if (rasterizer->light_has_shadow(light->base_rid)) { //rasterizer->light_instance_set_active_hint(light->light_info->instance); _light_instance_update_shadow(light,p_scenario,p_camera,cull_range); } E=E->next(); } } //discard lights not affecting anything (useful for deferred rendering, shadowmaps, etc) for (int i=0;i<light_cull_count;i++) { Instance *ins = light_cull_result[i]; if (light_discard_enabled) { //see if the light should be pre discarded because no one is seeing it //this test may seem expensive, but in reality, it shouldn't be //because of early out condition. It will only go through everything //if it's being discarded. bool valid=false; InstanceSet::Element *E =ins->light_info->affected.front(); while(E) { if (E->get()->last_render_pass==render_pass) { valid=true; // early out. break; } E=E->next(); } if (!valid) { light_cull_count--; SWAP( light_cull_result[i], light_cull_result[ light_cull_count ] ); i--; } } } { //assign shadows by distance to camera SortArray<Instance*,_InstanceLightsort> sorter; sorter.sort(light_cull_result,light_cull_count); for (int i=0;i<light_cull_count;i++) { Instance *ins = light_cull_result[i]; if (!rasterizer->light_has_shadow(ins->base_rid) || !shadows_enabled) continue; /* for far shadows? if (ins->version == ins->light_info->last_version && rasterizer->light_instance_has_far_shadow(ins->light_info->instance)) continue; // didn't change */ _light_instance_update_shadow(ins,p_scenario,p_camera,cull_range); ins->light_info->last_version=ins->version; } } /* STEP 6 - PROCESS GEOMETRY AND DRAW SCENE*/ RID environment; if (p_camera->env.is_valid()) //camera has more environment priority environment=p_camera->env; else environment=p_scenario->environment; rasterizer->begin_scene(p_viewport->viewport_data,environment,p_scenario->debug); rasterizer->set_viewport(viewport_rect); // add lights { List<RID>::Element *E=p_scenario->directional_lights.front(); for(;E;E=E->next()) { Instance *light = E->get().is_valid()?instance_owner.get(E->get()):NULL; ERR_CONTINUE(!light); rasterizer->add_light(light->light_info->instance); light->light_info->last_add_pass=render_pass; } for (int i=0;i<light_cull_count;i++) { Instance *ins = light_cull_result[i]; rasterizer->add_light(ins->light_info->instance); ins->light_info->last_add_pass=render_pass; } } // add geometry for(int i=0;i<cull_count;i++) { Instance *ins = instance_cull_result[i]; ERR_CONTINUE(!((1<<ins->base_type)&INSTANCE_GEOMETRY_MASK)); _instance_draw(ins); } rasterizer->end_scene(); } void VisualServerRaster::_render_canvas_item(CanvasItem *p_canvas_item,const Matrix32& p_transform,const Rect2& p_clip_rect, float p_opacity) { CanvasItem *ci = p_canvas_item; if (!ci->visible) return; if (p_opacity<0.007) return; Rect2 rect = ci->get_rect(); Matrix32 xform = p_transform * ci->xform; Rect2 global_rect = xform.xform(rect); global_rect.pos+=p_clip_rect.pos; if (global_rect.intersects(p_clip_rect) && ci->viewport.is_valid() && viewport_owner.owns(ci->viewport)) { Viewport *vp = viewport_owner.get(ci->viewport); Point2i from = xform.get_origin() + Point2(viewport_rect.x,viewport_rect.y); Point2i size = rect.size; size.x *= xform[0].length(); size.y *= xform[1].length(); _draw_viewport(vp, from.x, from.y, size.x, size.y); rasterizer->canvas_begin(); } int s = ci->commands.size(); bool reclip=false; float opacity = ci->opacity * p_opacity; #ifndef ONTOP_DISABLED CanvasItem **child_items = ci->child_items.ptr(); int child_item_count=ci->child_items.size(); int top_item_count=0; CanvasItem **top_items=(CanvasItem**)alloca(child_item_count*sizeof(CanvasItem*)); if (ci->clip) { rasterizer->canvas_set_clip(true,global_rect); canvas_clip=global_rect; } for(int i=0;i<child_item_count;i++) { if (child_items[i]->ontop) top_items[top_item_count++]=child_items[i]; else { _render_canvas_item(child_items[i],xform,p_clip_rect,opacity); } } #endif if (s!=0) { //Rect2 rect( ci->rect.pos + p_ofs, ci->rect.size); if (p_clip_rect.intersects(global_rect)) { rasterizer->canvas_begin_rect(xform); rasterizer->canvas_set_opacity( opacity * ci->self_opacity ); rasterizer->canvas_set_blend_mode( ci->blend_mode ); CanvasItem::Command **commands = &ci->commands[0]; for (int i=0;i<s;i++) { CanvasItem::Command *c=commands[i]; switch(c->type) { case CanvasItem::Command::TYPE_LINE: { CanvasItem::CommandLine* line = static_cast<CanvasItem::CommandLine*>(c); rasterizer->canvas_draw_line(line->from,line->to,line->color,line->width); } break; case CanvasItem::Command::TYPE_RECT: { CanvasItem::CommandRect* rect = static_cast<CanvasItem::CommandRect*>(c); // rasterizer->canvas_draw_rect(rect->rect,rect->region,rect->source,rect->flags&CanvasItem::CommandRect::FLAG_TILE,rect->flags&CanvasItem::CommandRect::FLAG_FLIP_H,rect->flags&CanvasItem::CommandRect::FLAG_FLIP_V,rect->texture,rect->modulate); #if 0 int flags=0; if (rect->flags&CanvasItem::CommandRect::FLAG_REGION) { flags|=Rasterizer::CANVAS_RECT_REGION; } if (rect->flags&CanvasItem::CommandRect::FLAG_TILE) { flags|=Rasterizer::CANVAS_RECT_TILE; } if (rect->flags&CanvasItem::CommandRect::FLAG_FLIP_H) { flags|=Rasterizer::CANVAS_RECT_FLIP_H; } if (rect->flags&CanvasItem::CommandRect::FLAG_FLIP_V) { flags|=Rasterizer::CANVAS_RECT_FLIP_V; } #else int flags=rect->flags; #endif rasterizer->canvas_draw_rect(rect->rect,flags,rect->source,rect->texture,rect->modulate); } break; case CanvasItem::Command::TYPE_STYLE: { CanvasItem::CommandStyle* style = static_cast<CanvasItem::CommandStyle*>(c); rasterizer->canvas_draw_style_box(style->rect,style->texture,style->margin,style->draw_center,style->color); } break; case CanvasItem::Command::TYPE_PRIMITIVE: { CanvasItem::CommandPrimitive* primitive = static_cast<CanvasItem::CommandPrimitive*>(c); rasterizer->canvas_draw_primitive(primitive->points,primitive->colors,primitive->uvs,primitive->texture,primitive->width); } break; case CanvasItem::Command::TYPE_POLYGON: { CanvasItem::CommandPolygon* polygon = static_cast<CanvasItem::CommandPolygon*>(c); rasterizer->canvas_draw_polygon(polygon->count,polygon->indices.ptr(),polygon->points.ptr(),polygon->uvs.ptr(),polygon->colors.ptr(),polygon->texture,polygon->colors.size()==1); } break; case CanvasItem::Command::TYPE_POLYGON_PTR: { CanvasItem::CommandPolygonPtr* polygon = static_cast<CanvasItem::CommandPolygonPtr*>(c); rasterizer->canvas_draw_polygon(polygon->count,polygon->indices,polygon->points,polygon->uvs,polygon->colors,polygon->texture,false); } break; case CanvasItem::Command::TYPE_CIRCLE: { CanvasItem::CommandCircle* circle = static_cast<CanvasItem::CommandCircle*>(c); static const int numpoints=32; Vector2 points[numpoints+1]; points[numpoints]=circle->pos; int indices[numpoints*3]; for(int i=0;i<numpoints;i++) { points[i]=circle->pos+Vector2( Math::sin(i*Math_PI*2.0/numpoints),Math::cos(i*Math_PI*2.0/numpoints) )*circle->radius; indices[i*3+0]=i; indices[i*3+1]=(i+1)%numpoints; indices[i*3+2]=numpoints; } rasterizer->canvas_draw_polygon(numpoints*3,indices,points,NULL,&circle->color,RID(),true); //rasterizer->canvas_draw_circle(circle->indices.size(),circle->indices.ptr(),circle->points.ptr(),circle->uvs.ptr(),circle->colors.ptr(),circle->texture,circle->colors.size()==1); } break; case CanvasItem::Command::TYPE_TRANSFORM: { CanvasItem::CommandTransform* transform = static_cast<CanvasItem::CommandTransform*>(c); rasterizer->canvas_set_transform(transform->xform); } break; case CanvasItem::Command::TYPE_BLEND_MODE: { CanvasItem::CommandBlendMode* bm = static_cast<CanvasItem::CommandBlendMode*>(c); rasterizer->canvas_set_blend_mode(bm->blend_mode); } break; case CanvasItem::Command::TYPE_CLIP_IGNORE: { CanvasItem::CommandClipIgnore* ci = static_cast<CanvasItem::CommandClipIgnore*>(c); if (canvas_clip!=Rect2()) { if (ci->ignore!=reclip) { if (ci->ignore) { rasterizer->canvas_set_clip(false,Rect2()); reclip=true; } else { rasterizer->canvas_set_clip(true,canvas_clip); reclip=false; } } } } break; } } rasterizer->canvas_end_rect(); } } if (reclip) { rasterizer->canvas_set_clip(true,canvas_clip); } #ifndef ONTOP_DISABLED for(int i=0;i<top_item_count;i++) { _render_canvas_item(top_items[i],xform,p_clip_rect,opacity); } #else for(int i=0;i<p_canvas_item->child_items.size();i++) { _render_canvas_item(p_canvas_item->child_items[i],xform,p_clip_rect,opacity); } #endif if (ci->clip) { rasterizer->canvas_set_clip(false,Rect2()); canvas_clip=Rect2(); } } void VisualServerRaster::_render_canvas(Canvas *p_canvas,const Matrix32 &p_transform) { rasterizer->canvas_begin(); int l = p_canvas->child_items.size(); for(int i=0;i<l;i++) { Canvas::ChildItem& ci=p_canvas->child_items[i]; _render_canvas_item(ci.item,p_transform,Rect2(viewport_rect.x,viewport_rect.y,viewport_rect.width,viewport_rect.height),1); //mirroring (useful for scrolling backgrounds) if (ci.mirror.x!=0) { Matrix32 xform2 = p_transform * Matrix32(0,Vector2(ci.mirror.x,0)); _render_canvas_item(ci.item,xform2,Rect2(viewport_rect.x,viewport_rect.y,viewport_rect.width,viewport_rect.height),1); } if (ci.mirror.y!=0) { Matrix32 xform2 = p_transform * Matrix32(0,Vector2(0,ci.mirror.y)); _render_canvas_item(ci.item,xform2,Rect2(viewport_rect.x,viewport_rect.y,viewport_rect.width,viewport_rect.height),1); } if (ci.mirror.y!=0 && ci.mirror.x!=0) { Matrix32 xform2 = p_transform * Matrix32(0,ci.mirror); _render_canvas_item(ci.item,xform2,Rect2(viewport_rect.x,viewport_rect.y,viewport_rect.width,viewport_rect.height),1); } } } void VisualServerRaster::_draw_viewport(Viewport *p_viewport,int p_ofs_x, int p_ofs_y,int p_parent_w,int p_parent_h) { ViewportRect desired_rect=p_viewport->rect; ViewportRect old_rect = viewport_rect; // bool vpchanged=false; // convert default expanding viewports to actual size //if (desired_rect.x==0 && desired_rect.y==0 && desired_rect.width==0 && desired_rect.height==0) { if (p_parent_w != 0 && p_parent_h != 0) { desired_rect.width=p_parent_w; desired_rect.height=p_parent_h; } ERR_FAIL_COND(desired_rect.width<=0 || desired_rect.height<=0); desired_rect.x+=p_ofs_x; desired_rect.y+=p_ofs_y; // if the viewport is different than the actual one, change it if ( p_viewport->render_target.is_valid() || viewport_rect.x != desired_rect.x || viewport_rect.y != desired_rect.y || viewport_rect.width != desired_rect.width || viewport_rect.height != desired_rect.height ) { viewport_rect=desired_rect; rasterizer->set_viewport(viewport_rect); } /* Camera should always be BEFORE any other 3D */ if (!p_viewport->hide_scenario && camera_owner.owns(p_viewport->camera) && scenario_owner.owns(p_viewport->scenario)) { Camera *camera = camera_owner.get( p_viewport->camera ); Scenario *scenario = scenario_owner.get( p_viewport->scenario ); _update_instances(); // check dirty instances before rendering _render_camera(p_viewport, camera,scenario ); } else if (true /*|| !p_viewport->canvas_list.empty()*/){ //clear the viewport black because of no camera? i seriously should.. rasterizer->clear_viewport(clear_color); } if (!p_viewport->hide_canvas) { int i=0; Map<Viewport::CanvasKey,Viewport::CanvasData*> canvas_map; for (Map<RID,Viewport::CanvasData>::Element *E=p_viewport->canvas_map.front();E;E=E->next()) { canvas_map[ Viewport::CanvasKey( E->key(), E->get().layer) ]=&E->get(); } for (Map<Viewport::CanvasKey,Viewport::CanvasData*>::Element *E=canvas_map.front();E;E=E->next()) { // print_line("canvas "+itos(i)+" size: "+itos(I->get()->canvas->child_items.size())); //print_line("GT "+p_viewport->global_transform+". CT: "+E->get()->transform); Matrix32 xform = p_viewport->global_transform * E->get()->transform; _render_canvas( E->get()->canvas,xform ); i++; } } //capture if (p_viewport->queue_capture) { rasterizer->capture_viewport(&p_viewport->capture); } //restore if ( viewport_rect.x != old_rect.x || viewport_rect.y != old_rect.y || viewport_rect.width != old_rect.width || viewport_rect.height != old_rect.height ) { viewport_rect=old_rect; rasterizer->set_viewport(viewport_rect); } } void VisualServerRaster::_draw_viewports() { //draw viewports for render targets List<Viewport*> to_blit; List<Viewport*> to_disable; for(SelfList<Viewport> *E=viewport_update_list.first();E;E=E->next()) { Viewport *vp = E->self(); ERR_CONTINUE(!vp); if ( vp->render_target_update_mode==RENDER_TARGET_UPDATE_WHEN_VISIBLE && !vp->rendered_in_prev_frame && !vp->queue_capture ) { continue; } if (vp->rt_to_screen_rect!=Rect2()) to_blit.push_back(vp); rasterizer->set_render_target(vp->render_target,vp->transparent_bg,vp->render_target_vflip); _draw_viewport(vp,0,0,vp->rect.width,vp->rect.height); if ( (vp->queue_capture && vp->render_target_update_mode==RENDER_TARGET_UPDATE_DISABLED) || vp->render_target_update_mode==RENDER_TARGET_UPDATE_ONCE) { //was only enabled for capture to_disable.push_back(vp); vp->render_target_update_mode=RENDER_TARGET_UPDATE_DISABLED; } } rasterizer->set_render_target(RID()); while(to_disable.size()) { //disable again because it was only for capture viewport_update_list.remove(&to_disable.front()->get()->update_list); to_disable.pop_front(); } //draw RTs directly to screen when requested for (List<Viewport*>::Element *E=to_blit.front();E;E=E->next()) { int window_w = OS::get_singleton()->get_video_mode().width; int window_h = OS::get_singleton()->get_video_mode().height; ViewportRect desired_rect; desired_rect.x = desired_rect.y = 0; desired_rect.width = window_w; desired_rect.height = window_h; if ( viewport_rect.x != desired_rect.x || viewport_rect.y != desired_rect.y || viewport_rect.width != desired_rect.width || viewport_rect.height != desired_rect.height ) { viewport_rect=desired_rect; rasterizer->set_viewport(viewport_rect); } rasterizer->canvas_begin(); rasterizer->canvas_disable_blending(); rasterizer->canvas_begin_rect(Matrix32()); rasterizer->canvas_draw_rect(E->get()->rt_to_screen_rect,0,Rect2(Point2(),E->get()->rt_to_screen_rect.size),E->get()->render_target_texture,Color(1,1,1)); } //draw viewports attached to screen for(Map<RID,int>::Element *E=screen_viewports.front();E;E=E->next()) { Viewport *vp = viewport_owner.get(E->key()); ERR_CONTINUE(!vp); int window_w = OS::get_singleton()->get_video_mode(E->get()).width; int window_h = OS::get_singleton()->get_video_mode(E->get()).height; _draw_viewport(vp,0,0,window_w,window_h); } //check when a viewport associated to a render target was drawn for(SelfList<Viewport> *E=viewport_update_list.first();E;E=E->next()) { Viewport *vp = E->self(); ERR_CONTINUE(!vp); if (vp->render_target_update_mode!=RENDER_TARGET_UPDATE_WHEN_VISIBLE) continue; vp->rendered_in_prev_frame=rasterizer->render_target_renedered_in_frame(vp->render_target); } } void VisualServerRaster::_draw_cursors_and_margins() { int window_w = OS::get_singleton()->get_video_mode().width; int window_h = OS::get_singleton()->get_video_mode().height; ViewportRect desired_rect; desired_rect.x = desired_rect.y = 0; desired_rect.width = window_w; desired_rect.height = window_h; if ( viewport_rect.x != desired_rect.x || viewport_rect.y != desired_rect.y || viewport_rect.width != desired_rect.width || viewport_rect.height != desired_rect.height ) { viewport_rect=desired_rect; rasterizer->set_viewport(viewport_rect); } rasterizer->canvas_begin(); rasterizer->canvas_begin_rect(Matrix32()); for (int i=0; i<MAX_CURSORS; i++) { if (!cursors[i].visible) { continue; }; RID tex = cursors[i].texture?cursors[i].texture:default_cursor_texture; ERR_CONTINUE( !tex ); Point2 size(texture_get_width(tex), texture_get_height(tex)); rasterizer->canvas_draw_rect(Rect2(cursors[i].pos, size), 0, Rect2(), tex, Color(1, 1, 1, 1)); }; if (black_margin[MARGIN_LEFT]) rasterizer->canvas_draw_rect(Rect2(0,0,black_margin[MARGIN_LEFT],window_h),0,Rect2(0,0,1,1),RID(),Color(0,0,0)); if (black_margin[MARGIN_RIGHT]) rasterizer->canvas_draw_rect(Rect2(window_w-black_margin[MARGIN_RIGHT],0,black_margin[MARGIN_RIGHT],window_h),0,Rect2(0,0,1,1),RID(),Color(0,0,0)); if (black_margin[MARGIN_TOP]) rasterizer->canvas_draw_rect(Rect2(0,0,window_w,black_margin[MARGIN_TOP]),0,Rect2(0,0,1,1),RID(),Color(0,0,0)); if (black_margin[MARGIN_BOTTOM]) rasterizer->canvas_draw_rect(Rect2(0,window_h-black_margin[MARGIN_BOTTOM],window_w,black_margin[MARGIN_BOTTOM]),0,Rect2(0,0,1,1),RID(),Color(0,0,0)); rasterizer->canvas_end_rect(); }; void VisualServerRaster::flush() { //do none } void VisualServerRaster::draw() { //if (changes) // print_line("changes: "+itos(changes)); changes=0; shadows_enabled=GLOBAL_DEF("render/shadows_enabled",true); room_cull_enabled = GLOBAL_DEF("render/room_cull_enabled",true); light_discard_enabled = GLOBAL_DEF("render/light_discard_enabled",true); rasterizer->begin_frame(); _draw_viewports(); _draw_cursors_and_margins(); rasterizer->end_frame(); draw_extra_frame=rasterizer->needs_to_draw_next_frame(); } bool VisualServerRaster::has_changed() const { return changes>0 || draw_extra_frame; } int VisualServerRaster::get_render_info(RenderInfo p_info) { return rasterizer->get_render_info(p_info); } bool VisualServerRaster::has_feature(Features p_feature) const { return rasterizer->has_feature(p_feature); // lies for now } void VisualServerRaster::set_default_clear_color(const Color& p_color) { clear_color=p_color; } void VisualServerRaster::set_boot_image(const Image& p_image, const Color& p_color) { if (p_image.empty()) return; rasterizer->begin_frame(); int window_w = OS::get_singleton()->get_video_mode(0).width; int window_h = OS::get_singleton()->get_video_mode(0).height; ViewportRect vr; vr.x=0; vr.y=0; vr.width=OS::get_singleton()->get_video_mode(0).width; vr.height=OS::get_singleton()->get_video_mode(0).height; rasterizer->set_viewport(vr); rasterizer->clear_viewport(p_color); rasterizer->canvas_begin(); RID texture = texture_create(); texture_allocate(texture,p_image.get_width(),p_image.get_height(),p_image.get_format(),TEXTURE_FLAG_FILTER); texture_set_data(texture,p_image); rasterizer->canvas_begin_rect(Matrix32()); Rect2 imgrect(0,0,p_image.get_width(),p_image.get_height()); Rect2 screenrect=imgrect; screenrect.pos+=((Size2(vr.width,vr.height)-screenrect.size)/2.0).floor(); rasterizer->canvas_draw_rect(screenrect,0,imgrect,texture,Color(1,1,1,0)); rasterizer->canvas_draw_rect(screenrect,0,imgrect,texture,Color(1,1,1,1)); rasterizer->canvas_end_rect(); rasterizer->end_frame(); rasterizer->flush_frame(); free(texture); // free since it's only one frame that stays there } void VisualServerRaster::init() { rasterizer->init(); shadows_enabled=GLOBAL_DEF("render/shadows_enabled",true); //default_scenario = scenario_create(); //default_viewport = viewport_create(); for(int i=0;i<4;i++) black_margin[i]=0; Image img; img.create(default_mouse_cursor_xpm); //img.convert(Image::FORMAT_RGB); default_cursor_texture = texture_create_from_image(img, 0); aabb_random_points.resize( GLOBAL_DEF("render/aabb_random_points",16) ); for(int i=0;i<aabb_random_points.size();i++) aabb_random_points[i]=Vector3(Math::random(0,1),Math::random(0,1),Math::random(0,1)); transformed_aabb_random_points.resize(aabb_random_points.size()); changes=0; } void VisualServerRaster::_clean_up_owner(RID_OwnerBase *p_owner,String p_type) { List<RID> rids; p_owner->get_owned_list(&rids); int lost=0; for(List<RID>::Element *I=rids.front();I;I=I->next()) { if (OS::get_singleton()->is_stdout_verbose()) { lost++; } free(I->get()); } if (lost) print_line("VisualServerRaster: WARNING: Lost "+itos(lost)+" RIDs of type "+p_type); } void VisualServerRaster::finish() { free(default_cursor_texture); _clean_up_owner( &room_owner,"Room" ); _clean_up_owner( &portal_owner,"Portal" ); _clean_up_owner( &camera_owner,"Camera" ); _clean_up_owner( &viewport_owner,"Viewport" ); _clean_up_owner( &scenario_owner,"Scenario" ); _clean_up_owner( &instance_owner,"Instance" ); _clean_up_owner( &canvas_owner,"Canvas" ); _clean_up_owner( &canvas_item_owner,"CanvasItem" ); rasterizer->finish(); octree_allocator.clear(); if (instance_dependency_map.size()) { print_line("base resources missing "+itos(instance_dependency_map.size())); } ERR_FAIL_COND( instance_dependency_map.size() ); } RID VisualServerRaster::get_test_cube() { if (test_cube.is_valid()) return test_cube; test_cube=_make_test_cube(); return test_cube; } VisualServerRaster::VisualServerRaster(Rasterizer *p_rasterizer) { rasterizer=p_rasterizer; instance_update_list=NULL; render_pass=0; clear_color=Color(0.3,0.3,0.3,1.0); OctreeAllocator::allocator=&octree_allocator; draw_extra_frame=false; } VisualServerRaster::~VisualServerRaster() { }
[ "reduzio@gmail.com" ]
reduzio@gmail.com
a101d550f4a8cfac8ea020486819f319e60609a2
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/chrome/browser/plugins/plugin_observer.h
110f777ffff52dc5ccb61d0f8e246757be1a2a41
[ "BSD-3-Clause" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
2,654
h
// Copyright (c) 2012 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. #ifndef CHROME_BROWSER_PLUGINS_PLUGIN_OBSERVER_H_ #define CHROME_BROWSER_PLUGINS_PLUGIN_OBSERVER_H_ #include <memory> #include <string> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/component_updater/component_updater_service.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #if defined(ENABLE_PLUGIN_INSTALLATION) #include <map> #endif class GURL; class PluginFinder; class PluginMetadata; #if defined(ENABLE_PLUGIN_INSTALLATION) class PluginInstaller; class PluginPlaceholderHost; #endif namespace content { class WebContents; } namespace infobars { class InfoBarDelegate; } class PluginObserver : public content::WebContentsObserver, public content::WebContentsUserData<PluginObserver> { public: ~PluginObserver() override; // content::WebContentsObserver implementation. void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) override; bool OnMessageReceived(const IPC::Message& message, content::RenderFrameHost* render_frame_host) override; private: class ComponentObserver; explicit PluginObserver(content::WebContents* web_contents); friend class content::WebContentsUserData<PluginObserver>; class PluginPlaceholderHost; // Message handlers: void OnBlockedUnauthorizedPlugin(const base::string16& name, const std::string& identifier); void OnBlockedOutdatedPlugin(int placeholder_id, const std::string& identifier); void OnBlockedComponentUpdatedPlugin(int placeholder_id, const std::string& identifier); #if defined(ENABLE_PLUGIN_INSTALLATION) void OnRemovePluginPlaceholderHost(int placeholder_id); #endif void RemoveComponentObserver(int placeholder_id); void OnOpenAboutPlugins(); void OnCouldNotLoadPlugin(const base::FilePath& plugin_path); #if defined(ENABLE_PLUGIN_INSTALLATION) // Stores all PluginPlaceholderHosts, keyed by their routing ID. std::map<int, PluginPlaceholderHost*> plugin_placeholders_; #endif // Stores all ComponentObservers, keyed by their routing ID. std::map<int, std::unique_ptr<ComponentObserver>> component_observers_; base::WeakPtrFactory<PluginObserver> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(PluginObserver); }; #endif // CHROME_BROWSER_PLUGINS_PLUGIN_OBSERVER_H_
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
dc82b5eacce5d4c3eacb2703360906230fdc8f8c
e53c5c14357ed2ccc1403a80181325f15f8ddee4
/Canvas/Src/AiBots/Core/Math/Transformations.h
540c77c93bd6c8cab84e99a4a7c31ac7fc0cc512
[]
no_license
XoDeR/2DVectorRenderingAndGui
13820817c2dd3456f992eee08edcfd88be2b5208
5a6e9629cb05c5145883b5a3c21e4fdebbae74ab
refs/heads/master
2020-12-25T14:38:15.558279
2016-08-28T13:12:48
2016-08-28T13:12:48
66,783,536
0
0
null
null
null
null
UTF-8
C++
false
false
5,376
h
#pragma once #include <vector> #include "Vector2.h" #include "Core/Math/Matrix3x3.h" #include "Transformations.h" // TODO remake to TransformSystem //------------------------------------------------------------------------ // Functions for converting 2D vectors between World and Local space. //------------------------------------------------------------------------ // given a std::vector of 2D vectors, a position, orientation and scale, // this function transforms the 2D vectors into the object's world space inline std::vector<Vector2> getWorldTransform(std::vector<Vector2>& points, const Vector2& pos, const Vector2& forward, const Vector2& side, const Vector2& scale) { // copy the original vertices into the buffer about to be transformed std::vector<Vector2> TranVector2Ds = points; // create a transformation matrix Matrix3x3 matTransform; // scale if ((scale.x != 1.0) || (scale.y != 1.0)) { matTransform.scaleMatrix(scale.x, scale.y); } // rotate matTransform.rotate(forward, side); // and translate matTransform.translate(pos.x, pos.y); // now transform the object's vertices matTransform.applyTransformationMatrix(TranVector2Ds); return TranVector2Ds; } // given a std::vector of 2D vectors, a position and orientation // this function transforms the 2D vectors into the object's world space inline std::vector<Vector2> getWorldTransform(std::vector<Vector2>& points, const Vector2& pos, const Vector2& forward, const Vector2& side) { // copy the original vertices into the buffer about to be transformed std::vector<Vector2> TranVector2Ds = points; // create a transformation matrix Matrix3x3 matTransform; // rotate matTransform.rotate(forward, side); // and translate matTransform.translate(pos.x, pos.y); // now transform the object's vertices matTransform.applyTransformationMatrix(TranVector2Ds); return TranVector2Ds; } // Transforms a point from the agent's local space into world space inline Vector2 getTransformedFromLocalSpaceToWorldSpace(const Vector2& point, const Vector2& AgentHeading, const Vector2& AgentSide, const Vector2& AgentPosition) { // make a copy of the point Vector2 TransPoint = point; // create a transformation matrix Matrix3x3 matTransform; // rotate matTransform.rotate(AgentHeading, AgentSide); // and translate matTransform.translate(AgentPosition.x, AgentPosition.y); // now transform the vertices matTransform.applyTransformationMatrix(TransPoint); return TransPoint; } // Transforms a vector from the agent's local space into world space inline Vector2 VectorToWorldSpace(const Vector2& vec, const Vector2& AgentHeading, const Vector2& AgentSide) { // make a copy of the point Vector2 TransVec = vec; // create a transformation matrix Matrix3x3 matTransform; // rotate matTransform.rotate(AgentHeading, AgentSide); // now transform the vertices matTransform.applyTransformationMatrix(TransVec); return TransVec; } inline Vector2 getTransformedPointToLocalSpace(const Vector2& point, Vector2& AgentHeading, Vector2& AgentSide, Vector2& AgentPosition) { // make a copy of the point Vector2 TransPoint = point; // create a transformation matrix Matrix3x3 matTransform; double Tx = -AgentPosition.dot(AgentHeading); double Ty = -AgentPosition.dot(AgentSide); // create the transformation matrix matTransform._11(AgentHeading.x); matTransform._12(AgentSide.x); matTransform._21(AgentHeading.y); matTransform._22(AgentSide.y); matTransform._31(Tx); matTransform._32(Ty); // now transform the vertices matTransform.applyTransformationMatrix(TransPoint); return TransPoint; } inline Vector2 VectorToLocalSpace(const Vector2 &vec, const Vector2& AgentHeading, const Vector2& AgentSide) { // make a copy of the point Vector2 TransPoint = vec; // create a transformation matrix Matrix3x3 matTransform; // create the transformation matrix matTransform._11(AgentHeading.x); matTransform._12(AgentSide.x); matTransform._21(AgentHeading.y); matTransform._22(AgentSide.y); // now transform the vertices matTransform.applyTransformationMatrix(TransPoint); return TransPoint; } // rotates 2D vector angle rads around the origin inline void rotateVector2DAroundOrigin(Vector2& v, double angle) { // create a transformation matrix Matrix3x3 mat; // rotate mat.rotate(angle); // now transform the object's vertices mat.applyTransformationMatrix(v); } // given an origin, a facing direction, a 'field of view' describing the // limit of the outer whiskers, a whisker length and the number of whiskers // this method returns a vector containing the end positions of a series // of whiskers radiating away from the origin and with equal distance between // them. (like the spokes of a wheel clipped to a specific segment size) inline std::vector<Vector2> createWhiskers(unsigned int NumWhiskers, double WhiskerLength, double fov, Vector2 facing, Vector2 origin) { //this is the magnitude of the angle separating each whisker double SectorSize = fov / (double)(NumWhiskers - 1); std::vector<Vector2> whiskers; Vector2 temp; double angle = -fov*0.5; for (unsigned int w = 0; w < NumWhiskers; ++w) { // create the whisker extending outwards at this angle temp = facing; rotateVector2DAroundOrigin(temp, angle); whiskers.push_back(origin + WhiskerLength * temp); angle += SectorSize; } return whiskers; }
[ "xoder.vs@gmail.com" ]
xoder.vs@gmail.com
785bdf0998459315fab11dfcb5dbca8473756216
995310a5ed19946037e928f9a85bae908694c8fe
/src/eloquent/vision/camera/esp32/eye/gray/vga.h
77b0052ec0851bbd696712bf75acc8cbb2d17ea0
[]
no_license
eloquentarduino/EloquentArduino
bca073e19af3e9cc5c7f135719cd026631277744
15983e68cf82c54afadaf2b6c8fdc95cad268489
refs/heads/master
2022-08-26T07:07:02.235025
2022-08-21T12:24:04
2022-08-21T12:24:04
227,818,265
162
57
null
2021-01-07T18:33:09
2019-12-13T10:49:33
C++
UTF-8
C++
false
false
1,356
h
// // Created by Simone on 31/03/2022. // #pragma once #include "../../../../../macros.h" #include "../../../../image/gray/vga.h" #include "../../pins/eye.h" #include "../../BaseEsp32Camera.h" namespace Eloquent { namespace Vision { namespace Cam { namespace Esp32 { /** * M5 wide * Grayscale * VGA */ class Camera : public BaseEsp32Camera { public: Eloquent::Vision::Image::Gray::Vga image; /** * * @return */ framesize_t getFrameSize() { return FRAMESIZE_VGA; } /** * * @return */ pixformat_t getPixFormat() { return PIXFORMAT_GRAYSCALE; } /** * * @param buffer */ void setFrameBuffer(uint8_t *buffer) { image.refresh(buffer); } }; } } } } ELOQUENT_SINGLETON(Eloquent::Vision::Cam::Esp32::Camera camera);
[ "eloquentarduino@gmail.com" ]
eloquentarduino@gmail.com
a679acb7e786b37ccff6d3316674be93bf08967d
75e45b0fd5682580cf5c0c0a97f90c7dafc58955
/PA7/src/bmploader.cpp
5e098c2c9f08008dace9ab4175bb86cf5bfb19d0
[]
no_license
seanpatrickmcdonald/cs480McDonald
604498ee74e017d61081705a25cab937fa2c9992
21bfe90081252fa89652bafc019d9060e801c8d5
refs/heads/master
2021-03-30T12:37:57.195732
2017-12-18T17:41:11
2017-12-18T17:41:11
101,669,156
0
0
null
null
null
null
UTF-8
C++
false
false
1,377
cpp
#include "bmploader.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" BMPLoader::BMPLoader() { } BMPLoader::~BMPLoader() { delete[] data; } int BMPLoader::loadFromFile(std::string filename) { /* std::fstream filestream; filestream.open(filename, std::ios::in); if(!filestream) { std::cout << "Invalid BMP: " << filename << std::endl; return -1; } filestream.get(header, 54); if (header[0] != 'B' || header[1] != 'M') { std::cout << "Invalid BMP:" << filename << std::endl; return -1; } dataPos = *(int*)&(header[0x0A]); imageSize = *(int*)&(header[0x22]); width = *(int*)&(header[0x12]); height = *(int*)&(header[0x16]); data = new unsigned char[imageSize]; for (unsigned int i = 0; i < imageSize; i++) { data[i] = filestream.get(); } */ int x, y, n; stbi_set_flip_vertically_on_load(true); data = stbi_load(filename.c_str(), &x, &y, &n, 3); width = x; height = y; /* if (!data) { std::cout << "failed to load: " << filename << " - Loading with bmploader..." << std::endl; data = new unsigned char[imageSize]; for (unsigned int i = 0; i < imageSize; i++) { data[i] = filestream.get(); } } filestream.close(); */ return true; }
[ "spmcdonald@nevada.unr.edu" ]
spmcdonald@nevada.unr.edu
db06fe80c34dbd10473693540fc57594074735d2
c7dd979ff5cdb4f3c47dab7db4a3d28ebc60bf9e
/src/Trainers/TrainerFactory.cpp
f263aea5914029c5e6dad33da68a520d2c236ed5
[]
no_license
chenghuige/melt-train
5a8dfd76f314487ac6f9b59e35ded5874c89221d
0968d6b43687019200f9113c4e9d44c10758f203
refs/heads/master
2021-01-20T01:53:36.762274
2016-11-08T15:36:53
2016-11-08T15:36:53
101,304,288
2
1
null
null
null
null
GB18030
C++
false
false
6,411
cpp
#include "MLCore/TrainerFactory.h" #include "Trainers/SVM/BaseLineLinearSVM.h" #include "Trainers/SVM/LinearSVM.h" #include "Trainers/Gbdt/BinaryClassificationGbdt.h" #include "Trainers/RandomTrainer.h" #ifdef MELT_USE_THIRD_PARTY #include "Trainers/VWTrainer.h" #include "Trainers/SofiaTrainer.h" #include "Trainers/LibLinearTrainer.h" #include "Trainers/LibSVMTrainer.h" #endif // MELT_USE_THIRD_PARTY #include "Trainers/EnsembleTrainer.h" #include "Trainers/Gbdt/RegressionGbdt.h" #include "Trainers/Gbdt/RankingGbdt.h" namespace gezi { namespace { enum class TrainerType { Unknown, //----------------------Binary Classification Random, LinearSVM, BaseLineLinearSVM, GbdtBinaryClassification, LogisticRegression, RandomForest, DecisionTree, KernalSVM, BinaryNeuralNetwork, VW, Sofia, LibLinear, LibSVM, Ensemble, //----------------------Regression GbdtRegression, //----------------------Ranking GbdtRank, //@TODO provid LambdaRank? }; //TrainerFactory的另外一种设计方式是每个Trainer自己处理 而不是统一放到这个cpp, 这样这里不需要应用这么多.h 利用类似REGISTER(NAME,TYPE)的方式, //存储到map<string,TrainerPtr>中 map是个好东西 //http://stackoverflow.com/questions/4357500/c-abstract-factory-using-templates //https://gist.github.com/pkrusche/5501253 //http://www.mass-communicating.com/code/2013/05/01/generic_factories_cpp.html //这样每个Trainer需要一个.cpp来 register 如果编译的时候去掉这个cpp 那么 就等于没有注册 但是这样一种类型的Trainer只能有一个实例? //这个模式可以进一步泛化 使用模板类统一表述 map<string, TrainerType> _trainerTypes { //----------------------Binary Classification { "random", TrainerType::Random }, { "baselinelinearsvm", TrainerType::BaseLineLinearSVM }, { "baselinesvm", TrainerType::BaseLineLinearSVM }, { "linearsvm", TrainerType::LinearSVM }, { "svm", TrainerType::LinearSVM }, { "gbdt", TrainerType::GbdtBinaryClassification }, { "gb", TrainerType::GbdtBinaryClassification }, { "fr", TrainerType::GbdtBinaryClassification }, { "vw", TrainerType::VW }, { "sofia", TrainerType::Sofia }, { "liblinear", TrainerType::LibLinear }, { "libsvm", TrainerType::LibSVM }, { "ensemble", TrainerType::Ensemble }, //----------------------Regression { "gbdtregression", TrainerType::GbdtRegression }, { "gbregression", TrainerType::GbdtRegression }, { "gbrt", TrainerType::GbdtRegression }, //-----------------------Rank { "lambdamart", TrainerType::GbdtRank }, { "gbdtrank", TrainerType::GbdtRank }, { "gbrank", TrainerType::GbdtRank }, //注意当前只实现lambdaMart,gbrank代表gbdtrank也指向lambdaMart }; } //------------- anoymous namespace void TrainerFactory::PrintTrainersInfo() { VLOG(0) << "---BinaryClassification Trainers"; VLOG(0) << "[LinearSVM] -cl linearsvm or svm | ./melt -helpmatch LinearSVM.cpp"; VLOG(0) << "super fast, for classification with large number of features like text classification"; VLOG(0) << "[Gbdt] -cl fastrank or fr or gbdt | ./melt -helpmatch Gbdt.cpp"; VLOG(0) << "fast, best auc result for most classification problems with num features < 10^5"; VLOG(0) << "For per trainer parameters use, like LinearSVM just <./melt -helpmatch LinearSVM.cpp>, for other common parameters <./melt -helpmatch Melt>"; VLOG(0) << "The default trainer is LinearSVM, if use other trainers use -cl, eg. <./melt feature.txt -c train -cl gbdt> will train feature.txt using gbdt trainer"; VLOG(0) << "---Regression Trainers"; VLOG(0) << "[Gbdt] -cl gbdtRegression or fastrankRegression or frr or gbrt| ./melt -helpmatch Gbdt.cpp"; VLOG(0) << "---Ranking Trainers"; VLOG(0) << "[GBDT/lambdaMart] -cl gbrank or gbdtrank or lambdamart| ./melt -helpmatch Gbdt.cpp"; print_enum_map(_trainerTypes); } TrainerPtr TrainerFactory::CreateTrainer(string name) { name = gezi::arg(name); TrainerType trainerType = _trainerTypes[name]; //----------------------Binary Classification switch (trainerType) { case TrainerType::Unknown: break; case TrainerType::Random: VLOG(0) << "Creating Random trainer, just for test auc will be around 0.5"; return make_shared<RandomTrainer>(); break; case TrainerType::BaseLineLinearSVM: VLOG(0) << "Creating BaselineLinearSVM trainer, this one is slow, try use LinearSVM"; return make_shared<BaseLineLinearSVM>(); break; case TrainerType::LinearSVM: VLOG(0) << "Creating LinearSVM trainer"; return make_shared<LinearSVM>(); break; case TrainerType::GbdtBinaryClassification: VLOG(0) << "Creating Gbdt trainer"; return make_shared<BinaryClassificationGbdt>(); break; case TrainerType::KernalSVM: VLOG(0) << "Creating KernalSVM trainer"; break; case TrainerType::DecisionTree: VLOG(0) << "Creating DecisionTree trainer"; break; case TrainerType::RandomForest: VLOG(0) << "Creating RandomForest trainer"; break; case TrainerType::LogisticRegression: VLOG(0) << "Creating LogisticRegression trainer"; break; case TrainerType::BinaryNeuralNetwork: VLOG(0) << "Creating BinaryNeuralNetwork trainer"; break; #ifdef MELT_USE_THIRD_PARTY case TrainerType::VW: VLOG(0) << "Creating VW trainer"; return make_shared<VWTrainer>(); break; case TrainerType::Sofia: VLOG(0) << "Creating Sofia trainer"; return make_shared<SofiaTrainer>(); break; case TrainerType::LibLinear: VLOG(0) << "Creating LibLinear trainer"; return make_shared<LibLinearTrainer>(); break; case TrainerType::LibSVM: VLOG(0) << "Creating LibSVM trainer"; return make_shared<LibSVMTrainer>(); break; #endif // MELT_USE_THIRD_PARTY case TrainerType::Ensemble: VLOG(0) << "Creating ensemble trainer"; return make_shared<EnsembleTrainer>(); break; //----------------------Regression case TrainerType::GbdtRegression: VLOG(0) << "Creating Gbdt trainer for regression"; return make_shared<RegressionGbdt>(); break; case TrainerType::GbdtRank: VLOG(0) << "Creating Gbdt(lambdaMart) trainer for rank"; return make_shared<RankingGbdt>(); break; default: break; } LOG(FATAL) << name << " is not supported now"; return nullptr; //will not come to here } } //----end of namespace gezi
[ "chenghuige@c4ccc3fd-b13d-49bf-a705-f618d8f4424a" ]
chenghuige@c4ccc3fd-b13d-49bf-a705-f618d8f4424a
ba8e139ec307f0e09fbcdf366134015b2330c024
74ceb9e2ceb3e08faec83198a4e0f526246b780c
/src/cvblobs2/BlobOperators.cpp
6fb2ae647edfb42495ae87c0781527810f645555
[ "MIT" ]
permissive
nmaludy/cvblobslib
8695d4ad3db60369a8657f0655ad33b0cf0850d3
44734f515ba40ee61bab98598c2d88c8de440846
refs/heads/master
2016-09-06T01:31:21.443899
2014-03-16T20:57:47
2014-03-16T20:57:47
15,518,504
0
1
null
null
null
null
ISO-8859-10
C++
false
false
20,641
cpp
/** * @author Ricard Borrās * @author Nick Maludy <nmaludy@gmail.com> * @date 03/15/2014 */ #include <cvblobs2/BlobOperators.h> // std #include <limits> // opencv #include <opencv2/imgproc/imgproc.hpp> // cvblobs #include <cvblobs2/Blob.h> #include <cvblobs2/BlobContour.h> CVBLOBS_BEGIN_NAMESPACE ////////////////// // BlobOperator // ////////////////// BlobOperator::~BlobOperator() {} double BlobOperator::result(cv::Ptr<Blob> pBlob) { double result; // verify if operator is calculated Blob::PropertiesType* p_props = pBlob->properties(); Blob::PropertiesType::iterator iter = p_props->find(name()); if (iter == p_props->end()) { // if not calculate it and add it to blob properties result = operator()(pBlob); (*p_props)[name()] = result; } else { // if is calculate, get result (without calculating it again) result = iter->second; } return result; } BlobOperator::operator BlobOperator*() { return (BlobOperator*)this; } /////////////// // BlobGetId // /////////////// double BlobGetID::operator()(cv::Ptr<Blob> pBlob) { return pBlob->id(); } std::string BlobGetID::name() { return "BlobGetID"; } ///////////////// // BlobGetArea // ///////////////// double BlobGetArea::operator()(cv::Ptr<Blob> pBlob) { return pBlob->area(); } std::string BlobGetArea::name() { return "BlobGetArea"; } ////////////////////// // BlobGetPerimeter // ////////////////////// double BlobGetPerimeter::operator()(cv::Ptr<Blob> pBlob) { return pBlob->perimeter(); } std::string BlobGetPerimeter::name() { return "BlobGetPerimeter"; } ///////////////////// // BlobGetExterior // ///////////////////// BlobGetExterior::BlobGetExterior() : mMask(), mbXBorderLeft(false), mbXBorderRight(false), mbYBorderTop(false), mbYBorderBottom(false) {} BlobGetExterior::BlobGetExterior(cv::Mat& mask, bool bXBorderLeft, bool bXBorderRight, bool bYBorderTop, bool bYBorderBottom) : mMask(mask), mbXBorderLeft(bXBorderLeft), mbXBorderRight(bXBorderRight), mbYBorderTop(bYBorderTop), mbYBorderBottom(bYBorderBottom) {} double BlobGetExterior::operator()(cv::Ptr<Blob> pBlob) { return pBlob->exterior(mMask, mbXBorderLeft, mbXBorderRight, mbYBorderTop, mbYBorderBottom); } ///////////////// // BlobGetMean // ///////////////// BlobGetMean::BlobGetMean() : mImage() {} BlobGetMean::BlobGetMean(cv::Mat& image) : mImage(image) {} double BlobGetMean::operator()(cv::Ptr<Blob> pBlob) { return pBlob->mean(mImage); } /////////////////// // BlobGetStdDev // /////////////////// BlobGetStdDev::BlobGetStdDev() : mImage() {} BlobGetStdDev::BlobGetStdDev(cv::Mat& image) : mImage(image) {} double BlobGetStdDev::operator()(cv::Ptr<Blob> pBlob) { return pBlob->stdDev(mImage); } ////////////////////////// // BlobGetReferenceMean // ////////////////////////// BlobGetReferencedMean::BlobGetReferencedMean() : mImage(), mReference(0.0) {} BlobGetReferencedMean::BlobGetReferencedMean(cv::Mat& image, double reference) : mImage(image), mReference(reference) {} double BlobGetReferencedMean::operator()(cv::Ptr<Blob> pBlob) { return mReference - pBlob->mean(mImage); } std::string BlobGetReferencedMean::name() { return "BlobGetReferencedMean"; } //////////////////////// // BlobGetCompactness // //////////////////////// double BlobGetCompactness::operator()(cv::Ptr<Blob> pBlob) { double area = pBlob->area(); if (area != 0.0) { return pow(pBlob->perimeter(), 2.0) / (4.0 * CV_PI * area); } else { return 0.0; } } /////////////////// // BlobGetLength // /////////////////// double BlobGetLength::operator()(cv::Ptr<Blob> pBlob) { // @todo refactor common length and width computation double area = pBlob->area(); double perimeter = pBlob->perimeter(); // @todo where does this function come from double tmp = (perimeter * perimeter) - (16.0 * area); double width = 0.0; if (tmp > 0.0) { width = (perimeter + sqrt(tmp)) / 4.0; // @todo what does he mean by this? // error intrínsec en els cālculs de l'ārea i el perímetre // Translates to: // intrinsic error in calculating the area and perimeter } else { width = perimeter / 4.0; } if (width <= 0.0) { return 0.0; } double length = pBlob->area() / width; return std::max(length, width); } //////////////////// // BlobGetBreadth // //////////////////// double BlobGetBreadth::operator()(cv::Ptr<Blob> pBlob) { // @todo refactor common length and width computation double area = pBlob->area(); double perimeter = pBlob->perimeter(); // @todo where does this function come from double tmp = (perimeter * perimeter) - (16.0 * area); double width = 0.0; if (tmp > 0.0) { width = (perimeter + sqrt(tmp)) / 4.0; // @todo what does he mean by this? // error intrínsec en els cālculs de l'ārea i el perímetre // Translates to: // intrinsic error in calculating the area and perimeter } else { width = perimeter / 4.0; } if (width <= 0.0) { return 0.0; } double length = pBlob->area() / width; return std::min(length, width); } ////////////////// // BlobGetDiffX // ////////////////// double BlobGetDiffX::operator()(cv::Ptr<Blob> pBlob) { return pBlob->boundingBox().width; } ////////////////// // BlobGetDiffY // ////////////////// double BlobGetDiffY::operator()(cv::Ptr<Blob> pBlob) { return pBlob->boundingBox().height; } /////////////////// // BlobGetMoment // /////////////////// BlobGetMoment::BlobGetMoment() : mP(0), mQ(0) {} BlobGetMoment::BlobGetMoment(int p, int q) : mP(p), mQ(q) {} double BlobGetMoment::operator()(cv::Ptr<Blob> pBlob) { return pBlob->moment(mP, mQ); } ////////////////////////// // BlobGetHullPerimeter // ////////////////////////// double BlobGetHullPerimeter::operator()(cv::Ptr<Blob> pBlob) { PointContainerType convex_hull; pBlob->convexHull(convex_hull); double perimeter = 0.0; if (!convex_hull.empty()) { perimeter = fabs( cv::arcLength(convex_hull, true) ); // true == closed } return perimeter; } ///////////////////// // BlobGetHullArea // ///////////////////// double BlobGetHullArea::operator()(cv::Ptr<Blob> pBlob) { PointContainerType convex_hull; pBlob->convexHull(convex_hull); double area = 0.0; if (!convex_hull.empty()) { area = fabs( cv::contourArea(convex_hull) ); } return area; } /////////////////////// // BlobGetMinXatMinY // /////////////////////// double BlobGetMinXatMinY::operator()(cv::Ptr<Blob> pBlob) { double result = std::numeric_limits<double>::max(); const PointContainerType& extern_contour = pBlob->externalContour()->contourPoints(); if (extern_contour.empty()) { return result; } typedef PointContainerType::const_iterator PointIter; // define end outside for loop for performance and intent // we are not going to modify this container PointIter end_iter = extern_contour.end(); for (PointIter iter = extern_contour.begin(); iter != end_iter; ++iter) { const cv::Point& actual_point = *iter; if (actual_point.y == pBlob->minY() && actual_point.x < result) { result = actual_point.x; } } return result; } /////////////////////// // BlobGetMinYatMaxX // /////////////////////// double BlobGetMinYatMaxX::operator()(cv::Ptr<Blob> pBlob) { double result = std::numeric_limits<double>::max(); const PointContainerType& extern_contour = pBlob->externalContour()->contourPoints(); if (extern_contour.empty()) { return result; } typedef PointContainerType::const_iterator PointIter; // define end outside for loop for performance and intent // we are not going to modify this container PointIter end_iter = extern_contour.end(); for (PointIter iter = extern_contour.begin(); iter != end_iter; ++iter) { const cv::Point& actual_point = *iter; if (actual_point.x == pBlob->maxX() && actual_point.y < result) { result = actual_point.y; } } return result; } /////////////////////// // BlobGetMaxXatMaxY // /////////////////////// double BlobGetMaxXatMaxY::operator()(cv::Ptr<Blob> pBlob) { double result = std::numeric_limits<double>::max(); const PointContainerType& extern_contour = pBlob->externalContour()->contourPoints(); if (extern_contour.empty()) { return result; } typedef PointContainerType::const_iterator PointIter; // define end outside for loop for performance and intent // we are not going to modify this container PointIter end_iter = extern_contour.end(); for (PointIter iter = extern_contour.begin(); iter != end_iter; ++iter) { const cv::Point& actual_point = *iter; if (actual_point.y == pBlob->maxY() && actual_point.x > result) { result = actual_point.x; } } return result; } /////////////////////// // BlobGetMaxYatMinX // /////////////////////// double BlobGetMaxYatMinX::operator()(cv::Ptr<Blob> pBlob) { double result = std::numeric_limits<double>::max(); const PointContainerType& extern_contour = pBlob->externalContour()->contourPoints(); if (extern_contour.empty()) { return result; } typedef PointContainerType::const_iterator PointIter; // define end outside for loop for performance and intent // we are not going to modify this container PointIter end_iter = extern_contour.end(); for (PointIter iter = extern_contour.begin(); iter != end_iter; ++iter) { const cv::Point& actual_point = *iter; if (actual_point.x == pBlob->minX() && actual_point.y > result) { result = actual_point.y; } } return result; } ///////////////// // BlobGetMinX // ///////////////// double BlobGetMinX::operator()(cv::Ptr<Blob> pBlob) { return pBlob->minX(); } ///////////////// // BlobGetMaxX // ///////////////// double BlobGetMaxX::operator()(cv::Ptr<Blob> pBlob) { return pBlob->maxX(); } ///////////////// // BlobGetMinY // ///////////////// double BlobGetMinY::operator()(cv::Ptr<Blob> pBlob) { return pBlob->minY(); } ///////////////// // BlobGetMaxY // ///////////////// double BlobGetMaxY::operator()(cv::Ptr<Blob> pBlob) { return pBlob->maxY(); } /////////////////////// // BlobGetElongation // /////////////////////// double BlobGetElongation::operator()(cv::Ptr<Blob> pBlob) { // @todo refactor common length and width computation double area = pBlob->area(); double perimeter = pBlob->perimeter(); // @todo where does this function come from double tmp = (perimeter * perimeter) - (16.0 * area); double width = 0.0; if (tmp > 0.0) { width = (perimeter + sqrt(tmp)) / 4.0; // @todo what does he mean by this? // error intrínsec en els cālculs de l'ārea i el perímetre // Translates to: // intrinsic error in calculating the area and perimeter } else { width = perimeter / 4.0; } if (width <= 0.0) { return 0.0; } double length = pBlob->area() / width; double length_max = std::max(length, width); double width_min = std::min(length, width); return length_max / width_min; } ////////////////////// // BlobGetRoughness // ////////////////////// double BlobGetRoughness::operator()(cv::Ptr<Blob> pBlob) { BlobGetHullPerimeter getHullPerimeter; double hull_perimeter = getHullPerimeter(pBlob); if (hull_perimeter != 0.0) { return pBlob->perimeter() / hull_perimeter; } return 0.0; } ////////////////////////////// // BlobGetDistanceFromPoint // ////////////////////////////// BlobGetDistanceFromPoint::BlobGetDistanceFromPoint() : mPoint(0.0, 0.0) {} BlobGetDistanceFromPoint::BlobGetDistanceFromPoint(const double x, const double y) : mPoint(x, y) {} BlobGetDistanceFromPoint::BlobGetDistanceFromPoint(const cv::Point& point) : mPoint() { mPoint = point; } double BlobGetDistanceFromPoint::operator()(cv::Ptr<Blob> pBlob) { BlobGetXCenter getXCenter; BlobGetYCenter getYCenter; double x_average = mPoint.x - getXCenter( pBlob ); double y_average = mPoint.y - getYCenter( pBlob ); return sqrt( (x_average * x_average) + (y_average * y_average) ); } //////////////////////////// // BlobGetExternPerimeter // //////////////////////////// BlobGetExternPerimeter::BlobGetExternPerimeter() : mMask(), mbXBorderLeft(false), mbXBorderRight(false), mbYBorderTop(false), mbYBorderBottom(false) {} BlobGetExternPerimeter::BlobGetExternPerimeter(cv::Mat& mask, bool bXBorderLeft, bool bXBorderRight, bool bYBorderTop, bool bYBorderBottom) : mMask(mask), mbXBorderLeft(bXBorderLeft), mbXBorderRight(bXBorderRight), mbYBorderTop(bYBorderTop), mbYBorderBottom(bYBorderBottom) {} double BlobGetExternPerimeter::operator()(cv::Ptr<Blob> pBlob) { return pBlob->externPerimeter(mMask, mbXBorderLeft, mbXBorderRight, mbYBorderTop, mbYBorderBottom); } ///////////////////////////////// // BlobGetExternPerimeterRatio // ///////////////////////////////// BlobGetExternPerimeterRatio::BlobGetExternPerimeterRatio() : mMask(), mbXBorderLeft(false), mbXBorderRight(false), mbYBorderTop(false), mbYBorderBottom(false) {} BlobGetExternPerimeterRatio::BlobGetExternPerimeterRatio(cv::Mat& mask, bool bXBorderLeft, bool bXBorderRight, bool bYBorderTop, bool bYBorderBottom) : mMask(mask), mbXBorderLeft(bXBorderLeft), mbXBorderRight(bXBorderRight), mbYBorderTop(bYBorderTop), mbYBorderBottom(bYBorderBottom) {} double BlobGetExternPerimeterRatio::operator()(cv::Ptr<Blob> pBlob) { const double perimeter = pBlob->perimeter(); const double extern_perimeter = pBlob->externPerimeter(mMask, mbXBorderLeft, mbXBorderRight, mbYBorderTop, mbYBorderBottom); if (perimeter != 0.0) { return extern_perimeter / perimeter; } else { return extern_perimeter; } } ///////////////////////////////////// // BlobGetExternHullPerimeterRatio // ///////////////////////////////////// BlobGetExternHullPerimeterRatio::BlobGetExternHullPerimeterRatio() : mMask(), mbXBorder(false), mbYBorder(false) {} BlobGetExternHullPerimeterRatio::BlobGetExternHullPerimeterRatio(cv::Mat& mask, bool bXBorder, bool bYBorder) : mMask(mask), mbXBorder(bXBorder), mbYBorder(bYBorder) {} double BlobGetExternHullPerimeterRatio::operator()(cv::Ptr<Blob> pBlob) { BlobGetHullPerimeter getHullPerimeter; const double hull_perimeter = getHullPerimeter(pBlob); const double extern_perimeter = pBlob->externPerimeter(mMask, mbXBorder, mbYBorder); if (hull_perimeter != 0.0) { return extern_perimeter / hull_perimeter; } else { return extern_perimeter; } } //////////////////// // BlobGetXCenter // //////////////////// double BlobGetXCenter::operator()(cv::Ptr<Blob> pBlob) { const double min_x = pBlob->minX(); const double max_x = pBlob->maxX(); return min_x + ((max_x - min_x) / 2.0); } //////////////////// // BlobGetYCenter // //////////////////// double BlobGetYCenter::operator()(cv::Ptr<Blob> pBlob) { const double min_y = pBlob->minY(); const double max_y = pBlob->maxY(); return min_y + ((max_y - min_y) / 2.0); } //////////////////////////// // BlobGetMajorAxisLength // //////////////////////////// double BlobGetMajorAxisLength::operator()(cv::Ptr<Blob> pBlob) { cv::RotatedRect elipse = pBlob->ellipse(); return elipse.size.width; } //////////////////////////// // BlobGetAreaElipseRatio // //////////////////////////// double BlobGetAreaElipseRatio::operator()(cv::Ptr<Blob> pBlob) { const double area = pBlob->area(); if (area == 0.0) { return 0.0; } const cv::RotatedRect elipse = pBlob->ellipse(); // https://en.wikipedia.org/wiki/Ellipse#Area // area of ellipse = pi * A * B // A = 1/2 the "major" axis ie the width of the ellipse // B = 1/2 the "minor" axis ie the height of the ellipse const double ellipse_area = ( CV_PI * (elipse.size.width / 2.0) * (elipse.size.height / 2.0)); const double ratioAreaElipseAreaTaca = ellipse_area / area; return ratioAreaElipseAreaTaca; } //////////////////////////// // BlobGetMinorAxisLength // //////////////////////////// double BlobGetMinorAxisLength::operator()(cv::Ptr<Blob> pBlob) { cv::RotatedRect elipse = pBlob->ellipse(); return elipse.size.height; } //////////////////////// // BlobGetOrientation // //////////////////////// double BlobGetOrientation::operator()(cv::Ptr<Blob> pBlob) { cv::RotatedRect elipse = pBlob->ellipse(); return elipse.angle; } ////////////////////////// // BlobGetElipseXCenter // ////////////////////////// double BlobGetElipseXCenter::operator()(cv::Ptr<Blob> pBlob) { cv::RotatedRect elipse = pBlob->ellipse(); return elipse.center.x; } ////////////////////////// // BlobGetElipseYCenter // ////////////////////////// double BlobGetElipseYCenter::operator()(cv::Ptr<Blob> pBlob) { cv::RotatedRect elipse = pBlob->ellipse(); return elipse.center.y; } /////////////////////////// // BlobGetOrientationCos // /////////////////////////// double BlobGetOrientationCos::operator()(cv::Ptr<Blob> pBlob) { BlobGetOrientation getOrientation; return fabs( cos(getOrientation(pBlob) * CVBLOBS_DEGREE2RAD) ); } ////////////////////// // BlobGetAxisRatio // ////////////////////// double BlobGetAxisRatio::operator()(cv::Ptr<Blob> pBlob) { BlobGetMajorAxisLength getMajor; double major = getMajor(pBlob); if (major != 0.0) { BlobGetMinorAxisLength getMinor; double minor = getMinor(pBlob); return minor / major; } else { return 0.0; } } ///////////////////// // BlobGetXYInside // ///////////////////// BlobGetXYInside::BlobGetXYInside() : mPoint(0, 0) {} BlobGetXYInside::BlobGetXYInside(const double& x, const double& y) : mPoint(x, y) {} BlobGetXYInside::BlobGetXYInside(const cv::Point& point) : mPoint() { mPoint = point; } double BlobGetXYInside::operator()(cv::Ptr<Blob> pBlob) { const PointContainerType& extern_contour = pBlob->externalContour()->contourPoints(); if (!extern_contour.empty()) { // false == don't measure distance return cv::pointPolygonTest(extern_contour, mPoint, false) >= 0; } return 0; } ///////////////////////// // BlobGetRelativeArea // ///////////////////////// BlobGetRelativeArea::BlobGetRelativeArea() : mTotalArea(1.0), mTheoreticalArea(0) {} BlobGetRelativeArea::BlobGetRelativeArea(double totalArea, int theoreticalArea) : mTotalArea(totalArea), mTheoreticalArea(theoreticalArea) {} double BlobGetRelativeArea::operator()(cv::Ptr<Blob> pBlob) { if (mTotalArea) { return (pBlob->area() / mTotalArea) * mTheoreticalArea; } return 0.0; } CVBLOBS_END_NAMESPACE
[ "nmaludy@gmail.com" ]
nmaludy@gmail.com
be288f4ca8ec3a55e31d810be44481ce8768045e
b64e9b7b1cf6b535025cafbf20266869755676e4
/Qt/SEGY/SEGYView/tracewidgetdraw.cpp
8748b0253ce42750fadb2ae82e2e698006d9d632
[]
no_license
qdhqf/Tang
6fa59b2b7ad43ac413400391dc0da7c3049a0640
b31d9eb7bb152fde59d352a566d4235e16e43845
refs/heads/master
2020-05-03T08:25:04.781058
2013-10-10T16:39:45
2013-10-10T16:39:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,816
cpp
#include "tracewidgetdraw.h" TraceWidgetDraw::TraceWidgetDraw(TraceWidget *parent) : QWidget(parent) { tracewidget = parent; N=5; setPalette(QPalette(Qt::white)); setAutoFillBackground(true); isDraw=false; //for(int i =0; i < N; i++) Max = 0.0; } TraceWidgetDraw::~TraceWidgetDraw() { Data.clear(); std::vector<float>().swap(Data); } void TraceWidgetDraw::paintEvent(QPaintEvent *e) { Max = 0.0; if (isDraw) { for(int i = 0; i < N;i++) { float temp = Data[i]; if (Max < abs(temp)) Max = temp; } w = this->width(); h = this->height(); QPainter p(this); p.setRenderHint(QPainter::Antialiasing,true); p.setPen(QPen(Qt::blue,3,Qt::SolidLine,Qt::RoundCap)); p.translate(10,10); w = w-20; p.drawLine(0,0,w,0); p.translate(w/2,0); h = h-20; qreal st = h/qreal(N); qreal sx = w/2.0/Max; p.setPen(QPen(Qt::black,0.5,Qt::DotLine,Qt::RoundCap)); for(int i =-5; i <= 5; i++) p.drawLine(i*(w/10),0,i*(w/10),h); for(int i = 100; i < N; i += 100) p.drawLine(-w/2.0,i*st,w/2.0,i*st); // for(qreal i = st; i <= h; i += st*100) // p.drawLine(-w/2.0,i,w/2.0,i); //p.drawLine(0,0,0,h); //p.translate(w/2+10,10); p.setPen(QPen(Qt::black,1,Qt::SolidLine,Qt::RoundCap)); QPoint point[N] ; for(int i = 0; i < N; i++) { point[i].setX(sx*Data[i]); point[i].setY(i*st); } p.drawPolyline(&point[0],N); } } void TraceWidgetDraw::resizeEvent(QResizeEvent *e) { w = this->width(); h = this->height(); update(); } void TraceWidgetDraw::SetData(float x[],int N) { Data.erase(Data.begin(),Data.end()); isDraw= true; for(int i = 0; i < N; i++) Data.push_back(x[i]); update(); }
[ "tangming10000@126.com" ]
tangming10000@126.com
3f058328b42bbd55abf0a99ffe4497e2bc9d8502
635312424a780e2adac206c27ed4c7676f58922d
/src/Mixtures/IsentropicMix.inl
24b7c4f5089317d8cb369d389cc0d8e439726010
[]
no_license
stanfordhpccenter/HTR-solver
aa5a50bafdc9df72f79db7c8532a1ffdf98d7fca
328f84270ce26b83e4c7a4e75c0681a129a48bda
refs/heads/master
2022-10-22T18:53:07.524136
2022-08-04T07:46:56
2022-08-07T04:44:06
249,679,563
59
21
null
null
null
null
UTF-8
C++
false
false
6,074
inl
// Copyright (c) "2019, by Stanford University // Developer: Mario Di Renzo // Affiliation: Center for Turbulence Research, Stanford University // URL: https://ctr.stanford.edu // Citation: Di Renzo, M., Lin, F., and Urzay, J. (2020). // HTR solver: An open-source exascale-oriented task-based // multi-GPU high-order code for hypersonic aerothermodynamics. // Computer Physics Communications 255, 107262" // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. #ifndef __CUDACC__ inline Mix::Mix(const Config &config) : R(config.Flow.mixture.u.IsentropicMix.gasConstant), gamma(config.Flow.mixture.u.IsentropicMix.gamma) { // This executable is expecting IsentropicMix in the input file assert(config.Flow.mixture.type == MixtureModel_IsentropicMix); }; #endif inline const char* Mix::GetSpeciesName(const int i) const { return (char*)"MIX"; }; inline int Mix::FindSpecies(const char *Name) const { return 0; }; __CUDA_HD__ inline bool Mix::CheckMixture(const VecNSp &Yi) const { #ifdef CHECK_MIX return (fabs(Yi[0] - 1.0) < 1e-3); #else return true; #endif }; __CUDA_HD__ inline double Mix::GetMolarWeightFromYi(const VecNSp &Yi) const { return RGAS/R; } __CUDA_HD__ inline double Mix::GetMolarWeightFromXi(const VecNSp &Xi) const { return RGAS/R; } __CUDA_HD__ inline void Mix::GetMolarFractions(VecNSp &Xi, const double MixW, const VecNSp &Yi) const { Xi[0] = Yi[0]; } __CUDA_HD__ inline void Mix::GetMassFractions(VecNSp &Yi, const double MixW, const VecNSp &Xi) const { Yi[0] = Xi[0]; } __CUDA_HD__ inline double Mix::GetRhoFromRhoYi(const VecNSp &rhoYi) const { return rhoYi[0]; } __CUDA_HD__ inline void Mix::GetRhoYiFromYi(VecNSp &rhoYi, const double rho, const VecNSp &Yi) const { rhoYi[0] = rho*Yi[0]; } __CUDA_HD__ inline void Mix::GetYi(VecNSp &Yi, const double rho, const VecNSp &rhoYi) const { Yi[0] = rhoYi[0]/rho; }; __CUDA_HD__ inline double Mix::GetRho(const double P, const double T, const double MixW) const { return P/(R * T); }; __CUDA_HD__ inline double Mix::GetHeatCapacity(const double T, const VecNSp &Yi) const { return gamma/(gamma-1)*R; }; __CUDA_HD__ inline double Mix::GetEnthalpy(const double T, const VecNSp &Yi) const { return gamma/(gamma-1)*R*T; }; __CUDA_HD__ inline double Mix::GetSpeciesEnthalpy(const int i, const double T) const { return T*R*gamma/(gamma-1.0); }; __CUDA_HD__ inline double Mix::GetSpeciesMolarWeight(const int i) const { return RGAS/R; }; __CUDA_HD__ inline double Mix::GetInternalEnergy(const double T, const VecNSp &Yi) const { return T*R/(gamma-1.0); }; __CUDA_HD__ inline double Mix::GetSpecificInternalEnergy(const int i, const double T) const { return T*R/(gamma-1.0); }; __CUDA_HD__ inline double Mix::GetTFromInternalEnergy(const double e0, double T, const VecNSp &Yi) const { return e0*(gamma-1.0)/R; }; __CUDA_HD__ inline double Mix::isValidInternalEnergy(const double e, const VecNSp &Yi) const { return (e > 0); }; __CUDA_HD__ inline double Mix::GetTFromRhoAndP(const double rho, const double MixW, const double P) const { return P/(rho*R); }; __CUDA_HD__ inline double Mix::GetPFromRhoAndT(const double rho, const double MixW, const double T) const { return rho*R*T; }; __CUDA_HD__ inline double Mix::GetViscosity(const double T, const VecNSp &Xi) const { return 0.0; }; __CUDA_HD__ inline double Mix::GetHeatConductivity(const double T, const VecNSp &Xi) const { return 0.0; }; __CUDA_HD__ inline double Mix::GetGamma(const double T, const double MixW, const VecNSp &Yi) const { return gamma; }; __CUDA_HD__ inline double Mix::GetSpeedOfSound(const double T, const double gamma, const double MixW) const { return sqrt(gamma*R*T); }; __CUDA_HD__ inline void Mix::GetDiffusivity(VecNSp &Di, const double P, const double T, const double MixW, const VecNSp &Xi) const { Di[0] = 0.0; }; __CUDA_HD__ inline double Mix::GetPartialElectricChargeDensity(const uint8_t i, const double rhon, const double MixW, const VecNSp &Xi) const { return 0.0; }; __CUDA_HD__ inline double Mix::GetElectricChargeDensity(const double rhon, const double MixW, const VecNSp &Xi) const { return 0.0; }; __CUDA_HD__ inline int8_t Mix::GetSpeciesChargeNumber(const int i) const { return 0; }; __CUDA_HD__ inline double Mix::GetDielectricPermittivity() const { return eps_0; }; __CUDA_HD__ inline void Mix::GetProductionRates(VecNSp &w, const double rhon, const double Pn, const double Tn, const VecNSp &Yi) const { w[0] = 0.0; }; __CUDA_HD__ inline double Mix::Getdpde(const double rho, const double gamma) const { return rho*(gamma - 1); }; __CUDA_HD__ inline void Mix::Getdpdrhoi(VecNSp &dpdrhoi, const double gamma, const double T, const VecNSp &Yi) const { dpdrhoi[0] = R*T; };
[ "direnzo.mario1@gmail.com" ]
direnzo.mario1@gmail.com
160d6d16d723b7a9f7cce19dff79a6e4c3d25de9
2b8fb66ed7fe286420b409a09d9cea55e20430da
/qt/src/threads_tests/thread.cpp
cfe82a0d454e4a185ae041b69f9fb4148da62bc8
[]
no_license
marvinfy/Trainings
3826c9097210c669cf1298d2bccc86fcfa8ef3a5
d1caaf8ac972bb2a695c07af4f722fdcb7ef293f
refs/heads/master
2021-01-01T15:15:55.450954
2012-12-15T20:12:23
2012-12-15T20:12:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
213
cpp
#include "thread.h" #include <iostream> extern bool g_stop; MyThread::MyThread() { } MyThread::~MyThread() { } void MyThread::run() { while (true) { std::cout << g_stop << std::endl; } }
[ "curso1@ubuntu.ubuntu-domain" ]
curso1@ubuntu.ubuntu-domain
c65a4571a390b288ddf28070e387a1ae7a573385
2ed433b2f977c229fd75dff0f7f8484d816d7498
/v110/base_class_110.h
ad715f95bfb32cd0c0f4a9283ab1ac5942e6f02f
[ "MIT" ]
permissive
glensand/visual-studio-compatibility
3e138f1a523b9ddcccdb36e778388119c3c9211a
7a7c7953bd4f7b8cf16485e66a90c966c8b1f829
refs/heads/master
2023-07-01T16:29:14.265710
2021-07-29T08:42:48
2021-07-29T08:42:48
249,183,623
0
0
null
null
null
null
UTF-8
C++
false
false
809
h
/* Copyright (C) 2021 Gleb Bezborodov - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license. * * You should have received a copy of the MIT license with * this file. If not, please write to: bezborodoff.gleb@gmail.com, or visit : https://github.com/glensand/visual-studio-compatibility */ #pragma once #include "export.h" #include <vector> #include <string> #include <functional> class ref_counted { public: virtual ~ref_counted() {} }; class base_class_110 : public ref_counted { public: API base_class_110(); virtual API ~base_class_110() { for (auto&& f : fun) f(); } void API add_fun(const std::function<void()>& f); protected: std::vector<std::string> vec; private: std::string str; std::vector<std::function<void()>> fun; };
[ "bezborodoff.gleb@gmail.com" ]
bezborodoff.gleb@gmail.com
131fffb9154c8f51afbf50fdfeec218e9dce8102
1c390cd4fd3605046914767485b49a929198b470
/PE/181.cpp
9f1e7f60233d46123971bf42549bfe7249c44641
[]
no_license
wwwwodddd/Zukunft
f87fe736b53506f69ab18db674311dd60de04a43
03ffffee9a76e99f6e00bba6dbae91abc6994a34
refs/heads/master
2023-01-24T06:14:35.691292
2023-01-21T15:42:32
2023-01-21T15:42:32
163,685,977
7
8
null
null
null
null
UTF-8
C++
false
false
363
cpp
#include <bits/stdc++.h> using namespace std; long long f[100][100]; int main() { int n = 60; int m = 40; f[0][0] = 1; for (int i = 0; i <= n; i++) { for (int j = (i == 0); j <= m; j++) { for (int k = 0; k + i <= n; k++) { for (int l = 0; l + j <= m; l++) { f[k + i][l + j] += f[k][l]; } } } } printf("%lld\n", f[n][m]); return 0; }
[ "wwwwodddd@gmail.com" ]
wwwwodddd@gmail.com
995293ac4cf8eaf5f6e32a4aa0d3287c43939584
4394331a19b099681b0738e02e7f0a2f0713e95d
/libmediainfo_0.7.82/MediaInfoLib/Source/MediaInfo/MediaInfo_Config_MediaInfo.cpp
217036e4db4b2e9d7a7a1a7f89ded5d75261550f
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "NCSA", "Zlib", "curl" ]
permissive
OLEG4120/MediaInfoCLI-android
b986f2a3a74d502ecfe8c106d0f026082411bca7
94cf4fd1edc9b7b9912d56976f1b4b025dfe6119
refs/heads/master
2021-01-10T16:00:28.266042
2016-01-28T06:44:05
2016-01-28T06:44:57
50,170,254
3
0
null
null
null
null
UTF-8
C++
false
false
97,322
cpp
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/MediaInfo_Config_MediaInfo.h" #include "MediaInfo/MediaInfo_Config.h" #include "ZenLib/ZtringListListF.h" #if MEDIAINFO_EVENTS #include "ZenLib/FileName.h" #endif //MEDIAINFO_EVENTS #if MEDIAINFO_IBI || MEDIAINFO_AES #include "base64.h" #endif //MEDIAINFO_IBI || MEDIAINFO_AES #include <algorithm> #if MEDIAINFO_DEMUX #include <cmath> #endif //MEDIAINFO_DEMUX using namespace ZenLib; using namespace std; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Debug #ifdef MEDIAINFO_DEBUG #include <stdio.h> #include <windows.h> namespace MediaInfo_Config_MediaInfo_Debug { FILE* F; std::string Debug; SYSTEMTIME st_In; void Debug_Open(bool Out) { F=fopen("C:\\Temp\\MediaInfo_Debug.txt", "a+t"); Debug.clear(); SYSTEMTIME st; GetLocalTime( &st ); char Duration[100]; if (Out) { FILETIME ft_In; if (SystemTimeToFileTime(&st_In, &ft_In)) { FILETIME ft_Out; if (SystemTimeToFileTime(&st, &ft_Out)) { ULARGE_INTEGER UI_In; UI_In.HighPart=ft_In.dwHighDateTime; UI_In.LowPart=ft_In.dwLowDateTime; ULARGE_INTEGER UI_Out; UI_Out.HighPart=ft_Out.dwHighDateTime; UI_Out.LowPart=ft_Out.dwLowDateTime; ULARGE_INTEGER UI_Diff; UI_Diff.QuadPart=UI_Out.QuadPart-UI_In.QuadPart; FILETIME ft_Diff; ft_Diff.dwHighDateTime=UI_Diff.HighPart; ft_Diff.dwLowDateTime=UI_Diff.LowPart; SYSTEMTIME st_Diff; if (FileTimeToSystemTime(&ft_Diff, &st_Diff)) { sprintf(Duration, "%02hd:%02hd:%02hd.%03hd", st_Diff.wHour, st_Diff.wMinute, st_Diff.wSecond, st_Diff.wMilliseconds); } else strcpy(Duration, " "); } else strcpy(Duration, " "); } else strcpy(Duration, " "); } else { st_In=st; strcpy(Duration, " "); } fprintf(F," %02hd:%02hd:%02hd.%03hd %s", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, Duration); } void Debug_Close() { Debug += "\r\n"; fwrite(Debug.c_str(), Debug.size(), 1, F); \ fclose(F); } } using namespace MediaInfo_Config_MediaInfo_Debug; #define MEDIAINFO_DEBUG1(_NAME,_TOAPPEND) \ Debug_Open(false); \ Debug+=", ";Debug+=_NAME; \ _TOAPPEND; \ Debug_Close(); #define MEDIAINFO_DEBUG2(_NAME,_TOAPPEND) \ Debug_Open(true); \ Debug+=", ";Debug+=_NAME; \ _TOAPPEND; \ Debug_Close(); #else // MEDIAINFO_DEBUG #define MEDIAINFO_DEBUG1(_NAME,__TOAPPEND) #define MEDIAINFO_DEBUG2(_NAME,__TOAPPEND) #endif // MEDIAINFO_DEBUG namespace MediaInfoLib { const size_t Buffer_NormalSize=/*188*7;//*/64*1024; //*************************************************************************** // Info //*************************************************************************** MediaInfo_Config_MediaInfo::MediaInfo_Config_MediaInfo() { FileIsSeekable=true; FileIsSub=false; FileIsDetectingDuration=false; FileIsReferenced=false; FileTestContinuousFileNames=true; FileKeepInfo=false; FileStopAfterFilled=false; FileStopSubStreamAfterFilled=false; Audio_MergeMonoStreams=false; File_Demux_Interleave=false; File_ID_OnlyRoot=false; #if MEDIAINFO_ADVANCED File_IgnoreSequenceFileSize=false; File_IgnoreSequenceFilesCount=false; File_SequenceFilesSkipFrames=0; File_DefaultFrameRate=0; File_Source_List=false; File_RiskyBitRateEstimation=false; File_MergeBitRateInfo=true; #if MEDIAINFO_DEMUX File_Demux_Unpacketize_StreamLayoutChange_Skip=false; #endif //MEDIAINFO_DEMUX #endif //MEDIAINFO_ADVANCED #if MEDIAINFO_MD5 File_Md5=false; #endif //MEDIAINFO_MD5 #if defined(MEDIAINFO_REFERENCES_YES) File_CheckSideCarFiles=false; #endif //defined(MEDIAINFO_REFERENCES_YES) File_TimeToLive=0; File_Buffer_Size_Hint_Pointer=NULL; File_Buffer_Read_Size=64*1024*1024; #if MEDIAINFO_AES Encryption_Format=Encryption_Format_None; Encryption_Method=Encryption_Method_None; Encryption_Mode=Encryption_Mode_None; Encryption_Padding=Encryption_Padding_None; #endif //MEDIAINFO_AES #if MEDIAINFO_NEXTPACKET NextPacket=false; #endif //MEDIAINFO_NEXTPACKET #if MEDIAINFO_FILTER File_Filter_Audio=false; File_Filter_HasChanged_=false; #endif //MEDIAINFO_FILTER #if MEDIAINFO_EVENTS Event_CallBackFunction=NULL; Event_UserHandler=NULL; SubFile_StreamID=(int64u)-1; ParseUndecodableFrames=false; #endif //MEDIAINFO_EVENTS #if MEDIAINFO_DEMUX Demux_ForceIds=false; Demux_PCM_20bitTo16bit=false; Demux_PCM_20bitTo24bit=false; Demux_Avc_Transcode_Iso14496_15_to_Iso14496_10=false; Demux_Hevc_Transcode_Iso14496_15_to_AnnexB=false; Demux_Unpacketize=false; Demux_Rate=0; Demux_FirstDts=(int64u)-1; Demux_FirstFrameNumber=(int64u)-1; Demux_InitData=0; //In Demux event #endif //MEDIAINFO_DEMUX #if MEDIAINFO_IBIUSAGE Ibi_UseIbiInfoIfAvailable=false; #endif //MEDIAINFO_IBIUSAGE #if MEDIAINFO_IBIUSAGE Ibi_Create=false; #endif //MEDIAINFO_IBIUSAGE //Specific File_MpegTs_ForceMenu=false; File_MpegTs_stream_type_Trust=true; File_MpegTs_Atsc_transport_stream_id_Trust=true; File_MpegTs_RealTime=false; File_Mxf_TimeCodeFromMaterialPackage=false; File_Mxf_ParseIndex=false; File_Bdmv_ParseTargetedFile=true; #if defined(MEDIAINFO_DVDIF_YES) File_DvDif_DisableAudioIfIsInContainer=false; File_DvDif_IgnoreTransmittingFlags=false; #endif //defined(MEDIAINFO_DVDIF_YES) #if defined(MEDIAINFO_DVDIF_ANALYZE_YES) File_DvDif_Analysis=false; #endif //defined(MEDIAINFO_DVDIF_ANALYZE_YES) #if MEDIAINFO_MACROBLOCKS File_Macroblocks_Parse=false; #endif //MEDIAINFO_MACROBLOCKS File_GrowingFile_Delay=10; #if defined(MEDIAINFO_LIBMMS_YES) File_Mmsh_Describe_Only=false; #endif //defined(MEDIAINFO_LIBMMS_YES) File_Eia608_DisplayEmptyStream=false; File_Eia708_DisplayEmptyStream=false; State=0; #if defined(MEDIAINFO_AC3_YES) File_Ac3_IgnoreCrc=false; #endif //defined(MEDIAINFO_AC3_YES) //Internal to MediaInfo, not thread safe File_Names_Pos=0; File_Buffer=NULL; File_Buffer_Size_Max=0; File_Buffer_Size_ToRead=Buffer_NormalSize; File_Buffer_Size=0; File_Buffer_Repeat=false; File_Buffer_Repeat_IsSupported=false; File_IsGrowing=false; File_IsNotGrowingAnymore=false; File_IsImageSequence=false; #if defined(MEDIAINFO_EIA608_YES) File_Scte20_IsPresent=false; #endif //defined(MEDIAINFO_EIA608_YES) #if defined(MEDIAINFO_EIA608_YES) || defined(MEDIAINFO_EIA708_YES) File_DtvccTransport_Stream_IsPresent=false; File_DtvccTransport_Descriptor_IsPresent=false; #endif //defined(MEDIAINFO_EIA608_YES) || defined(MEDIAINFO_EIA708_YES) File_Current_Offset=0; File_Current_Size=(int64u)-1; File_IgnoreEditsBefore=0; File_IgnoreEditsAfter=(int64u)-1; File_EditRate=0; File_Size=(int64u)-1; ParseSpeed=MediaInfoLib::Config.ParseSpeed_Get(); #if MEDIAINFO_EVENTS Config_PerPackage=NULL; #endif //MEDIAINFO_EVENTS #if MEDIAINFO_DEMUX Demux_EventWasSent=false; Demux_Offset_Frame=(int64u)-1; Demux_Offset_DTS=(int64u)-1; Demux_Offset_DTS_FromStream=(int64u)-1; Events_Delayed_CurrentSource=NULL; #if MEDIAINFO_SEEK Demux_IsSeeking=false; #endif //MEDIAINFO_SEEK #endif //MEDIAINFO_DEMUX #if MEDIAINFO_SEEK File_GoTo_IsFrameOffset=false; #endif //MEDIAINFO_SEEK } MediaInfo_Config_MediaInfo::~MediaInfo_Config_MediaInfo() { delete[] File_Buffer; //File_Buffer=NULL; #if MEDIAINFO_EVENTS for (events_delayed::iterator Event=Events_Delayed.begin(); Event!=Events_Delayed.end(); ++Event) for (size_t Pos=0; Pos<Event->second.size(); Pos++) delete Event->second[Pos]; //Event->second[Pos]=NULL; #endif //MEDIAINFO_EVENTS } //*************************************************************************** // Info //*************************************************************************** Ztring MediaInfo_Config_MediaInfo::Option (const String &Option, const String &Value) { #if MEDIAINFO_EVENTS SubFile_Config(Option)=Value; #endif //MEDIAINFO_EVENTS String Option_Lower(Option); size_t Egal_Pos=Option_Lower.find(__T('=')); if (Egal_Pos==string::npos) Egal_Pos=Option_Lower.size(); transform(Option_Lower.begin(), Option_Lower.begin()+Egal_Pos, Option_Lower.begin(), (int(*)(int))tolower); //(int(*)(int)) is a patch for unix if (Option_Lower==__T("file_isseekable")) { File_IsSeekable_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_isseekable_get")) { return File_IsSeekable_Get()?"1":"0"; } if (Option_Lower==__T("file_issub")) { File_IsSub_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_issub_get")) { return File_IsSub_Get()?"1":"0"; } if (Option_Lower==__T("file_isdetectingduration")) { File_IsDetectingDuration_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_isdetectingduration_get")) { return File_IsDetectingDuration_Get()?"1":"0"; } if (Option_Lower==__T("file_isreferenced")) { File_IsReferenced_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_isreferenced_get")) { return File_IsReferenced_Get()?"1":"0"; } if (Option_Lower==__T("file_testcontinuousfilenames")) { File_TestContinuousFileNames_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_testcontinuousfilenames_get")) { return File_TestContinuousFileNames_Get()?"1":"0"; } if (Option_Lower==__T("file_keepinfo")) { File_KeepInfo_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_keepinfo_get")) { return File_KeepInfo_Get()?"1":"0"; } if (Option_Lower==__T("file_stopafterfilled")) { File_StopAfterFilled_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_stopafterfilled_get")) { return File_StopAfterFilled_Get()?"1":"0"; } if (Option_Lower==__T("file_stopsubstreamafterfilled")) { File_StopSubStreamAfterFilled_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_stopsubstreamafterfilled_get")) { return File_StopSubStreamAfterFilled_Get()?"1":"0"; } if (Option_Lower==__T("file_audio_mergemonostreams")) { File_Audio_MergeMonoStreams_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_audio_mergemonostreams_get")) { return File_Audio_MergeMonoStreams_Get()?"1":"0"; } else if (Option_Lower==__T("file_demux_interleave")) { File_Demux_Interleave_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_demux_interleave_get")) { return File_Demux_Interleave_Get()?"1":"0"; } else if (Option_Lower==__T("file_id_onlyroot")) { File_ID_OnlyRoot_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_id_onlyroot_get")) { return File_ID_OnlyRoot_Get()?"1":"0"; } else if (Option_Lower==__T("file_ignoresequencefilescount")) { #if MEDIAINFO_ADVANCED File_IgnoreSequenceFilesCount_Set(!(Value==__T("0") || Value.empty())); return Ztring(); #else //MEDIAINFO_ADVANCED return __T("Disabled due to compilation options"); #endif //MEDIAINFO_ADVANCED } else if (Option_Lower==__T("file_sequencefilesskipframes") || Option_Lower==__T("file_sequencefileskipframes")) { #if MEDIAINFO_ADVANCED File_SequenceFilesSkipFrames_Set(Ztring(Value).To_int64u()); return Ztring(); #else //MEDIAINFO_ADVANCED return __T("Disabled due to compilation options"); #endif //MEDIAINFO_ADVANCED } else if (Option_Lower==__T("file_defaultframerate")) { #if MEDIAINFO_ADVANCED File_DefaultFrameRate_Set(Ztring(Value).To_float64()); return Ztring(); #else //MEDIAINFO_ADVANCED return __T("File_DefaultFrameRate is disabled due to compilation options"); #endif //MEDIAINFO_ADVANCED } else if (Option_Lower==__T("file_source_list")) { #if MEDIAINFO_ADVANCED File_Source_List_Set(!(Value==__T("0") || Value.empty())); return Ztring(); #else //MEDIAINFO_ADVANCED return __T("File_Source_List_Set is disabled due to compilation options"); #endif //MEDIAINFO_ADVANCED } else if (Option_Lower==__T("file_riskybitrateestimation")) { #if MEDIAINFO_ADVANCED File_RiskyBitRateEstimation_Set(!(Value==__T("0") || Value.empty())); return Ztring(); #else //MEDIAINFO_ADVANCED return __T("Advanced features are disabled due to compilation options"); #endif //MEDIAINFO_ADVANCED } else if (Option_Lower==__T("file_mergebitrateinfo")) { #if MEDIAINFO_ADVANCED File_MergeBitRateInfo_Set(!(Value==__T("0") || Value.empty())); return Ztring(); #else //MEDIAINFO_ADVANCED return __T("Advanced features are disabled due to compilation options"); #endif //MEDIAINFO_ADVANCED } else if (Option_Lower==__T("file_demux_unpacketize_streamlayoutchange_skip")) { #if MEDIAINFO_DEMUX #if MEDIAINFO_ADVANCED File_Demux_Unpacketize_StreamLayoutChange_Skip_Set(!(Value==__T("0") || Value.empty())); return Ztring(); #else //MEDIAINFO_ADVANCED return __T("Advanced features disabled due to compilation options"); #endif //MEDIAINFO_ADVANCED #else //MEDIAINFO_ADVANCED return __T("Advanced features disabled due to compilation options"); #endif //MEDIAINFO_ADVANCED } else if (Option_Lower==__T("file_md5")) { #if MEDIAINFO_MD5 File_Md5_Set(!(Value==__T("0") || Value.empty())); return Ztring(); #else //MEDIAINFO_MD5 return __T("MD5 is disabled due to compilation options"); #endif //MEDIAINFO_MD5 } else if (Option_Lower==__T("file_hash")) { #if MEDIAINFO_HASH ZtringList List; List.Separator_Set(0, __T(",")); List.Write(Value); ZtringList ToReturn; ToReturn.Separator_Set(0, __T(",")); HashWrapper::HashFunctions Functions; for (size_t i=0; i<List.size(); ++i) { Ztring Value(List[i]); Value.MakeLowerCase(); bool Found=false; for (size_t j=0; j<HashWrapper::HashFunction_Max; ++j) { Ztring Name; Name.From_UTF8(HashWrapper::Name((HashWrapper::HashFunction)j)); Name.MakeLowerCase(); if (Value==Name) { Functions.set(j); Found=true; } } if (!Found) ToReturn.push_back(List[i]); } File_Hash_Set(Functions); if (ToReturn.empty()) return Ztring(); else return ToReturn.Read()+__T(" hash functions are unknown or disabled due to compilation options"); #else //MEDIAINFO_HASH return __T("Hash functions are disabled due to compilation options"); #endif //MEDIAINFO_HASH } else if (Option_Lower==__T("file_hash_get")) { #if MEDIAINFO_HASH ZtringList List; HashWrapper::HashFunctions Functions=File_Hash_Get(); for (size_t i=0; i<HashWrapper::HashFunction_Max; ++i) if (Functions[i]) List.push_back(Ztring().From_UTF8(HashWrapper::Name((HashWrapper::HashFunction)i))); List.Separator_Set(0, __T(",")); return List.Read(); #else //MEDIAINFO_HASH return __T("Hash functions are disabled due to compilation options"); #endif //MEDIAINFO_HASH } else if (Option_Lower==__T("file_checksidecarfiles")) { #if defined(MEDIAINFO_REFERENCES_YES) File_CheckSideCarFiles_Set(!(Value==__T("0") || Value.empty())); return Ztring(); #else //defined(MEDIAINFO_REFERENCES_YES) return __T("Disabled due to compilation options"); #endif //defined(MEDIAINFO_REFERENCES_YES) } else if (Option_Lower==__T("file_filename")) { File_FileName_Set(Value); return __T(""); } else if (Option_Lower==__T("file_filename_get")) { return File_FileName_Get(); } else if (Option_Lower==__T("file_filenameformat")) { File_FileNameFormat_Set(Value); return __T(""); } else if (Option_Lower==__T("file_filenameformat_get")) { return File_FileNameFormat_Get(); } else if (Option_Lower==__T("file_timetolive")) { File_TimeToLive_Set(Ztring(Value).To_float64()); return __T(""); } else if (Option_Lower==__T("file_timetolive_get")) { return Ztring::ToZtring(File_TimeToLive_Get(), 9); } else if (Option_Lower==__T("file_partial_begin")) { File_Partial_Begin_Set(Value); return __T(""); } else if (Option_Lower==__T("file_partial_begin_get")) { return File_Partial_Begin_Get(); } else if (Option_Lower==__T("file_partial_end")) { File_Partial_End_Set(Value); return __T(""); } else if (Option_Lower==__T("file_partial_end_get")) { return File_Partial_End_Get(); } else if (Option_Lower==__T("file_forceparser")) { File_ForceParser_Set(Value); return __T(""); } else if (Option_Lower==__T("file_forceparser_get")) { return File_ForceParser_Get(); } else if (Option_Lower==__T("file_buffer_size_hint_pointer")) { File_Buffer_Size_Hint_Pointer_Set((size_t*)Ztring(Value).To_int64u()); return __T(""); } else if (Option_Lower==__T("file_buffer_size_hint_pointer_get")) { return Ztring::ToZtring((size_t)File_Buffer_Size_Hint_Pointer_Get()); } else if (Option_Lower==__T("file_buffer_read_size")) { File_Buffer_Read_Size_Set((size_t)Ztring(Value).To_int64u()); return __T(""); } else if (Option_Lower==__T("file_buffer_read_size_get")) { return Ztring::ToZtring((size_t)File_Buffer_Read_Size_Get()); } else if (Option_Lower==__T("file_filter")) { #if MEDIAINFO_FILTER Ztring ValueLowerCase=Ztring(Value).MakeLowerCase(); if (ValueLowerCase==__T("audio")) File_Filter_Audio_Set(true); else File_Filter_Set(ValueLowerCase.To_int64u()); return Ztring(); #else //MEDIAINFO_FILTER return __T("Filter manager is disabled due to compilation options"); #endif //MEDIAINFO_FILTER } else if (Option_Lower==__T("file_filter_get")) { #if MEDIAINFO_FILTER return Ztring();//.From_Number(File_Filter_Get()); #else //MEDIAINFO_FILTER return __T("Filter manager is disabled due to compilation options"); #endif //MEDIAINFO_FILTER } else if (Option_Lower==__T("file_duplicate")) { #if MEDIAINFO_DUPLICATE return File_Duplicate_Set(Value); #else //MEDIAINFO_DUPLICATE return __T("Duplicate manager is disabled due to compilation options"); #endif //MEDIAINFO_DUPLICATE } else if (Option_Lower==__T("file_duplicate_get")) { #if MEDIAINFO_DUPLICATE //if (File_Duplicate_Get()) return __T("1"); //else // return __T(""); #else //MEDIAINFO_DUPLICATE return __T("Duplicate manager is disabled due to compilation options"); #endif //MEDIAINFO_DUPLICATE } else if (Option_Lower==__T("file_demux_forceids")) { #if MEDIAINFO_DEMUX if (Ztring(Value).To_int64u()==0) Demux_ForceIds_Set(false); else Demux_ForceIds_Set(true); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_pcm_20bitto16bit")) { #if MEDIAINFO_DEMUX if (Ztring(Value).To_int64u()==0) Demux_PCM_20bitTo16bit_Set(false); else Demux_PCM_20bitTo16bit_Set(true); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_pcm_20bitto24bit")) { #if MEDIAINFO_DEMUX if (Ztring(Value).To_int64u()==0) Demux_PCM_20bitTo24bit_Set(false); else Demux_PCM_20bitTo24bit_Set(true); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_avc_transcode_iso14496_15_to_iso14496_10")) { #if MEDIAINFO_DEMUX if (Ztring(Value).To_int64u()==0) Demux_Avc_Transcode_Iso14496_15_to_Iso14496_10_Set(false); else Demux_Avc_Transcode_Iso14496_15_to_Iso14496_10_Set(true); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_hevc_transcode_iso14496_15_to_annexb")) { #if MEDIAINFO_DEMUX if (Ztring(Value).To_int64u()==0) Demux_Hevc_Transcode_Iso14496_15_to_AnnexB_Set(false); else Demux_Hevc_Transcode_Iso14496_15_to_AnnexB_Set(true); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_unpacketize")) { #if MEDIAINFO_DEMUX if (Ztring(Value).To_int64u()==0) Demux_Unpacketize_Set(false); else Demux_Unpacketize_Set(true); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_rate")) { #if MEDIAINFO_DEMUX Demux_Rate_Set(Ztring(Value).To_float64()); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_firstdts")) { #if MEDIAINFO_DEMUX int64u ValueInt64u; if (Value.find(__T(":"))!=string::npos) { Ztring ValueZ=Value; ValueInt64u=0; size_t Value_Pos=ValueZ.find(__T(":")); if (Value_Pos==string::npos) Value_Pos=ValueZ.size(); ValueInt64u+=Ztring(ValueZ.substr(0, Value_Pos)).To_int64u()*60*60*1000*1000*1000; ValueZ.erase(0, Value_Pos+1); Value_Pos=ValueZ.find(__T(":")); if (Value_Pos==string::npos) Value_Pos=ValueZ.size(); ValueInt64u+=Ztring(ValueZ.substr(0, Value_Pos)).To_int64u()*60*1000*1000*1000; ValueZ.erase(0, Value_Pos+1); Value_Pos=ValueZ.find(__T(".")); if (Value_Pos==string::npos) Value_Pos=ValueZ.size(); ValueInt64u+=Ztring(ValueZ.substr(0, Value_Pos)).To_int64u()*1000*1000*1000; ValueZ.erase(0, Value_Pos+1); if (!ValueZ.empty()) ValueInt64u+=Ztring(ValueZ).To_int64u()*1000*1000*1000/(int64u)pow(10.0, (int)ValueZ.size()); } else ValueInt64u=Ztring(Value).To_int64u(); Demux_FirstDts_Set(ValueInt64u); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_firstframenumber")) { #if MEDIAINFO_DEMUX Demux_FirstFrameNumber_Set(Ztring(Value).To_int64u()); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_demux_initdata")) { #if MEDIAINFO_DEMUX Ztring Value_Lower(Value); Value_Lower.MakeLowerCase(); if (Value_Lower==__T("event")) Demux_InitData_Set(0); else if (Value_Lower==__T("field")) Demux_InitData_Set(1); else return __T("Invalid value"); return Ztring(); #else //MEDIAINFO_DEMUX return __T("Demux manager is disabled due to compilation options"); #endif //MEDIAINFO_DEMUX } else if (Option_Lower==__T("file_ibi")) { #if MEDIAINFO_IBIUSAGE Ibi_Set(Value); return Ztring(); #else //MEDIAINFO_IBIUSAGE return __T("IBI support is disabled due to compilation options"); #endif //MEDIAINFO_IBIUSAGE } else if (Option_Lower==__T("file_ibi_create")) { #if MEDIAINFO_IBIUSAGE if (Ztring(Value).To_int64u()==0) Ibi_Create_Set(false); else Ibi_Create_Set(true); return Ztring(); #else //MEDIAINFO_IBIUSAGE return __T("IBI support is disabled due to compilation options"); #endif //MEDIAINFO_IBIUSAGE } else if (Option_Lower==__T("file_ibi_useibiinfoifavailable")) { #if MEDIAINFO_IBIUSAGE if (Ztring(Value).To_int64u()==0) Ibi_UseIbiInfoIfAvailable_Set(false); else Ibi_UseIbiInfoIfAvailable_Set(true); return Ztring(); #else //MEDIAINFO_IBIUSAGE return __T("IBI support is disabled due to compilation options"); #endif //MEDIAINFO_IBIUSAGE } else if (Option_Lower==__T("file_encryption_format")) { #if MEDIAINFO_AES Encryption_Format_Set(Value); return Ztring(); #else //MEDIAINFO_AES return __T("Encryption manager is disabled due to compilation options"); #endif //MEDIAINFO_AES } else if (Option_Lower==__T("file_encryption_key")) { #if MEDIAINFO_AES Encryption_Key_Set(Value); return Ztring(); #else //MEDIAINFO_AES return __T("Encryption manager is disabled due to compilation options"); #endif //MEDIAINFO_AES } else if (Option_Lower==__T("file_encryption_method")) { #if MEDIAINFO_AES Encryption_Method_Set(Value); return Ztring(); #else //MEDIAINFO_AES return __T("Encryption manager is disabled due to compilation options"); #endif //MEDIAINFO_AES } else if (Option_Lower==__T("file_encryption_mode") || Option_Lower==__T("file_encryption_modeofoperation")) { #if MEDIAINFO_AES Encryption_Mode_Set(Value); return Ztring(); #else //MEDIAINFO_AES return __T("Encryption manager is disabled due to compilation options"); #endif //MEDIAINFO_AES } else if (Option_Lower==__T("file_encryption_padding")) { #if MEDIAINFO_AES Encryption_Padding_Set(Value); return Ztring(); #else //MEDIAINFO_AES return __T("Encryption manager is disabled due to compilation options"); #endif //MEDIAINFO_AES } else if (Option_Lower==__T("file_encryption_initializationvector")) { #if MEDIAINFO_AES Encryption_InitializationVector_Set(Value); return Ztring(); #else //MEDIAINFO_AES return __T("Encryption manager is disabled due to compilation options"); #endif //MEDIAINFO_AES } else if (Option_Lower==__T("file_nextpacket")) { #if MEDIAINFO_NEXTPACKET if (Ztring(Value).To_int64u()==0) NextPacket_Set(false); else NextPacket_Set(true); return Ztring(); #else //MEDIAINFO_NEXTPACKET return __T("NextPacket manager is disabled due to compilation options"); #endif //MEDIAINFO_NEXTPACKET } else if (Option_Lower==__T("file_subfile_streamid_set")) { #if MEDIAINFO_EVENTS SubFile_StreamID_Set(Value.empty()?(int64u)-1:Ztring(Value).To_int64u()); return Ztring(); #else //MEDIAINFO_EVENTS return __T("Event manager is disabled due to compilation options"); #endif //MEDIAINFO_EVENTS } else if (Option_Lower==__T("file_subfile_ids_set")) { #if MEDIAINFO_EVENTS SubFile_IDs_Set(Value); return Ztring(); #else //MEDIAINFO_EVENTS return __T("Event manager is disabled due to compilation options"); #endif //MEDIAINFO_EVENTS } else if (Option_Lower==__T("file_parseundecodableframes")) { #if MEDIAINFO_EVENTS ParseUndecodableFrames_Set(!(Value==__T("0") || Value.empty())); return Ztring(); #else //MEDIAINFO_EVENTS return __T("Event manager is disabled due to compilation options"); #endif //MEDIAINFO_EVENTS } else if (Option_Lower==__T("file_mpegts_forcemenu")) { File_MpegTs_ForceMenu_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_mpegts_forcemenu_get")) { return File_MpegTs_ForceMenu_Get()?"1":"0"; } else if (Option_Lower==__T("file_mpegts_stream_type_trust")) { File_MpegTs_stream_type_Trust_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_mpegts_stream_type_trust_get")) { return File_MpegTs_stream_type_Trust_Get()?"1":"0"; } else if (Option_Lower==__T("file_mpegts_atsc_transport_stream_id_trust")) { File_MpegTs_Atsc_transport_stream_id_Trust_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_mpegts_atsc_transport_stream_id_trust_get")) { return File_MpegTs_Atsc_transport_stream_id_Trust_Get()?"1":"0"; } else if (Option_Lower==__T("file_mpegts_realtime")) { File_MpegTs_RealTime_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_mpegts_realtime_get")) { return File_MpegTs_RealTime_Get()?"1":"0"; } else if (Option_Lower==__T("file_mxf_timecodefrommaterialpackage")) { File_Mxf_TimeCodeFromMaterialPackage_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_mxf_timecodefrommaterialpackage_get")) { return File_Mxf_TimeCodeFromMaterialPackage_Get()?"1":"0"; } else if (Option_Lower==__T("file_mxf_parseindex")) { File_Mxf_ParseIndex_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_mxf_parseindex_get")) { return File_Mxf_ParseIndex_Get()?"1":"0"; } else if (Option_Lower==__T("file_bdmv_parsetargetedfile")) { File_Bdmv_ParseTargetedFile_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_bdmv_parsetargetedfile_get")) { return File_Bdmv_ParseTargetedFile_Get()?"1":"0"; } else if (Option_Lower==__T("file_dvdif_disableaudioifisincontainer")) { #if defined(MEDIAINFO_DVDIF_YES) File_DvDif_DisableAudioIfIsInContainer_Set(!(Value==__T("0") || Value.empty())); return __T(""); #else //defined(MEDIAINFO_DVDIF_YES) return __T("DVDIF is disabled due to compilation options"); #endif //defined(MEDIAINFO_DVDIF_YES) } else if (Option_Lower==__T("file_dvdif_disableaudioifisincontainer_get")) { #if defined(MEDIAINFO_DVDIF_YES) return File_DvDif_DisableAudioIfIsInContainer_Get()?"1":"0"; #else //defined(MEDIAINFO_DVDIF_YES) return __T("DVDIF is disabled due to compilation options"); #endif //defined(MEDIAINFO_DVDIF_YES) } else if (Option_Lower==__T("file_dvdif_ignoretransmittingflags")) { #if defined(MEDIAINFO_DVDIF_YES) File_DvDif_IgnoreTransmittingFlags_Set(!(Value==__T("0") || Value.empty())); return __T(""); #else //defined(MEDIAINFO_DVDIF_YES) return __T("DVDIF is disabled due to compilation options"); #endif //defined(MEDIAINFO_DVDIF_YES) } else if (Option_Lower==__T("file_dvdif_ignoretransmittingflags_get")) { #if defined(MEDIAINFO_DVDIF_YES) return File_DvDif_IgnoreTransmittingFlags_Get()?"1":"0"; #else //defined(MEDIAINFO_DVDIF_YES) return __T("DVDIF is disabled due to compilation options"); #endif //defined(MEDIAINFO_DVDIF_YES) } else if (Option_Lower==__T("file_dvdif_analysis")) { #if defined(MEDIAINFO_DVDIF_ANALYZE_YES) File_DvDif_Analysis_Set(!(Value==__T("0") || Value.empty())); return __T(""); #else //defined(MEDIAINFO_DVDIF_ANALYZE_YES) return __T("DVDIF Analysis is disabled due to compilation options"); #endif //defined(MEDIAINFO_DVDIF_ANALYZE_YES) } else if (Option_Lower==__T("file_dvdif_analysis_get")) { #if defined(MEDIAINFO_DVDIF_ANALYZE_YES) return File_DvDif_Analysis_Get()?"1":"0"; #else //defined(MEDIAINFO_DVDIF_ANALYZE_YES) return __T("DVDIF Analysis is disabled due to compilation options"); #endif //defined(MEDIAINFO_DVDIF_ANALYZE_YES) } else if (Option_Lower==__T("file_macroblocks_parse")) { #if MEDIAINFO_MACROBLOCKS File_Macroblocks_Parse_Set(!(Value==__T("0") || Value.empty())); return __T(""); #else //MEDIAINFO_MACROBLOCKS return __T("Macroblock parsing is disabled due to compilation options"); #endif //MEDIAINFO_MACROBLOCKS } else if (Option_Lower==__T("file_macroblocks_parse_get")) { #if MEDIAINFO_MACROBLOCKS return File_Macroblocks_Parse_Get()?"1":"0"; #else //MEDIAINFO_MACROBLOCKS return __T("Macroblock parsing is disabled due to compilation options"); #endif //MEDIAINFO_MACROBLOCKS } else if (Option_Lower==__T("file_growingfile_delay")) { File_GrowingFile_Delay_Set(Ztring(Value).To_float64()); return Ztring(); } else if (Option_Lower==__T("file_growingfile_delay_get")) { return Ztring::ToZtring(File_GrowingFile_Delay_Get()); } else if (Option_Lower==__T("file_curl")) { #if defined(MEDIAINFO_LIBCURL_YES) File_Curl_Set(Value); return __T(""); #else //defined(MEDIAINFO_LIBCURL_YES) return __T("Libcurl support is disabled due to compilation options"); #endif //defined(MEDIAINFO_LIBCURL_YES) } else if (Option_Lower.find(__T("file_curl,"))==0 || Option_Lower.find(__T("file_curl;"))==0) { #if defined(MEDIAINFO_LIBCURL_YES) File_Curl_Set(Option.substr(10), Value); return __T(""); #else //defined(MEDIAINFO_LIBCURL_YES) return __T("Libcurl support is disabled due to compilation options"); #endif //defined(MEDIAINFO_LIBCURL_YES) } else if (Option_Lower==__T("file_curl_get")) { #if defined(MEDIAINFO_LIBCURL_YES) return File_Curl_Get(Value); #else //defined(MEDIAINFO_LIBCURL_YES) return __T("Libcurl support is disabled due to compilation options"); #endif //defined(MEDIAINFO_LIBCURL_YES) } else if (Option_Lower==__T("file_mmsh_describe_only")) { #if defined(MEDIAINFO_LIBMMS_YES) File_Mmsh_Describe_Only_Set(!(Value==__T("0") || Value.empty())); return __T(""); #else //defined(MEDIAINFO_LIBMMS_YES) return __T("Libmms support is disabled due to compilation options"); #endif //defined(MEDIAINFO_LIBMMS_YES) } else if (Option_Lower==__T("file_mmsh_describe_only_get")) { #if defined(MEDIAINFO_LIBMMS_YES) return File_Mmsh_Describe_Only_Get()?"1":"0"; #else //defined(MEDIAINFO_LIBMMS_YES) return __T("Libmms support is disabled due to compilation options"); #endif //defined(MEDIAINFO_LIBMMS_YES) } else if (Option_Lower==__T("file_eia708_displayemptystream")) { File_Eia708_DisplayEmptyStream_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_eia708_displayemptystream_get")) { return File_Eia708_DisplayEmptyStream_Get()?"1":"0"; } else if (Option_Lower==__T("file_eia608_displayemptystream")) { File_Eia608_DisplayEmptyStream_Set(!(Value==__T("0") || Value.empty())); return __T(""); } else if (Option_Lower==__T("file_eia608_displayemptystream_get")) { return File_Eia608_DisplayEmptyStream_Get()?"1":"0"; } else if (Option_Lower==__T("file_ac3_ignorecrc")) { #if defined(MEDIAINFO_AC3_YES) File_Ac3_IgnoreCrc_Set(!(Value==__T("0") || Value.empty())); return __T(""); #else //defined(MEDIAINFO_AC3_YES) return __T("AC-3 support is disabled due to compilation options"); #endif //defined(MEDIAINFO_AC3_YES) } else if (Option_Lower==__T("file_ac3_ignorecrc_get")) { #if defined(MEDIAINFO_AC3_YES) return File_Ac3_IgnoreCrc_Get()?"1":"0"; #else //defined(MEDIAINFO_AC3_YES) return __T("AC-3 support is disabled due to compilation options"); #endif //defined(MEDIAINFO_AC3_YES) } else if (Option_Lower==__T("file_event_callbackfunction")) { #if MEDIAINFO_EVENTS return Event_CallBackFunction_Set(Value); #else //MEDIAINFO_EVENTS return __T("Event manager is disabled due to compilation options"); #endif //MEDIAINFO_EVENTS } else return __T("Option not known"); } //*************************************************************************** // File Is Seekable //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_IsSeekable_Set (bool NewValue) { CriticalSectionLocker CSL(CS); FileIsSeekable=NewValue; } bool MediaInfo_Config_MediaInfo::File_IsSeekable_Get () { CriticalSectionLocker CSL(CS); return FileIsSeekable; } //*************************************************************************** // File Is Sub //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_IsSub_Set (bool NewValue) { CriticalSectionLocker CSL(CS); FileIsSub=NewValue; } bool MediaInfo_Config_MediaInfo::File_IsSub_Get () { CriticalSectionLocker CSL(CS); return FileIsSub; } //*************************************************************************** // File Is Detecting Duration //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_IsDetectingDuration_Set (bool NewValue) { CriticalSectionLocker CSL(CS); FileIsDetectingDuration=NewValue; } bool MediaInfo_Config_MediaInfo::File_IsDetectingDuration_Get () { CriticalSectionLocker CSL(CS); return FileIsDetectingDuration; } //*************************************************************************** // File Is Referenced //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_IsReferenced_Set (bool NewValue) { CriticalSectionLocker CSL(CS); FileIsReferenced=NewValue; } bool MediaInfo_Config_MediaInfo::File_IsReferenced_Get () { CriticalSectionLocker CSL(CS); return FileIsReferenced; } //*************************************************************************** // File Keep Info //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_KeepInfo_Set (bool NewValue) { CriticalSectionLocker CSL(CS); FileKeepInfo=NewValue; } bool MediaInfo_Config_MediaInfo::File_KeepInfo_Get () { CriticalSectionLocker CSL(CS); return FileKeepInfo; } //*************************************************************************** // File test continuous file names //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_TestContinuousFileNames_Set (bool NewValue) { CriticalSectionLocker CSL(CS); FileTestContinuousFileNames=NewValue; } bool MediaInfo_Config_MediaInfo::File_TestContinuousFileNames_Get () { CriticalSectionLocker CSL(CS); return FileTestContinuousFileNames; } //*************************************************************************** // Stop after filled //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_StopAfterFilled_Set (bool NewValue) { CriticalSectionLocker CSL(CS); FileStopAfterFilled=NewValue; } bool MediaInfo_Config_MediaInfo::File_StopAfterFilled_Get () { CriticalSectionLocker CSL(CS); return FileStopAfterFilled; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_StopSubStreamAfterFilled_Set (bool NewValue) { CriticalSectionLocker CSL(CS); FileStopSubStreamAfterFilled=NewValue; } bool MediaInfo_Config_MediaInfo::File_StopSubStreamAfterFilled_Get () { CriticalSectionLocker CSL(CS); return FileStopSubStreamAfterFilled; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Audio_MergeMonoStreams_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Audio_MergeMonoStreams=NewValue; } bool MediaInfo_Config_MediaInfo::File_Audio_MergeMonoStreams_Get () { CriticalSectionLocker CSL(CS); return Audio_MergeMonoStreams; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Demux_Interleave_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Demux_Interleave=NewValue; } bool MediaInfo_Config_MediaInfo::File_Demux_Interleave_Get () { CriticalSectionLocker CSL(CS); return File_Demux_Interleave; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_ID_OnlyRoot_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_ID_OnlyRoot=NewValue; } bool MediaInfo_Config_MediaInfo::File_ID_OnlyRoot_Get () { CriticalSectionLocker CSL(CS); return File_ID_OnlyRoot; } //--------------------------------------------------------------------------- #if MEDIAINFO_MD5 void MediaInfo_Config_MediaInfo::File_Md5_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Md5=NewValue; Hash_Functions.set(HashWrapper::MD5, NewValue); } bool MediaInfo_Config_MediaInfo::File_Md5_Get () { CriticalSectionLocker CSL(CS); return Hash_Functions[HashWrapper::MD5]; } #endif //MEDIAINFO_MD5 //--------------------------------------------------------------------------- #if MEDIAINFO_HASH void MediaInfo_Config_MediaInfo::File_Hash_Set (HashWrapper::HashFunctions Funtions) { CriticalSectionLocker CSL(CS); Hash_Functions=Funtions; //Legacy if (File_Md5) Hash_Functions.set(HashWrapper::MD5); } HashWrapper::HashFunctions MediaInfo_Config_MediaInfo::File_Hash_Get () { CriticalSectionLocker CSL(CS); return Hash_Functions; } #endif //MEDIAINFO_HASH //--------------------------------------------------------------------------- #if defined(MEDIAINFO_REFERENCES_YES) void MediaInfo_Config_MediaInfo::File_CheckSideCarFiles_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_CheckSideCarFiles=NewValue; } bool MediaInfo_Config_MediaInfo::File_CheckSideCarFiles_Get () { CriticalSectionLocker CSL(CS); return File_CheckSideCarFiles; } #endif //defined(MEDIAINFO_REFERENCES_YES) //--------------------------------------------------------------------------- #if MEDIAINFO_ADVANCED void MediaInfo_Config_MediaInfo::File_IgnoreSequenceFileSize_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_IgnoreSequenceFileSize=NewValue; } bool MediaInfo_Config_MediaInfo::File_IgnoreSequenceFileSize_Get () { CriticalSectionLocker CSL(CS); return File_IgnoreSequenceFileSize; } #endif //MEDIAINFO_ADVANCED //--------------------------------------------------------------------------- #if MEDIAINFO_ADVANCED void MediaInfo_Config_MediaInfo::File_IgnoreSequenceFilesCount_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_IgnoreSequenceFilesCount=NewValue; } bool MediaInfo_Config_MediaInfo::File_IgnoreSequenceFilesCount_Get () { CriticalSectionLocker CSL(CS); return File_IgnoreSequenceFilesCount; } #endif //MEDIAINFO_ADVANCED //--------------------------------------------------------------------------- #if MEDIAINFO_ADVANCED void MediaInfo_Config_MediaInfo::File_SequenceFilesSkipFrames_Set (int64u NewValue) { CriticalSectionLocker CSL(CS); File_SequenceFilesSkipFrames=NewValue; } int64u MediaInfo_Config_MediaInfo::File_SequenceFilesSkipFrames_Get () { CriticalSectionLocker CSL(CS); return File_SequenceFilesSkipFrames; } #endif //MEDIAINFO_ADVANCED //--------------------------------------------------------------------------- #if MEDIAINFO_ADVANCED void MediaInfo_Config_MediaInfo::File_DefaultFrameRate_Set (float64 NewValue) { CriticalSectionLocker CSL(CS); File_DefaultFrameRate=NewValue; #if MEDIAINFO_DEMUX Demux_Rate=File_DefaultFrameRate; #endif //MEDIAINFO_DEMUX } float64 MediaInfo_Config_MediaInfo::File_DefaultFrameRate_Get () { CriticalSectionLocker CSL(CS); return File_DefaultFrameRate; } #endif //MEDIAINFO_ADVANCED //--------------------------------------------------------------------------- #if MEDIAINFO_ADVANCED void MediaInfo_Config_MediaInfo::File_Source_List_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Source_List=NewValue; } bool MediaInfo_Config_MediaInfo::File_Source_List_Get () { CriticalSectionLocker CSL(CS); return File_Source_List; } #endif //MEDIAINFO_ADVANCED //--------------------------------------------------------------------------- #if MEDIAINFO_ADVANCED void MediaInfo_Config_MediaInfo::File_RiskyBitRateEstimation_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_RiskyBitRateEstimation=NewValue; } bool MediaInfo_Config_MediaInfo::File_RiskyBitRateEstimation_Get () { CriticalSectionLocker CSL(CS); return File_RiskyBitRateEstimation; } #endif //MEDIAINFO_ADVANCED //--------------------------------------------------------------------------- #if MEDIAINFO_ADVANCED void MediaInfo_Config_MediaInfo::File_MergeBitRateInfo_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_MergeBitRateInfo=NewValue; } bool MediaInfo_Config_MediaInfo::File_MergeBitRateInfo_Get () { CriticalSectionLocker CSL(CS); return File_MergeBitRateInfo; } #endif //MEDIAINFO_ADVANCED //--------------------------------------------------------------------------- #if MEDIAINFO_DEMUX #if MEDIAINFO_ADVANCED void MediaInfo_Config_MediaInfo::File_Demux_Unpacketize_StreamLayoutChange_Skip_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Demux_Unpacketize_StreamLayoutChange_Skip=NewValue; } bool MediaInfo_Config_MediaInfo::File_Demux_Unpacketize_StreamLayoutChange_Skip_Get () { CriticalSectionLocker CSL(CS); return File_Demux_Unpacketize_StreamLayoutChange_Skip; } #endif //MEDIAINFO_ADVANCED #endif //MEDIAINFO_DEMUX //*************************************************************************** // File name from somewhere else //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_FileName_Set (const Ztring &NewValue) { CriticalSectionLocker CSL(CS); File_FileName=NewValue; } Ztring MediaInfo_Config_MediaInfo::File_FileName_Get () { CriticalSectionLocker CSL(CS); return File_FileName; } //*************************************************************************** // File name format //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_FileNameFormat_Set (const Ztring &NewValue) { CriticalSectionLocker CSL(CS); File_FileNameFormat=NewValue; } Ztring MediaInfo_Config_MediaInfo::File_FileNameFormat_Get () { CriticalSectionLocker CSL(CS); return File_FileNameFormat; } //*************************************************************************** // Time to live //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_TimeToLive_Set (float64 NewValue) { CriticalSectionLocker CSL(CS); File_TimeToLive=NewValue; } float64 MediaInfo_Config_MediaInfo::File_TimeToLive_Get () { CriticalSectionLocker CSL(CS); return File_TimeToLive; } //*************************************************************************** // Partial file (begin and end are cut) //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Partial_Begin_Set (const Ztring &NewValue) { CriticalSectionLocker CSL(CS); File_Partial_Begin=NewValue; } Ztring MediaInfo_Config_MediaInfo::File_Partial_Begin_Get () { CriticalSectionLocker CSL(CS); return File_Partial_Begin; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Partial_End_Set (const Ztring &NewValue) { CriticalSectionLocker CSL(CS); File_Partial_End=NewValue; } Ztring MediaInfo_Config_MediaInfo::File_Partial_End_Get () { CriticalSectionLocker CSL(CS); return File_Partial_End; } //*************************************************************************** // Force Parser //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_ForceParser_Set (const Ztring &NewValue) { CriticalSectionLocker CSL(CS); File_ForceParser=NewValue; } Ztring MediaInfo_Config_MediaInfo::File_ForceParser_Get () { CriticalSectionLocker CSL(CS); return File_ForceParser; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Buffer_Size_Hint_Pointer_Set (size_t* NewValue) { CriticalSectionLocker CSL(CS); File_Buffer_Size_Hint_Pointer=NewValue; } size_t* MediaInfo_Config_MediaInfo::File_Buffer_Size_Hint_Pointer_Get () { CriticalSectionLocker CSL(CS); return File_Buffer_Size_Hint_Pointer; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Buffer_Read_Size_Set (size_t NewValue) { CriticalSectionLocker CSL(CS); File_Buffer_Read_Size=NewValue; } size_t MediaInfo_Config_MediaInfo::File_Buffer_Read_Size_Get () { CriticalSectionLocker CSL(CS); return File_Buffer_Read_Size; } //*************************************************************************** // Filter //*************************************************************************** //--------------------------------------------------------------------------- #if MEDIAINFO_FILTER void MediaInfo_Config_MediaInfo::File_Filter_Set (int64u NewValue) { CriticalSectionLocker CSL(CS); File_Filter_16[(int16u)NewValue]=true; File_Filter_HasChanged_=true; } bool MediaInfo_Config_MediaInfo::File_Filter_Get (const int16u Value) { CriticalSectionLocker CSL(CS); //Test bool Exists; if (File_Filter_16.empty()) Exists=true; else Exists=(File_Filter_16.find(Value)!=File_Filter_16.end()); return Exists; } bool MediaInfo_Config_MediaInfo::File_Filter_Get () { CriticalSectionLocker CSL(CS); bool Exist=!File_Filter_16.empty(); return Exist; } void MediaInfo_Config_MediaInfo::File_Filter_Audio_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Filter_Audio=NewValue; } bool MediaInfo_Config_MediaInfo::File_Filter_Audio_Get () { CriticalSectionLocker CSL(CS); return File_Filter_Audio; } bool MediaInfo_Config_MediaInfo::File_Filter_HasChanged () { CriticalSectionLocker CSL(CS); bool File_Filter_HasChanged_Temp=File_Filter_HasChanged_; File_Filter_HasChanged_=false; return File_Filter_HasChanged_Temp; } #endif //MEDIAINFO_FILTER //*************************************************************************** // Duplicate //*************************************************************************** #if MEDIAINFO_DUPLICATE Ztring MediaInfo_Config_MediaInfo::File_Duplicate_Set (const Ztring &Value_In) { //Preparing for File__Duplicate... CS.Enter(); File__Duplicate_List.push_back(Value_In); //Handling Memory index Ztring ToReturn; ZtringList List=Value_In; for (size_t Pos=0; Pos<List.size(); Pos++) { //Form= "(-)Data", if "-" the value will be removed Ztring &Value=List[Pos]; bool ToRemove=false; if (Value.find(__T('-'))==0) { Value.erase(Value.begin()); ToRemove=true; } //Testing if this is information about a target if (List[Pos].find(__T("memory:"))==0 || List[Pos].find(__T("file:"))==0) { //Searching if already exist size_t Memory_Pos=File__Duplicate_Memory_Indexes.Find(List[Pos]); if (!ToRemove && Memory_Pos==Error) { //Does not exist yet (and adding is wanted) Memory_Pos=File__Duplicate_Memory_Indexes.Find(__T("")); if (Memory_Pos!=Error) File__Duplicate_Memory_Indexes[Memory_Pos]=List[Pos]; //A free place is found else { //Adding the place at the end Memory_Pos=File__Duplicate_Memory_Indexes.size(); File__Duplicate_Memory_Indexes.push_back(List[Pos]); } } else if (ToRemove) { //Exists yet but Removal is wanted File__Duplicate_Memory_Indexes[Memory_Pos].clear(); Memory_Pos=(size_t)-1; } ToReturn+=__T(";")+Ztring().From_Number(Memory_Pos); } } if (!ToReturn.empty()) ToReturn.erase(ToReturn.begin()); //Remove first ";" CS.Leave(); File_IsSeekable_Set(false); //If duplication, we can not seek anymore return ToReturn; } Ztring MediaInfo_Config_MediaInfo::File_Duplicate_Get (size_t AlreadyRead_Pos) { CriticalSectionLocker CSL(CS); if (AlreadyRead_Pos>=File__Duplicate_List.size()) return Ztring(); //Nothing or not more than the last time Ztring Temp=File__Duplicate_List[AlreadyRead_Pos]; return Temp; } bool MediaInfo_Config_MediaInfo::File_Duplicate_Get_AlwaysNeeded (size_t AlreadyRead_Pos) { CriticalSectionLocker CSL(CS); bool Temp=AlreadyRead_Pos>=File__Duplicate_List.size(); return !Temp; //True if there is something to read } size_t MediaInfo_Config_MediaInfo::File__Duplicate_Memory_Indexes_Get (const Ztring &Value) { CriticalSectionLocker CSL(CS); return File__Duplicate_Memory_Indexes.Find(Value); } void MediaInfo_Config_MediaInfo::File__Duplicate_Memory_Indexes_Erase (const Ztring &Value) { CriticalSectionLocker CSL(CS); size_t Pos=File__Duplicate_Memory_Indexes.Find(Value); if (Pos!=Error) File__Duplicate_Memory_Indexes[Pos].clear(); } #endif //MEDIAINFO_DUPLICATE //*************************************************************************** // Demux //*************************************************************************** #if MEDIAINFO_DEMUX //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Demux_ForceIds_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Demux_ForceIds=NewValue; } bool MediaInfo_Config_MediaInfo::Demux_ForceIds_Get () { CriticalSectionLocker CSL(CS); return Demux_ForceIds; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Demux_PCM_20bitTo16bit_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Demux_PCM_20bitTo16bit=NewValue; } bool MediaInfo_Config_MediaInfo::Demux_PCM_20bitTo16bit_Get () { CriticalSectionLocker CSL(CS); return Demux_PCM_20bitTo16bit; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Demux_PCM_20bitTo24bit_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Demux_PCM_20bitTo24bit=NewValue; } bool MediaInfo_Config_MediaInfo::Demux_PCM_20bitTo24bit_Get () { CriticalSectionLocker CSL(CS); return Demux_PCM_20bitTo24bit; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Demux_Avc_Transcode_Iso14496_15_to_Iso14496_10_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Demux_Avc_Transcode_Iso14496_15_to_Iso14496_10=NewValue; } bool MediaInfo_Config_MediaInfo::Demux_Avc_Transcode_Iso14496_15_to_Iso14496_10_Get () { CriticalSectionLocker CSL(CS); return Demux_Avc_Transcode_Iso14496_15_to_Iso14496_10; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Demux_Hevc_Transcode_Iso14496_15_to_AnnexB_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Demux_Hevc_Transcode_Iso14496_15_to_AnnexB=NewValue; } bool MediaInfo_Config_MediaInfo::Demux_Hevc_Transcode_Iso14496_15_to_AnnexB_Get () { CriticalSectionLocker CSL(CS); return Demux_Hevc_Transcode_Iso14496_15_to_AnnexB; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Demux_Unpacketize_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Demux_Unpacketize=NewValue; } bool MediaInfo_Config_MediaInfo::Demux_Unpacketize_Get () { CriticalSectionLocker CSL(CS); return Demux_Unpacketize; } #endif //MEDIAINFO_DEMUX //--------------------------------------------------------------------------- #if MEDIAINFO_DEMUX void MediaInfo_Config_MediaInfo::Demux_Rate_Set (float64 NewValue) { CriticalSectionLocker CSL(CS); Demux_Rate=NewValue; } float64 MediaInfo_Config_MediaInfo::Demux_Rate_Get () { CriticalSectionLocker CSL(CS); return Demux_Rate; } #endif //MEDIAINFO_DEMUX //--------------------------------------------------------------------------- #if MEDIAINFO_DEMUX void MediaInfo_Config_MediaInfo::Demux_FirstDts_Set (int64u NewValue) { CriticalSectionLocker CSL(CS); Demux_FirstDts=NewValue; } int64u MediaInfo_Config_MediaInfo::Demux_FirstDts_Get () { CriticalSectionLocker CSL(CS); return Demux_FirstDts; } #endif //MEDIAINFO_DEMUX //--------------------------------------------------------------------------- #if MEDIAINFO_DEMUX void MediaInfo_Config_MediaInfo::Demux_FirstFrameNumber_Set (int64u NewValue) { CriticalSectionLocker CSL(CS); Demux_FirstFrameNumber=NewValue; } int64u MediaInfo_Config_MediaInfo::Demux_FirstFrameNumber_Get () { CriticalSectionLocker CSL(CS); return Demux_FirstFrameNumber; } #endif //MEDIAINFO_DEMUX //--------------------------------------------------------------------------- #if MEDIAINFO_DEMUX void MediaInfo_Config_MediaInfo::Demux_InitData_Set (int8u NewValue) { CriticalSectionLocker CSL(CS); Demux_InitData=NewValue; } int8u MediaInfo_Config_MediaInfo::Demux_InitData_Get () { CriticalSectionLocker CSL(CS); return Demux_InitData; } #endif //MEDIAINFO_DEMUX //*************************************************************************** // IBI support //*************************************************************************** #if MEDIAINFO_IBIUSAGE //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Ibi_Set (const Ztring &Value) { string Data_Base64=Value.To_UTF8(); CriticalSectionLocker CSL(CS); Ibi=Base64::decode(Data_Base64); } string MediaInfo_Config_MediaInfo::Ibi_Get () { CriticalSectionLocker CSL(CS); return Ibi; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Ibi_UseIbiInfoIfAvailable_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Ibi_UseIbiInfoIfAvailable=NewValue; } bool MediaInfo_Config_MediaInfo::Ibi_UseIbiInfoIfAvailable_Get () { CriticalSectionLocker CSL(CS); return Ibi_UseIbiInfoIfAvailable; } #endif //MEDIAINFO_IBIUSAGE #if MEDIAINFO_IBIUSAGE //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Ibi_Create_Set (bool NewValue) { CriticalSectionLocker CSL(CS); Ibi_Create=NewValue; } bool MediaInfo_Config_MediaInfo::Ibi_Create_Get () { CriticalSectionLocker CSL(CS); return Ibi_Create; } #endif //MEDIAINFO_IBIUSAGE //*************************************************************************** // Encryption //*************************************************************************** //--------------------------------------------------------------------------- #if MEDIAINFO_AES void MediaInfo_Config_MediaInfo::Encryption_Format_Set (const Ztring &Value) { string Data=Value.To_UTF8(); encryption_format Encryption_Format_Temp=Encryption_Format_None; if (Data=="AES") Encryption_Format_Temp=Encryption_Format_Aes; CriticalSectionLocker CSL(CS); Encryption_Format=Encryption_Format_Temp; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Encryption_Format_Set (encryption_format Value) { CriticalSectionLocker CSL(CS); Encryption_Format=Value; } string MediaInfo_Config_MediaInfo::Encryption_Format_GetS () { CriticalSectionLocker CSL(CS); switch (Encryption_Format) { case Encryption_Format_Aes: return "AES"; default: return string(); } } encryption_format MediaInfo_Config_MediaInfo::Encryption_Format_Get () { CriticalSectionLocker CSL(CS); return Encryption_Format; } #endif //MEDIAINFO_AES //--------------------------------------------------------------------------- #if MEDIAINFO_AES void MediaInfo_Config_MediaInfo::Encryption_Key_Set (const Ztring &Value) { string Data_Base64=Value.To_UTF8(); CriticalSectionLocker CSL(CS); Encryption_Key=Base64::decode(Data_Base64); } void MediaInfo_Config_MediaInfo::Encryption_Key_Set (const int8u* Value, size_t Value_Size) { CriticalSectionLocker CSL(CS); Encryption_Key=string((const char*)Value, Value_Size); } string MediaInfo_Config_MediaInfo::Encryption_Key_Get () { CriticalSectionLocker CSL(CS); return Encryption_Key; } #endif //MEDIAINFO_AES //--------------------------------------------------------------------------- #if MEDIAINFO_AES void MediaInfo_Config_MediaInfo::Encryption_Method_Set (const Ztring &Value) { string Data=Value.To_UTF8(); encryption_method Encryption_Method_Temp=Encryption_Method_None; if (Data=="Segment") Encryption_Method_Temp=Encryption_Method_Segment; CriticalSectionLocker CSL(CS); Encryption_Method=Encryption_Method_Temp; } void MediaInfo_Config_MediaInfo::Encryption_Method_Set (encryption_method Value) { CriticalSectionLocker CSL(CS); Encryption_Method=Value; } string MediaInfo_Config_MediaInfo::Encryption_Method_GetS () { CriticalSectionLocker CSL(CS); switch (Encryption_Method) { case Encryption_Method_Segment: return "Segment"; default: return string(); } } encryption_method MediaInfo_Config_MediaInfo::Encryption_Method_Get () { CriticalSectionLocker CSL(CS); return Encryption_Method; } #endif //MEDIAINFO_AES //--------------------------------------------------------------------------- #if MEDIAINFO_AES void MediaInfo_Config_MediaInfo::Encryption_Mode_Set (const Ztring &Value) { string Data=Value.To_UTF8(); encryption_mode Encryption_Mode_Temp=Encryption_Mode_None; if (Data=="CBC") Encryption_Mode_Temp=Encryption_Mode_Cbc; CriticalSectionLocker CSL(CS); Encryption_Mode=Encryption_Mode_Temp; } void MediaInfo_Config_MediaInfo::Encryption_Mode_Set (encryption_mode Value) { CriticalSectionLocker CSL(CS); Encryption_Mode=Value; } string MediaInfo_Config_MediaInfo::Encryption_Mode_GetS () { CriticalSectionLocker CSL(CS); switch (Encryption_Mode) { case Encryption_Mode_Cbc: return "CBC"; default: return string(); } } encryption_mode MediaInfo_Config_MediaInfo::Encryption_Mode_Get () { CriticalSectionLocker CSL(CS); return Encryption_Mode; } #endif //MEDIAINFO_AES //--------------------------------------------------------------------------- #if MEDIAINFO_AES void MediaInfo_Config_MediaInfo::Encryption_Padding_Set (const Ztring &Value) { string Data=Value.To_UTF8(); encryption_padding Encryption_Padding_Temp=Encryption_Padding_None; if (Data=="PKCS7") Encryption_Padding_Temp=Encryption_Padding_Pkcs7; CriticalSectionLocker CSL(CS); Encryption_Padding=Encryption_Padding_Temp; } void MediaInfo_Config_MediaInfo::Encryption_Padding_Set (encryption_padding Value) { CriticalSectionLocker CSL(CS); Encryption_Padding=Value; } string MediaInfo_Config_MediaInfo::Encryption_Padding_GetS () { CriticalSectionLocker CSL(CS); switch (Encryption_Padding) { case Encryption_Padding_Pkcs7: return "PKCS7"; default: return string(); } } encryption_padding MediaInfo_Config_MediaInfo::Encryption_Padding_Get () { CriticalSectionLocker CSL(CS); return Encryption_Padding; } #endif //MEDIAINFO_AES //--------------------------------------------------------------------------- #if MEDIAINFO_AES void MediaInfo_Config_MediaInfo::Encryption_InitializationVector_Set (const Ztring &Value) { if (Value==__T("Sequence number")) { CriticalSectionLocker CSL(CS); Encryption_InitializationVector="Sequence number"; } else { string Data_Base64=Value.To_UTF8(); CriticalSectionLocker CSL(CS); Encryption_InitializationVector=Base64::decode(Data_Base64); } } string MediaInfo_Config_MediaInfo::Encryption_InitializationVector_Get () { CriticalSectionLocker CSL(CS); return Encryption_InitializationVector; } #endif //MEDIAINFO_AES //*************************************************************************** // NextPacket //*************************************************************************** //--------------------------------------------------------------------------- #if MEDIAINFO_NEXTPACKET void MediaInfo_Config_MediaInfo::NextPacket_Set (bool NewValue) { CriticalSectionLocker CSL(CS); NextPacket=NewValue; } bool MediaInfo_Config_MediaInfo::NextPacket_Get () { CriticalSectionLocker CSL(CS); return NextPacket; } #endif //MEDIAINFO_NEXTPACKET //*************************************************************************** // SubFile //*************************************************************************** #if MEDIAINFO_EVENTS //--------------------------------------------------------------------------- ZtringListList MediaInfo_Config_MediaInfo::SubFile_Config_Get () { CriticalSectionLocker CSL(CS); return SubFile_Config; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::SubFile_StreamID_Set (int64u Value) { CriticalSectionLocker CSL(CS); SubFile_StreamID=Value; } //--------------------------------------------------------------------------- int64u MediaInfo_Config_MediaInfo::SubFile_StreamID_Get () { CriticalSectionLocker CSL(CS); return SubFile_StreamID; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::SubFile_IDs_Set (Ztring Value) { CriticalSectionLocker CSL(CS); SubFile_IDs=Value; } //--------------------------------------------------------------------------- Ztring MediaInfo_Config_MediaInfo::SubFile_IDs_Get () { CriticalSectionLocker CSL(CS); return SubFile_IDs; } #endif //MEDIAINFO_EVENTS //*************************************************************************** // SubFile //*************************************************************************** #if MEDIAINFO_EVENTS //--------------------------------------------------------------------------- bool MediaInfo_Config_MediaInfo::ParseUndecodableFrames_Get () { CriticalSectionLocker CSL(CS); return ParseUndecodableFrames; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::ParseUndecodableFrames_Set (bool Value) { CriticalSectionLocker CSL(CS); ParseUndecodableFrames=Value; } #endif //MEDIAINFO_EVENTS //*************************************************************************** // Event //*************************************************************************** //--------------------------------------------------------------------------- #if MEDIAINFO_EVENTS bool MediaInfo_Config_MediaInfo::Event_CallBackFunction_IsSet () { CriticalSectionLocker CSL(CS); return Event_CallBackFunction?true:false; } #endif //MEDIAINFO_EVENTS //--------------------------------------------------------------------------- #if MEDIAINFO_EVENTS Ztring MediaInfo_Config_MediaInfo::Event_CallBackFunction_Set (const Ztring &Value) { ZtringList List=Value; CriticalSectionLocker CSL(CS); if (List.empty()) { Event_CallBackFunction=(MediaInfo_Event_CallBackFunction*)NULL; Event_UserHandler=NULL; } else for (size_t Pos=0; Pos<List.size(); Pos++) { if (List[Pos].find(__T("CallBack=memory://"))==0) Event_CallBackFunction=(MediaInfo_Event_CallBackFunction*)Ztring(List[Pos].substr(18, std::string::npos)).To_int64u(); else if (List[Pos].find(__T("UserHandle=memory://"))==0) Event_UserHandler=(void*)Ztring(List[Pos].substr(20, std::string::npos)).To_int64u(); else if (List[Pos].find(__T("UserHandler=memory://"))==0) Event_UserHandler=(void*)Ztring(List[Pos].substr(21, std::string::npos)).To_int64u(); else return("Problem during Event_CallBackFunction value parsing"); } return Ztring(); } #endif //MEDIAINFO_EVENTS //--------------------------------------------------------------------------- #if MEDIAINFO_EVENTS Ztring MediaInfo_Config_MediaInfo::Event_CallBackFunction_Get () { CriticalSectionLocker CSL(CS); return __T("CallBack=memory://")+Ztring::ToZtring((size_t)Event_CallBackFunction)+__T(";UserHandler=memory://")+Ztring::ToZtring((size_t)Event_UserHandler); } #endif //MEDIAINFO_EVENTS //--------------------------------------------------------------------------- #if MEDIAINFO_EVENTS void MediaInfo_Config_MediaInfo::Event_Send (File__Analyze* Source, const int8u* Data_Content, size_t Data_Size, const Ztring &File_Name) { CriticalSectionLocker CSL(CS); if (Source==NULL) { MediaInfo_Event_Generic* Temp=(MediaInfo_Event_Generic*)Data_Content; if (Demux_Offset_Frame!=(int64u)-1) { if (Temp->FrameNumber!=(int64u)-1) Temp->FrameNumber+=Demux_Offset_Frame; if (Temp->FrameNumber_PresentationOrder!=(int64u)-1) Temp->FrameNumber_PresentationOrder+=Demux_Offset_Frame; } if (Demux_Offset_DTS!=(int64u)-1) { if (Temp->DTS!=(int64u)-1) Temp->DTS+=Demux_Offset_DTS; if (Temp->PTS!=(int64u)-1) Temp->PTS+=Demux_Offset_DTS; if (Demux_Offset_DTS_FromStream!=(int64u)-1) { if (Temp->DTS!=(int64u)-1) Temp->DTS-=Demux_Offset_DTS_FromStream; if (Temp->PTS!=(int64u)-1) Temp->PTS-=Demux_Offset_DTS_FromStream; } } if (File_IgnoreEditsBefore) { if (Temp->FrameNumber!=(int64u)-1) { if (Temp->FrameNumber>File_IgnoreEditsBefore) Temp->FrameNumber-=File_IgnoreEditsBefore; else Temp->FrameNumber=0; } if (Temp->DTS!=(int64u)-1) { if (File_IgnoreEditsBefore && File_EditRate) { int64u TimeOffset=float64_int64s(((float64)File_IgnoreEditsBefore)/File_EditRate*1000000000); if (Temp->DTS>TimeOffset) Temp->DTS-=TimeOffset; else Temp->DTS=0; } } if (Temp->PTS!=(int64u)-1) { if (File_IgnoreEditsBefore && File_EditRate) { int64u TimeOffset=float64_int64s(((float64)File_IgnoreEditsBefore)/File_EditRate*1000000000); if (Temp->PTS>TimeOffset) Temp->PTS-=TimeOffset; else Temp->PTS=0; } } } } if (Source) { event_delayed* Event=new event_delayed(Data_Content, Data_Size, File_Name); Events_Delayed[Source].push_back(Event); // Copying buffers int32u* EventCode=(int32u*)Data_Content; if (((*EventCode)&0x00FFFFFF)==((MediaInfo_Event_Global_Demux<<8)|4) && Data_Size==sizeof(MediaInfo_Event_Global_Demux_4)) { MediaInfo_Event_Global_Demux_4* Old=(MediaInfo_Event_Global_Demux_4*)Data_Content; MediaInfo_Event_Global_Demux_4* New=(MediaInfo_Event_Global_Demux_4*)Event->Data_Content; if (New->Content_Size) { int8u* Content=new int8u[New->Content_Size]; std::memcpy(Content, Old->Content, New->Content_Size*sizeof(int8u)); New->Content=Content; } if (New->Offsets_Size) { int64u* Offsets_Stream=new int64u[New->Offsets_Size]; std::memcpy(Offsets_Stream, Old->Offsets_Stream, New->Offsets_Size*sizeof(int64u)); New->Offsets_Stream=Offsets_Stream; int64u* Offsets_Content=new int64u[New->Offsets_Size]; std::memcpy(Offsets_Content, Old->Offsets_Content, New->Offsets_Size*sizeof(int64u)); New->Offsets_Content=Offsets_Content; } if (New->OriginalContent_Size) { int8u* OriginalContent=new int8u[New->OriginalContent_Size]; std::memcpy(OriginalContent, Old->OriginalContent, New->OriginalContent_Size*sizeof(int8u)); New->OriginalContent=OriginalContent; } } } else if (Event_CallBackFunction) { MEDIAINFO_DEBUG1( "CallBackFunction", Debug+=", EventID=";Debug+=Ztring::ToZtring(LittleEndian2int32u(Data_Content), 16).To_UTF8();) Event_CallBackFunction ((unsigned char*)Data_Content, Data_Size, Event_UserHandler); MEDIAINFO_DEBUG2( "CallBackFunction", ) } else if (!File_Name.empty()) { MediaInfo_Event_Generic* Event_Generic=(MediaInfo_Event_Generic*)Data_Content; if ((Event_Generic->EventCode&0x00FFFFFF)==((MediaInfo_Event_Global_Demux<<8)|0x04)) //Demux version 4 { if (!MediaInfoLib::Config.Demux_Get()) return; MediaInfo_Event_Global_Demux_4* Event=(MediaInfo_Event_Global_Demux_4*)Data_Content; Ztring File_Name_Final(File_Name); if (Event->StreamIDs_Size==0) File_Name_Final+=__T(".demux"); else for (size_t Pos=0; Pos<Event->StreamIDs_Size; Pos++) { if (Event->StreamIDs_Width[Pos]==17) { Ztring ID; ID.From_CC4((int32u)Event->StreamIDs[Pos]); File_Name_Final+=__T('.')+ID; } else if (Event->StreamIDs_Width[Pos]) { Ztring ID; ID.From_Number(Event->StreamIDs[Pos], 16); while (ID.size()<Event->StreamIDs_Width[Pos]) ID.insert(0, 1, __T('0')); if (ID.size()>Event->StreamIDs_Width[Pos]) ID.erase(0, ID.size()-Event->StreamIDs_Width[Pos]); File_Name_Final+=__T('.')+ID; } else File_Name_Final+=__T(".raw"); } File F; F.Open(File_Name_Final, File::Access_Write_Append); F.Write(Event->Content, Event->Content_Size); } } } void MediaInfo_Config_MediaInfo::Event_Accepted (File__Analyze* Source) { #if MEDIAINFO_DEMUX && MEDIAINFO_NEXTPACKET if (Demux_EventWasSent && NextPacket_Get()) { Events_Delayed_CurrentSource=Source; return; } #endif //MEDIAINFO_DEMUX && MEDIAINFO_NEXTPACKET for (events_delayed::iterator Event=Events_Delayed.begin(); Event!=Events_Delayed.end(); ++Event) if (Event->first==Source) { for (size_t Pos=0; Pos<Event->second.size(); Pos++) if (Event->second[Pos]) { Event_Send(NULL, Event->second[Pos]->Data_Content, Event->second[Pos]->Data_Size, Event->second[Pos]->File_Name); int32u EventCode=*((int32u*)Event->second[Pos]->Data_Content); bool IsDemux=(EventCode&0x00FFFF00)==(MediaInfo_Event_Global_Demux<<8); if (IsDemux) { MediaInfo_Event_Global_Demux_4* Old=(MediaInfo_Event_Global_Demux_4*)Event->second[Pos]->Data_Content; delete[] Old->Content; Old->Content=NULL; if (Old->Offsets_Size) { delete[] Old->Offsets_Content; Old->Offsets_Content=NULL; } if (Old->Offsets_Size) { delete[] Old->OriginalContent; Old->OriginalContent=NULL; } } delete Event->second[Pos]; Event->second[Pos]=NULL; #if MEDIAINFO_DEMUX && MEDIAINFO_NEXTPACKET if (IsDemux && NextPacket_Get()) { Demux_EventWasSent=true; Event->second.erase(Event->second.begin(), Event->second.begin()+Pos); Events_Delayed_CurrentSource=Source; return; } #endif //MEDIAINFO_DEMUX && MEDIAINFO_NEXTPACKET } Events_Delayed.erase(Event->first); return; } } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::Event_SubFile_Start(const Ztring &FileName_Absolute) { Ztring FileName_Relative; if (File_Names_RootDirectory.empty()) { FileName FN(FileName_Absolute); FileName_Relative=FN.Name_Get(); if (!FN.Extension_Get().empty()) { FileName_Relative+=__T('.'); FileName_Relative+=FN.Extension_Get(); } } else { Ztring Root=File_Names_RootDirectory+PathSeparator; FileName_Relative=FileName_Absolute; if (FileName_Relative.find(Root)==0) FileName_Relative.erase(0, Root.size()); } struct MediaInfo_Event_General_SubFile_Start_0 Event; memset(&Event, 0xFF, sizeof(struct MediaInfo_Event_Generic)); Event.EventCode=MediaInfo_EventCode_Create(0, MediaInfo_Event_General_SubFile_Start, 0); Event.EventSize=sizeof(struct MediaInfo_Event_General_SubFile_Start_0); Event.StreamIDs_Size=0; std::string FileName_Relative_Ansi=FileName_Relative.To_UTF8(); std::wstring FileName_Relative_Unicode=FileName_Relative.To_Unicode(); std::string FileName_Absolute_Ansi=FileName_Absolute.To_UTF8(); std::wstring FileName_Absolute_Unicode=FileName_Absolute.To_Unicode(); Event.FileName_Relative=FileName_Relative_Ansi.c_str(); Event.FileName_Relative_Unicode=FileName_Relative_Unicode.c_str(); Event.FileName_Absolute=FileName_Absolute_Ansi.c_str(); Event.FileName_Absolute_Unicode=FileName_Absolute_Unicode.c_str(); Event_Send(NULL, (const int8u*)&Event, Event.EventSize); } #endif //MEDIAINFO_EVENTS //*************************************************************************** // Force Parser //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_MpegTs_ForceMenu_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_MpegTs_ForceMenu=NewValue; } bool MediaInfo_Config_MediaInfo::File_MpegTs_ForceMenu_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_MpegTs_ForceMenu; return Temp; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_MpegTs_stream_type_Trust_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_MpegTs_stream_type_Trust=NewValue; } bool MediaInfo_Config_MediaInfo::File_MpegTs_stream_type_Trust_Get () { CS.Enter(); bool Temp=File_MpegTs_stream_type_Trust; CS.Leave(); return Temp; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_MpegTs_Atsc_transport_stream_id_Trust_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_MpegTs_Atsc_transport_stream_id_Trust=NewValue; } bool MediaInfo_Config_MediaInfo::File_MpegTs_Atsc_transport_stream_id_Trust_Get () { CS.Enter(); bool Temp=File_MpegTs_Atsc_transport_stream_id_Trust; CS.Leave(); return Temp; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_MpegTs_RealTime_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_MpegTs_RealTime=NewValue; } bool MediaInfo_Config_MediaInfo::File_MpegTs_RealTime_Get () { CS.Enter(); bool Temp=File_MpegTs_RealTime; CS.Leave(); return Temp; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Mxf_TimeCodeFromMaterialPackage_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Mxf_TimeCodeFromMaterialPackage=NewValue; } bool MediaInfo_Config_MediaInfo::File_Mxf_TimeCodeFromMaterialPackage_Get () { CS.Enter(); bool Temp=File_Mxf_TimeCodeFromMaterialPackage; CS.Leave(); return Temp; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Mxf_ParseIndex_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Mxf_ParseIndex=NewValue; } bool MediaInfo_Config_MediaInfo::File_Mxf_ParseIndex_Get () { CS.Enter(); bool Temp=File_Mxf_ParseIndex; CS.Leave(); return Temp; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Bdmv_ParseTargetedFile_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Bdmv_ParseTargetedFile=NewValue; } bool MediaInfo_Config_MediaInfo::File_Bdmv_ParseTargetedFile_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_Bdmv_ParseTargetedFile; return Temp; } //--------------------------------------------------------------------------- #if defined(MEDIAINFO_DVDIF_YES) void MediaInfo_Config_MediaInfo::File_DvDif_DisableAudioIfIsInContainer_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_DvDif_DisableAudioIfIsInContainer=NewValue; } bool MediaInfo_Config_MediaInfo::File_DvDif_DisableAudioIfIsInContainer_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_DvDif_DisableAudioIfIsInContainer; return Temp; } #endif //defined(MEDIAINFO_DVDIF_YES) //--------------------------------------------------------------------------- #if defined(MEDIAINFO_DVDIF_YES) void MediaInfo_Config_MediaInfo::File_DvDif_IgnoreTransmittingFlags_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_DvDif_IgnoreTransmittingFlags=NewValue; } bool MediaInfo_Config_MediaInfo::File_DvDif_IgnoreTransmittingFlags_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_DvDif_IgnoreTransmittingFlags; return Temp; } #endif //defined(MEDIAINFO_DVDIF_YES) //--------------------------------------------------------------------------- #if defined(MEDIAINFO_DVDIF_ANALYZE_YES) void MediaInfo_Config_MediaInfo::File_DvDif_Analysis_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_DvDif_Analysis=NewValue; } bool MediaInfo_Config_MediaInfo::File_DvDif_Analysis_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_DvDif_Analysis; return Temp; } #endif //defined(MEDIAINFO_DVDIF_ANALYZE_YES) //--------------------------------------------------------------------------- #if MEDIAINFO_MACROBLOCKS void MediaInfo_Config_MediaInfo::File_Macroblocks_Parse_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Macroblocks_Parse=NewValue; } bool MediaInfo_Config_MediaInfo::File_Macroblocks_Parse_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_Macroblocks_Parse; return Temp; } #endif //MEDIAINFO_MACROBLOCKS //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_GrowingFile_Delay_Set (float64 NewValue) { CriticalSectionLocker CSL(CS); File_GrowingFile_Delay=NewValue; } float64 MediaInfo_Config_MediaInfo::File_GrowingFile_Delay_Get () { CriticalSectionLocker CSL(CS); float64 Temp=File_GrowingFile_Delay; return Temp; } //--------------------------------------------------------------------------- #if defined(MEDIAINFO_LIBCURL_YES) void MediaInfo_Config_MediaInfo::File_Curl_Set (const Ztring &NewValue) { size_t Pos=NewValue.find(__T(',')); if (Pos==string::npos) Pos=NewValue.find(__T(';')); if (Pos!=string::npos) { Ztring Field=NewValue.substr(0, Pos); Field.MakeLowerCase(); Ztring Value=NewValue.substr(Pos+1, string::npos); CriticalSectionLocker CSL(CS); Curl[Field]=Value; } } void MediaInfo_Config_MediaInfo::File_Curl_Set (const Ztring &Field_, const Ztring &NewValue) { Ztring Field=Field_; Field.MakeLowerCase(); CriticalSectionLocker CSL(CS); Curl[Field]=NewValue; } Ztring MediaInfo_Config_MediaInfo::File_Curl_Get (const Ztring &Field_) { Ztring Field=Field_; Field.MakeLowerCase(); CriticalSectionLocker CSL(CS); std::map<Ztring, Ztring>::iterator Value=Curl.find(Field); if (Value==Curl.end()) return Ztring(); else return Curl[Field]; } #endif //defined(MEDIAINFO_LIBCURL_YES) //--------------------------------------------------------------------------- #if defined(MEDIAINFO_LIBMMS_YES) void MediaInfo_Config_MediaInfo::File_Mmsh_Describe_Only_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Mmsh_Describe_Only=NewValue; } bool MediaInfo_Config_MediaInfo::File_Mmsh_Describe_Only_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_Mmsh_Describe_Only; return Temp; } #endif //defined(MEDIAINFO_LIBMMS_YES) //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Eia608_DisplayEmptyStream_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Eia608_DisplayEmptyStream=NewValue; } bool MediaInfo_Config_MediaInfo::File_Eia608_DisplayEmptyStream_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_Eia608_DisplayEmptyStream; return Temp; } //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::File_Eia708_DisplayEmptyStream_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Eia708_DisplayEmptyStream=NewValue; } bool MediaInfo_Config_MediaInfo::File_Eia708_DisplayEmptyStream_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_Eia708_DisplayEmptyStream; return Temp; } //--------------------------------------------------------------------------- #if defined(MEDIAINFO_AC3_YES) void MediaInfo_Config_MediaInfo::File_Ac3_IgnoreCrc_Set (bool NewValue) { CriticalSectionLocker CSL(CS); File_Ac3_IgnoreCrc=NewValue; } bool MediaInfo_Config_MediaInfo::File_Ac3_IgnoreCrc_Get () { CriticalSectionLocker CSL(CS); bool Temp=File_Ac3_IgnoreCrc; return Temp; } #endif //defined(MEDIAINFO_AC3_YES) //*************************************************************************** // Analysis internal //*************************************************************************** //--------------------------------------------------------------------------- void MediaInfo_Config_MediaInfo::State_Set (float NewValue) { CriticalSectionLocker CSL(CS); State=NewValue; } float MediaInfo_Config_MediaInfo::State_Get () { CriticalSectionLocker CSL(CS); float Temp=State; return Temp; } } //NameSpace
[ "oleg02007@gmail.com" ]
oleg02007@gmail.com
3abd398d6d08eda409681482ff1a09e48ea8e96c
f1fb2d200242dbf3c3842e212a8aa3f9b674f045
/Source/Server Side/GameServer/Attack.cpp
ee3af268c496a16332a617b36481d844bc18c759
[]
no_license
ptr0x-real/xMuPP
28909cda09b3c7d336a9e4c6e7125be3a0d76fb2
0f563add302530c8497ef70139129d7f5f5fd987
refs/heads/master
2023-01-11T15:21:29.680314
2023-01-08T10:52:58
2023-01-08T10:52:58
294,630,244
3
5
null
null
null
null
UTF-8
C++
false
false
81,875
cpp
// Attack.cpp: implementation of the CAttack class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Attack.h" #include "BattleSoccerManager.h" #include "CastleSiege.h" #include "ChaosCastle.h" #include "Crywolf.h" #include "CustomArena.h" #include "CustomWing.h" #include "DarkSpirit.h" #include "Duel.h" #include "EffectManager.h" #include "GensSystem.h" #include "Guild.h" #include "IllusionTemple.h" #include "Kalima.h" #include "Map.h" #include "MapManager.h" #include "MasterSkillTree.h" #include "Monster.h" #include "MuunSystem.h" #include "ObjectManager.h" #include "Party.h" #include "PentagramSystem.h" #include "ServerInfo.h" #include "SkillManager.h" #include "Util.h" CAttack gAttack; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CAttack::CAttack() // OK { } CAttack::~CAttack() // OK { } bool CAttack::Attack(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,bool send,BYTE flag,int damage,int count,bool combo) // OK { #pragma region ATTACK_CHECK if(lpObj->Index == lpTarget->Index) { return 0; } if(lpObj->Type == OBJECT_USER && gObjIsConnectedGP(lpObj->Index) == 0) { return 0; } if(lpTarget->Type == OBJECT_USER && gObjIsConnectedGP(lpTarget->Index) == 0) { return 0; } if(lpObj->Map != lpTarget->Map || lpObj->Teleport == 2) { return 0; } if(gMap[lpObj->Map].CheckAttr(lpObj->X,lpObj->Y,1) != 0 || gMap[lpTarget->Map].CheckAttr(lpTarget->X,lpTarget->Y,1) != 0) { return 0; } #if(GAMESERVER_UPDATE>=402) if(gDuel.GetDuelArenaBySpectator(lpObj->Index) != 0 || gDuel.GetDuelArenaBySpectator(lpTarget->Index) != 0) { return 0; } #endif #if(GAMESERVER_TYPE==1) if(gCastleSiege.GetCastleState() != CASTLESIEGE_STATE_STARTSIEGE) { if(lpTarget->Type == OBJECT_MONSTER && lpTarget->Map == MAP_CASTLE_SIEGE && (lpTarget->Class == 277 || lpTarget->Class == 283 || lpTarget->Class == 288)) { return 0; } } if(gCrywolf.GetCrywolfState() == CRYWOLF_STATE_READY || gCrywolf.GetCrywolfState() == CRYWOLF_STATE_END) { if(lpTarget->Type == OBJECT_MONSTER && lpTarget->Map == MAP_CRYWOLF) { return 0; } } #endif if(lpObj->GuildNumber > 0 && lpObj->Guild != 0 && lpObj->Guild->WarState != 0) { if(lpObj->Guild->WarType == 1 && GetBattleSoccerGoalMove(0) == 0) { return 1; } if(lpObj->Guild->WarType == 0 && lpTarget->Type == OBJECT_MONSTER) { return 0; } } if(lpTarget->Type == OBJECT_NPC || lpTarget->Live == 0 || lpTarget->State != OBJECT_PLAYING || lpTarget->Teleport != 0) { return 0; } if(lpTarget->Type == OBJECT_MONSTER) { if(KALIMA_ATTRIBUTE_RANGE(lpTarget->Attribute) != 0) { return 0; } if((lpTarget->Class >= 100 && lpTarget->Class <= 110) || lpTarget->Class == 523) // Trap { return 0; } if(lpTarget->Class == 221 || lpTarget->Class == 222) // Siege { return 0; } } if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_MONSTER) { if(OBJECT_RANGE(lpObj->SummonIndex) != 0) { if(lpObj->SummonIndex == lpTarget->Index) { return 0; } } } int SummonIndex = lpObj->Index; if(lpObj->Type == OBJECT_MONSTER && OBJECT_RANGE(lpObj->SummonIndex) != 0) { SummonIndex = lpObj->SummonIndex; } int SummonTargetIndex = lpTarget->Index; if(lpTarget->Type == OBJECT_MONSTER && OBJECT_RANGE(lpTarget->SummonIndex) != 0) { SummonTargetIndex = lpTarget->SummonIndex; } if(this->CheckPlayerTarget(&gObj[SummonIndex],&gObj[SummonTargetIndex]) == 0) { return 0; } #pragma endregion #pragma region ATTACK_RETURN int skill = ((lpSkill==0)?SKILL_NONE:lpSkill->m_skill); if(damage == 0 && skill != SKILL_PLASMA_STORM && this->DecreaseArrow(lpObj) == 0) { return 0; } if(lpObj->Type == OBJECT_USER) { lpObj->HPAutoRecuperationTime = GetTickCount(); lpObj->MPAutoRecuperationTime = GetTickCount(); lpObj->BPAutoRecuperationTime = GetTickCount(); lpObj->SDAutoRecuperationTime = GetTickCount(); } if(lpTarget->Type == OBJECT_USER) { lpTarget->HPAutoRecuperationTime = GetTickCount(); lpTarget->MPAutoRecuperationTime = GetTickCount(); lpTarget->BPAutoRecuperationTime = GetTickCount(); lpTarget->SDAutoRecuperationTime = GetTickCount(); } if(OBJECT_RANGE(lpObj->SummonIndex) != 0) { gObjSummonSetEnemy(lpObj,lpTarget->Index); } if(lpObj->Type == OBJECT_USER) { gDarkSpirit[lpObj->Index].SetTarget(lpTarget->Index); } bool duel = gDuel.CheckDuel(lpObj,lpTarget); if(lpObj->Type == OBJECT_USER && duel != 0) { lpObj->DuelTickCount = GetTickCount(); } if(lpTarget->Type == OBJECT_USER && duel != 0) { lpTarget->DuelTickCount = GetTickCount(); } gEffectManager.DelEffect(lpObj,EFFECT_INVISIBILITY); if(gEffectManager.CheckEffect(lpTarget,EFFECT_ORDER_OF_PROTECTION) != 0 && lpSkill == 0) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } if(gEffectManager.CheckEffect(lpTarget,EFFECT_ORDER_OF_PROTECTION) != 0 && lpSkill != 0) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } if(gEffectManager.CheckEffect(lpTarget,EFFECT_PHYSI_DAMAGE_IMMUNITY) != 0 && lpSkill == 0) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } if(gEffectManager.CheckEffect(lpTarget,EFFECT_MAGIC_DAMAGE_IMMUNITY) != 0 && lpSkill != 0) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } if(lpTarget->Type == OBJECT_MONSTER) { if(lpTarget->Class == 200 && lpSkill == 0) { gObjMonsterStateProc(lpTarget,6,lpObj->Index,0); this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } if(lpTarget->Class == 200 && lpSkill != 0) { gObjMonsterStateProc(lpTarget,7,lpObj->Index,0); this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } if(gEffectManager.CheckEffect(lpTarget,EFFECT_MONSTER_PHYSI_DAMAGE_IMMUNITY) != 0 && skill == SKILL_NONE) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } if(gEffectManager.CheckEffect(lpTarget,EFFECT_MONSTER_MAGIC_DAMAGE_IMMUNITY) != 0 && skill != SKILL_NONE) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } if(lpTarget->MonsterSkillElementOption.CheckImmuneTime() != 0) { if(lpTarget->MonsterSkillElementOption.m_SkillElementImmuneNumber == skill) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 1; } } } #pragma endregion #pragma region DAMAGE_CALC flag = 0; BYTE miss = 0; WORD effect = 0; if(damage == 0) { if((lpObj->Type != OBJECT_USER || lpTarget->Type != OBJECT_USER) && this->MissCheck(lpObj,lpTarget,lpSkill,send,count,&miss) == 0) { #if(GAMESERVER_UPDATE>=701) this->AttackElemental(lpObj,lpTarget,lpSkill,send,flag,damage,count,combo); #endif return 1; } if((lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) && this->MissCheckPvP(lpObj,lpTarget,lpSkill,send,count,&miss) == 0) { #if(GAMESERVER_UPDATE>=701) this->AttackElemental(lpObj,lpTarget,lpSkill,send,flag,damage,count,combo); #endif return 1; } int defense = this->GetTargetDefense(lpObj,lpTarget,&effect); if(skill == SKILL_PLASMA_STORM) { damage = this->GetAttackDamageFenrir(lpObj,lpTarget,lpSkill,&effect,defense); } else if(lpObj->Class == CLASS_SU && (skill == SKILL_SAHAMUTT || skill == SKILL_NEIL || skill == SKILL_GHOST_PHANTOM)) { damage = this->GetAttackDamageCursed(lpObj,lpTarget,lpSkill,&effect,defense); } else if((lpObj->Class == CLASS_DW || lpObj->Class == CLASS_MG || lpObj->Class == CLASS_SU) && skill != SKILL_NONE && skill != SKILL_FALLING_SLASH && skill != SKILL_LUNGE && skill != SKILL_UPPERCUT && skill != SKILL_CYCLONE && skill != SKILL_SLASH && skill != SKILL_TWISTING_SLASH && skill != SKILL_IMPALE && skill != SKILL_FIRE_SLASH && skill != SKILL_POWER_SLASH && skill != SKILL_SPIRAL_SLASH && skill != SKILL_SWORD_SLASH && skill != SKILL_BLOOD_STORM) { damage = this->GetAttackDamageWizard(lpObj,lpTarget,lpSkill,&effect,defense); } else { damage = this->GetAttackDamage(lpObj,lpTarget,lpSkill,&effect,defense); } if(damage > 0) { this->WeaponDurabilityDown(lpObj,lpTarget); } if(miss != 0) { damage = (damage*30)/100; } for(int n=0;n < MAX_DAMAGE_REDUCTION;n++) { damage -= (damage*lpTarget->DamageReduction[n])/100; } if(lpTarget->EffectOption.AddDamageReduction > 0) { damage -= (damage*lpTarget->EffectOption.AddDamageReduction)/100; } if((GetTickCount()-lpTarget->ShieldDamageReductionTime) < ((DWORD)(gServerInfo.m_DefenseTimeConstA*1000))) { damage -= (damage*lpTarget->ShieldDamageReduction)/100; } this->WingSprite(lpObj,lpTarget,&damage); this->HelperSprite(lpObj,lpTarget,&damage); int MinDamage = (lpObj->Level+lpObj->MasterLevel)/10; MinDamage = ((MinDamage<1)?1:MinDamage); damage = ((damage<MinDamage)?MinDamage:damage); this->DamageSprite(lpTarget,damage); #if(GAMESERVER_UPDATE>=803) gMuunSystem.MuunSprite(lpTarget,damage); #endif if(skill == SKILL_FALLING_SLASH || skill == SKILL_LUNGE || skill == SKILL_UPPERCUT || skill == SKILL_CYCLONE || skill == SKILL_SLASH || skill == SKILL_TWISTING_SLASH || skill == SKILL_RAGEFUL_BLOW || skill == SKILL_DEATH_STAB || skill == SKILL_CRESCENT_MOON_SLASH || skill == SKILL_STAR_FALL || skill == SKILL_IMPALE || skill == SKILL_FIRE_BREATH || skill == SKILL_ICE_ARROW || skill == SKILL_PENETRATION || skill == SKILL_FIRE_SLASH || skill == SKILL_POWER_SLASH || skill == SKILL_SPIRAL_SLASH || skill == SKILL_FROZEN_STAB || skill == SKILL_SWORD_SLASH || skill == SKILL_CHARGE || skill == SKILL_BLOOD_STORM) { if(skill != SKILL_IMPALE || lpObj->Inventory[8].m_Index == GET_ITEM(13,2) || lpObj->Inventory[8].m_Index == GET_ITEM(13,3) || lpObj->Inventory[8].m_Index == GET_ITEM(13,37)) { if(lpObj->Class == CLASS_DK) { damage = (damage*lpObj->DKDamageMultiplierRate)/100; } else { damage = (damage*200)/100; } } } else if(skill == SKILL_FORCE || skill == SKILL_FIRE_BURST || skill == SKILL_EARTHQUAKE || skill == SKILL_ELECTRIC_SPARK || skill == SKILL_FIRE_BLAST || skill == SKILL_FIRE_SCREAM || skill == SKILL_BIRDS) { damage = (damage*lpObj->DLDamageMultiplierRate)/100; } else if(skill == SKILL_PLASMA_STORM) { damage = (damage*(200+(((lpObj->Level>300)?((lpObj->Level-300)+lpObj->MasterLevel):0)/5)))/100; } else if(skill == SKILL_CHAIN_LIGHTNING) { damage = (damage*((count==2)?70:((count==3)?50:100)))/100; } else if(skill == SKILL_RAKLION_SELUPAN1) { damage = (damage*200)/100; } else if(skill == SKILL_RAKLION_SELUPAN2) { damage = (damage*220)/100; } else if(skill == SKILL_RAKLION_SELUPAN3) { damage = (damage*230)/100; } else if(skill == SKILL_RAKLION_SELUPAN4) { damage = (damage*250)/100; } else if(skill == SKILL_LARGE_RING_BLOWER || skill == SKILL_UPPER_BEAST || skill == SKILL_PHOENIX_SHOT) { damage = (damage*lpObj->RFDamageMultiplierRate[0])/100; } else if(skill == SKILL_CHAIN_DRIVER) { damage = (damage+((lpObj->Vitality+lpObj->AddVitality)/gServerInfo.m_RFDamageMultiplierConstB)); damage = (damage*lpObj->RFDamageMultiplierRate[0])/100; } else if(skill == SKILL_DARK_SIDE) { damage = (damage+(((lpObj->Dexterity+lpObj->AddDexterity)/gServerInfo.m_RFDamageMultiplierConstA)+((lpObj->Energy+lpObj->AddEnergy)/gServerInfo.m_RFDamageMultiplierConstC))); damage = (damage*lpObj->RFDamageMultiplierRate[2])/100; } else if(skill == SKILL_DRAGON_LORE) { damage = (damage+((lpObj->Energy+lpObj->AddEnergy)/gServerInfo.m_RFDamageMultiplierConstC)); damage = (damage*lpObj->RFDamageMultiplierRate[1])/100; } else if(skill == SKILL_DRAGON_SLAYER) { damage = (damage*lpObj->RFDamageMultiplierRate[1])/100; damage = ((lpTarget->Type==OBJECT_USER)?((damage+100)*3):damage); } else if(skill == SKILL_CHARGE) { damage = (damage*(150+lpObj->RFDamageMultiplierRate[0]))/100; } if(count > 0 && (skill == SKILL_UPPER_BEAST || skill == SKILL_DARK_SIDE)) { effect |= (((count%2)==0)?0x20:0x10); } if(count > 0 && (skill == SKILL_LARGE_RING_BLOWER || skill == SKILL_CHAIN_DRIVER || skill == SKILL_DRAGON_LORE || skill == SKILL_PHOENIX_SHOT)) { effect |= (((count%4)==0)?0x20:0x10); } if((GetLargeRand()%100) < ((lpObj->DoubleDamageRate)-lpTarget->ResistDoubleDamageRate)) { effect |= 0x40; damage += damage; } if((GetLargeRand()%100) < lpObj->TripleDamageRate) { effect |= 0x100; damage += damage+damage; } if(combo != 0) { effect |= 0x80; damage += damage; damage += (((lpObj->Strength+lpObj->AddStrength)+(lpObj->Dexterity+lpObj->AddDexterity)+(lpObj->Energy+lpObj->AddEnergy))/gServerInfo.m_ComboDamageConstA)*gServerInfo.m_ComboDamageConstB; #if(GAMESERVER_UPDATE>=602) damage += (damage*gMasterSkillTree.GetMasterSkillValue(lpObj,MASTER_SKILL_ADD_COMBO_DAMAGE))/100; #endif skill = SKILL_COMBO; } } else { if(skill != SKILL_EXPLOSION) { effect = 0x04; damage = (damage*((lpObj->Type==OBJECT_USER&&lpTarget->Type==OBJECT_USER)?gServerInfo.m_ReflectDamageRatePvP:gServerInfo.m_ReflectDamageRatePvM))/100; } } #pragma endregion #pragma region DAMAGE_CONFIG if(lpObj->Type == OBJECT_USER) { if(lpTarget->Type == OBJECT_USER) { damage = (damage*gServerInfo.m_GeneralDamageRatePvP)/100; damage = (damage*gServerInfo.m_DamageRatePvP[lpObj->Class])/100; damage = (damage*gServerInfo.m_DamageRateTo[lpObj->Class][lpTarget->Class])/100; if(gDuel.CheckDuel(lpObj,lpTarget) != 0) { damage = (damage*gServerInfo.m_DuelDamageRate)/100; } else if(gGensSystem.CheckGens(lpObj,lpTarget) != 0) { damage = (damage*gServerInfo.m_GensDamageRate)/100; } else if(CA_MAP_RANGE(lpObj->Map) != 0 && CA_MAP_RANGE(lpTarget->Map) != 0) { damage = (damage*gServerInfo.m_CustomArenaDamageRate)/100; } else if(CC_MAP_RANGE(lpObj->Map) != 0 && CC_MAP_RANGE(lpTarget->Map) != 0) { damage = (damage*gServerInfo.m_ChaosCastleDamageRate)/100; } else if(IT_MAP_RANGE(lpObj->Map) != 0 && IT_MAP_RANGE(lpTarget->Map) != 0) { damage = (damage*gServerInfo.m_IllusionTempleDamageRate)/100; } #if(GAMESERVER_TYPE==1) else if(gCastleSiege.GetCastleState() == CASTLESIEGE_STATE_STARTSIEGE && lpObj->Map == MAP_CASTLE_SIEGE && lpTarget->Map == MAP_CASTLE_SIEGE) { if(lpObj->CsJoinSide == 0 || lpTarget->CsJoinSide == 0 || lpObj->CsJoinSide != lpTarget->CsJoinSide) { damage = (damage*gServerInfo.m_CastleSiegeDamageRate1)/100; } else { damage = (damage*gServerInfo.m_CastleSiegeDamageRate2)/100; } } #endif } else { damage = (damage*gServerInfo.m_GeneralDamageRatePvM)/100; damage = (damage*gServerInfo.m_DamageRatePvM[lpObj->Class])/100; } } #pragma endregion #pragma region DAMAGE_FINISH if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_MONSTER) { if(lpTarget->Class == 277 || lpTarget->Class == 283) // Castle Gate,Guardian Statue { if(gEffectManager.CheckEffect(lpObj,EFFECT_BLESS_POTION) != 0) { damage += (damage*20)/100; } damage = (damage*gServerInfo.m_CastleSiegeDamageRate3)/100; lpObj->AccumulatedDamage = ((lpObj->AccumulatedDamage>100)?0:(lpObj->AccumulatedDamage+damage)); } } damage = ((damage<0)?0:damage); #pragma endregion #pragma region APPLY_EFFECT if(lpObj->Type == OBJECT_USER && effect != 4) { if((GetLargeRand()%100) < lpObj->OffensiveFullHPRestoreRate) { lpObj->Life = lpObj->MaxLife+lpObj->AddLife; GCLifeSend(lpObj->Index,0xFF,(int)lpObj->Life,lpObj->Shield); } if((GetLargeRand()%100) < lpObj->OffensiveFullSDRestoreRate) { lpObj->Shield = lpObj->MaxShield+lpObj->AddShield; GCLifeSend(lpObj->Index,0xFF,(int)lpObj->Life,lpObj->Shield); } if((GetLargeRand()%100) < lpObj->OffensiveFullMPRestoreRate) { lpObj->Mana = lpObj->MaxMana+lpObj->AddMana; GCManaSend(lpObj->Index,0xFF,(int)lpObj->Mana,lpObj->BP); } if((GetLargeRand()%100) < lpObj->OffensiveFullBPRestoreRate) { lpObj->BP = lpObj->MaxBP+lpObj->AddBP; GCManaSend(lpObj->Index,0xFF,(int)lpObj->Mana,lpObj->BP); } #if(GAMESERVER_UPDATE>=602) if(lpObj->Inventory[0].m_Index >= GET_ITEM(2,0) && lpObj->Inventory[0].m_Index < GET_ITEM(3,0)) { if((GetLargeRand()%100) < (gMasterSkillTree.GetMasterSkillValue(lpObj,MASTER_SKILL_ADD_MACE_MASTERY)-lpTarget->ResistStunRate)) { if(gEffectManager.CheckEffect(lpTarget,EFFECT_IRON_DEFENSE) == 0 && gEffectManager.CheckEffect(lpTarget,EFFECT_IRON_DEFENSE_IMPROVED) == 0) { gEffectManager.AddEffect(lpTarget,0,EFFECT_STERN,2,0,0,0,0); } } } if(lpObj->Inventory[1].m_Index >= GET_ITEM(2,0) && lpObj->Inventory[1].m_Index < GET_ITEM(3,0)) { if((GetLargeRand()%100) < (gMasterSkillTree.GetMasterSkillValue(lpObj,MASTER_SKILL_ADD_MACE_MASTERY)-lpTarget->ResistStunRate)) { if(gEffectManager.CheckEffect(lpTarget,EFFECT_IRON_DEFENSE) == 0 && gEffectManager.CheckEffect(lpTarget,EFFECT_IRON_DEFENSE_IMPROVED) == 0) { gEffectManager.AddEffect(lpTarget,0,EFFECT_STERN,2,0,0,0,0); } } } if(gEffectManager.CheckEffect(lpObj,EFFECT_BLOOD_HOWLING) != 0 || gEffectManager.CheckEffect(lpObj,EFFECT_BLOOD_HOWLING_IMPROVED) != 0) { int rate = gServerInfo.m_BloodHowlingConstA; rate += gMasterSkillTree.GetMasterSkillValue(lpObj,MASTER_SKILL_ADD_BLOOD_HOWLING_IMPROVED); if((GetLargeRand()%100) < rate) { if(gEffectManager.CheckEffect(lpTarget,EFFECT_IRON_DEFENSE) == 0 && gEffectManager.CheckEffect(lpTarget,EFFECT_IRON_DEFENSE_IMPROVED) == 0) { int damage = gServerInfo.m_BloodHowlingConstB; gEffectManager.AddEffect(lpTarget,0,EFFECT_DEATH_STAB_ENHANCED,10,lpObj->Index,1,SET_NUMBERHW(damage),SET_NUMBERLW(damage)); } } } #endif } if(lpSkill != 0 && count <= 1) { if(this->ApplySkillEffect(lpObj,lpTarget,lpSkill,damage) == 0) { if(send != 0) { gSkillManager.GCSkillAttackSend(lpObj,lpSkill->m_index,lpTarget->Index,0); } } else { if(send != 0) { gSkillManager.GCSkillAttackSend(lpObj,lpSkill->m_index,lpTarget->Index,1); } } } #pragma endregion #pragma region DAMAGE_APPLY int ShieldDamage = 0; if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) { ShieldDamage = this->GetShieldDamage(lpObj,lpTarget,damage); if(lpTarget->Life < (damage-ShieldDamage)) { lpTarget->Life = 0; } else { lpTarget->Life -= damage-ShieldDamage; } if(lpTarget->Shield < ShieldDamage) { lpTarget->Shield = 0; } else { lpTarget->Shield -= ShieldDamage; } } else { if(lpTarget->Life < damage) { lpTarget->Life = 0; } else { lpTarget->Life -= damage; } } if(lpTarget->Type == OBJECT_MONSTER) { lpTarget->LastAttackerID = lpObj->Index; gObjAddMsgSendDelay(lpTarget,0,lpObj->Index,100,0); if(lpTarget->CurrentAI != 0) { lpTarget->Agro.IncAgro(lpObj->Index,(damage/50)); } } #pragma endregion #pragma region CHECK_SELF_DEFENSE if(damage > 0) { if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER && lpObj->Index != lpTarget->Index) { bool CheckSelfDefense = 1; if(effect == 4) { CheckSelfDefense = 0; } if(gDuel.CheckDuel(lpObj,lpTarget) != 0) { CheckSelfDefense = 0; } if(gObjGetRelationShip(lpObj,lpTarget) == 2) { CheckSelfDefense = 0; } if(gObjTargetGuildWarCheck(lpObj,lpTarget) != 0) { CheckSelfDefense = 0; } if(gGensSystem.CheckGens(lpObj,lpTarget) != 0) { CheckSelfDefense = 0; } #if(GAMESERVER_TYPE==1) if(lpObj->Map == MAP_CASTLE_SIEGE && gCastleSiege.GetCastleState() == CASTLESIEGE_STATE_STARTSIEGE && lpObj->CsJoinSide != 0) { CheckSelfDefense = 0; } #endif if(CA_MAP_RANGE(lpObj->Map) != 0 && CA_MAP_RANGE(lpTarget->Map) != 0) { CheckSelfDefense = 0; } if(CC_MAP_RANGE(lpObj->Map) != 0 && CC_MAP_RANGE(lpTarget->Map) != 0) { CheckSelfDefense = 0; } if(IT_MAP_RANGE(lpObj->Map) != 0 && IT_MAP_RANGE(lpTarget->Map) != 0) { CheckSelfDefense = 0; } if(gMapManager.GetMapNonOutlaw(lpObj->Map) != 0) { CheckSelfDefense = 0; } if(CheckSelfDefense != 0) { gObjCheckSelfDefense(lpObj,lpTarget->Index); } } this->ArmorDurabilityDown(lpObj,lpTarget); } lpObj->Rest = 0; #pragma endregion #pragma region ATTACK_FINISH if(damage > 0) { gEffectManager.DelEffect(lpTarget,EFFECT_SLEEP); if(effect != 4 && lpTarget->Type == OBJECT_USER) { if((GetLargeRand()%100) < lpTarget->FullDamageReflectRate) { gObjAddMsgSendDelay(lpTarget,10,lpObj->Index,10,damage); } else if((lpTarget->DamageReflect+lpTarget->EffectOption.AddDamageReflect) > 0) { gObjAddMsgSendDelay(lpTarget,10,lpObj->Index,10,((damage*(lpTarget->DamageReflect+lpTarget->EffectOption.AddDamageReflect))/100)); } if((GetLargeRand()%100) < lpTarget->DefensiveFullHPRestoreRate) { lpTarget->Life = lpTarget->MaxLife+lpTarget->AddLife; GCLifeSend(lpTarget->Index,0xFF,(int)lpTarget->Life,lpTarget->Shield); } if((GetLargeRand()%100) < lpTarget->DefensiveFullSDRestoreRate) { lpTarget->Shield = lpTarget->MaxShield+lpTarget->AddShield; GCLifeSend(lpTarget->Index,0xFF,(int)lpTarget->Life,lpTarget->Shield); } if((GetLargeRand()%100) < lpTarget->DefensiveFullMPRestoreRate) { lpTarget->Mana = lpTarget->MaxMana+lpTarget->AddMana; GCManaSend(lpTarget->Index,0xFF,(int)lpTarget->Mana,lpTarget->BP); } if((GetLargeRand()%100) < lpTarget->DefensiveFullBPRestoreRate) { lpTarget->BP = lpTarget->MaxBP+lpTarget->AddBP; GCManaSend(lpTarget->Index,0xFF,(int)lpTarget->Mana,lpTarget->BP); } if(lpTarget->Inventory[8].IsItem() == 0 || (lpTarget->Inventory[8].m_Index != GET_ITEM(13,2) && lpTarget->Inventory[8].m_Index != GET_ITEM(13,3) && lpTarget->Inventory[8].m_Index != GET_ITEM(13,4) && lpTarget->Inventory[8].m_Index != GET_ITEM(13,37))) { if((GetLargeRand()%100) < gServerInfo.m_DamageStuckRate[lpTarget->Class]) { flag = 1; } } } gObjectManager.CharacterLifeCheck(lpObj,lpTarget,(damage-ShieldDamage),0,flag,effect,((lpSkill==0)?0:lpSkill->m_index),ShieldDamage); #if(GAMESERVER_UPDATE>=701) this->AttackElemental(lpObj,lpTarget,lpSkill,send,flag,damage,count,combo); #endif } else { GCDamageSend(lpObj->Index,lpTarget->Index,0,0,effect,0); #if(GAMESERVER_UPDATE>=701) this->AttackElemental(lpObj,lpTarget,lpSkill,send,flag,damage,count,combo); #endif } if(lpObj->Type == OBJECT_USER && lpObj->Life <= 0 && lpObj->CheckLifeTime <= 0) { lpObj->AttackObj = lpTarget; lpObj->AttackerKilled = ((lpTarget->Type==OBJECT_USER)?1:0); lpObj->CheckLifeTime = 3; } #pragma endregion return 1; } bool CAttack::AttackElemental(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,bool send,BYTE flag,int damage,int count,bool combo) // OK { #if(GAMESERVER_UPDATE>=701) #pragma region ATTACK_CHECK if(lpObj->ElementalAttribute == 0) { return 0; } if(lpObj->Type == OBJECT_USER && lpSkill == 0) { return 0; } if(lpObj->Type == OBJECT_USER && (lpObj->Inventory[236].IsItem() == 0 || lpObj->Inventory[236].IsPentagramItem() == 0 || lpObj->Inventory[236].m_IsValidItem == 0)) { return 0; } #pragma endregion #pragma region DAMAGE_CALC flag = 0; BYTE miss = 0; WORD effect = lpObj->ElementalAttribute; if(this->MissCheckElemental(lpObj,lpTarget,lpSkill,send,count,&miss) == 0) { return 1; } int defense = this->GetTargetElementalDefense(lpObj,lpTarget,&effect); damage = this->GetAttackDamageElemental(lpObj,lpTarget,lpSkill,&effect,damage,defense); if(miss != 0) { damage = (damage*30)/100; } if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) { damage -= (damage*lpTarget->PentagramJewelOption.AddElementalDamageReductionPvP)/100; } if(lpObj->Type != OBJECT_USER && lpTarget->Type == OBJECT_USER) { damage -= (damage*lpTarget->PentagramJewelOption.AddElementalDamageReductionPvM)/100; } int MinDamage = (lpObj->Level+lpObj->MasterLevel)/10; MinDamage = ((MinDamage<1)?1:MinDamage); damage = ((damage<MinDamage)?MinDamage:damage); #pragma endregion #pragma region DAMAGE_CONFIG if(lpObj->Type == OBJECT_USER) { if(lpTarget->Type == OBJECT_USER) { damage = (damage*gServerInfo.m_GeneralElementalDamageRatePvP)/100; damage = (damage*gServerInfo.m_ElementalDamageRatePvP[lpObj->Class])/100; damage = (damage*gServerInfo.m_ElementalDamageRateTo[lpObj->Class][lpTarget->Class])/100; if(gDuel.CheckDuel(lpObj,lpTarget) != 0) { damage = (damage*gServerInfo.m_DuelElementalDamageRate)/100; } else if(gGensSystem.CheckGens(lpObj,lpTarget) != 0) { damage = (damage*gServerInfo.m_GensElementalDamageRate)/100; } else if(CA_MAP_RANGE(lpObj->Map) != 0 && CA_MAP_RANGE(lpTarget->Map) != 0) { damage = (damage*gServerInfo.m_CustomArenaElementalDamageRate)/100; } else if(CC_MAP_RANGE(lpObj->Map) != 0 && CC_MAP_RANGE(lpTarget->Map) != 0) { damage = (damage*gServerInfo.m_ChaosCastleElementalDamageRate)/100; } else if(IT_MAP_RANGE(lpObj->Map) != 0 && IT_MAP_RANGE(lpTarget->Map) != 0) { damage = (damage*gServerInfo.m_IllusionTempleElementalDamageRate)/100; } #if(GAMESERVER_TYPE==1) else if(gCastleSiege.GetCastleState() == CASTLESIEGE_STATE_STARTSIEGE && lpObj->Map == MAP_CASTLE_SIEGE && lpTarget->Map == MAP_CASTLE_SIEGE) { if(lpObj->CsJoinSide == 0 || lpTarget->CsJoinSide == 0 || lpObj->CsJoinSide != lpTarget->CsJoinSide) { damage = (damage*gServerInfo.m_CastleSiegeElementalDamageRate1)/100; } else { damage = (damage*gServerInfo.m_CastleSiegeElementalDamageRate2)/100; } } #endif } else { damage = (damage*gServerInfo.m_GeneralElementalDamageRatePvM)/100; damage = (damage*gServerInfo.m_ElementalDamageRatePvM[lpObj->Class])/100; } } #pragma endregion #pragma region APPLY_EFFECT if(lpObj->Type == OBJECT_USER) { if((GetLargeRand()%100) < lpObj->PentagramJewelOption.AddElementalSlowRate) { gEffectManager.AddEffect(lpTarget,0,EFFECT_PENTAGRAM_JEWEL_SLOW,20,0,0,0,0); } if((GetLargeRand()%100) < lpObj->PentagramJewelOption.AddElementalDebuffRate) { switch(lpObj->ElementalAttribute) { case ELEMENTAL_ATTRIBUTE_FIRE: gEffectManager.AddEffect(lpTarget,0,EFFECT_PENTAGRAM_JEWEL_HALF_SD,5,0,0,0,0); break; case ELEMENTAL_ATTRIBUTE_WATER: gEffectManager.AddEffect(lpTarget,0,EFFECT_PENTAGRAM_JEWEL_HALF_MP,5,0,0,0,0); break; case ELEMENTAL_ATTRIBUTE_EARTH: gEffectManager.AddEffect(lpTarget,0,EFFECT_PENTAGRAM_JEWEL_HALF_SPEED,5,0,0,0,0); break; case ELEMENTAL_ATTRIBUTE_WIND: gEffectManager.AddEffect(lpTarget,0,EFFECT_PENTAGRAM_JEWEL_HALF_HP,5,0,0,0,0); break; case ELEMENTAL_ATTRIBUTE_DARK: gEffectManager.AddEffect(lpTarget,0,EFFECT_PENTAGRAM_JEWEL_STUN,5,0,0,0,0); break; } } } #pragma endregion #pragma region DAMAGE_APPLY int ShieldDamage = 0; if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) { ShieldDamage = this->GetShieldDamage(lpObj,lpTarget,damage); if(lpTarget->Life < (damage-ShieldDamage)) { lpTarget->Life = 0; } else { lpTarget->Life -= damage-ShieldDamage; } if(lpTarget->Shield < ShieldDamage) { lpTarget->Shield = 0; } else { lpTarget->Shield -= ShieldDamage; } GCLifeSend(lpTarget->Index,0xFF,(int)lpTarget->Life,lpTarget->Shield); } else { if(lpTarget->Life < damage) { lpTarget->Life = 0; } else { lpTarget->Life -= damage; } } #pragma endregion #pragma region ATTACK_FINISH if(damage > 0) { gObjectManager.CharacterLifeCheck(lpObj,lpTarget,(damage-ShieldDamage),4,flag,effect,((lpSkill==0)?0:lpSkill->m_index),ShieldDamage); } else { GCElementalDamageSend(lpObj->Index,lpTarget->Index,(BYTE)effect,0); } #pragma endregion return 1; #else return 0; #endif } bool CAttack::DecreaseArrow(LPOBJ lpObj) // OK { if(lpObj->Type != OBJECT_USER || lpObj->Class != CLASS_FE) { return 1; } if(gEffectManager.CheckEffect(lpObj,EFFECT_INFINITY_ARROW) != 0 || gEffectManager.CheckEffect(lpObj,EFFECT_INFINITY_ARROW_IMPROVED) != 0) { return 1; } if(lpObj->Inventory[0].m_Index >= GET_ITEM(4,0) && lpObj->Inventory[0].m_Index < GET_ITEM(5,0) && lpObj->Inventory[0].m_Index != GET_ITEM(4,15) && lpObj->Inventory[0].m_Slot == 0) { if(lpObj->Inventory[1].m_Index != GET_ITEM(4,7) || lpObj->Inventory[1].m_Durability < 1) { return 0; } else { gItemManager.DecreaseItemDur(lpObj,1,1); } } if(lpObj->Inventory[1].m_Index >= GET_ITEM(4,0) && lpObj->Inventory[1].m_Index < GET_ITEM(5,0) && lpObj->Inventory[1].m_Index != GET_ITEM(4,7) && lpObj->Inventory[1].m_Slot == 1) { if(lpObj->Inventory[0].m_Index != GET_ITEM(4,15) || lpObj->Inventory[0].m_Durability < 1) { return 0; } else { gItemManager.DecreaseItemDur(lpObj,0,1); } } return 1; } void CAttack::WingSprite(LPOBJ lpObj,LPOBJ lpTarget,int* damage) // OK { if(lpObj != 0 && lpObj->Type == OBJECT_USER) { CItem* lpItem = &lpObj->Inventory[7]; if(lpItem->IsItem() != 0 && lpItem->m_Durability > 0) { if(lpObj->Class == CLASS_DW || lpObj->Class == CLASS_FE || lpObj->Class == CLASS_SU) { lpObj->Life -= 1; } else { lpObj->Life -= 3; } GCLifeSend(lpObj->Index,0xFF,(int)lpObj->Life,lpObj->Shield); if((lpItem->m_Index >= GET_ITEM(12,0) && lpItem->m_Index <= GET_ITEM(12,2)) || lpItem->m_Index == GET_ITEM(12,41)) // 1st wing { (*damage) = ((*damage)*(112+(lpItem->m_Level*2)))/100; } else if((lpItem->m_Index >= GET_ITEM(12,3) && lpItem->m_Index <= GET_ITEM(12,6)) || lpItem->m_Index == GET_ITEM(12,42)) // 2sd wing { (*damage) = ((*damage)*(132+(lpItem->m_Level*1)))/100; } else if((lpItem->m_Index >= GET_ITEM(12,36) && lpItem->m_Index <= GET_ITEM(12,40)) || lpItem->m_Index == GET_ITEM(12,43) || lpItem->m_Index == GET_ITEM(12,50)) // 3rd wing { (*damage) = ((*damage)*(139+(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,49)) // Cloak of Fighter { (*damage) = ((*damage)*(120+(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index >= GET_ITEM(12,130) && lpItem->m_Index <= GET_ITEM(12,135)) // Mini Wings { (*damage) = ((*damage)*(112+(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,262)) // Cloak of Death { (*damage) = ((*damage)*(121+(lpItem->m_Level*1)))/100; } else if(lpItem->m_Index == GET_ITEM(12,263)) // Wings of Chaos { (*damage) = ((*damage)*(133+(lpItem->m_Level*1)))/100; } else if(lpItem->m_Index == GET_ITEM(12,264)) // Wings of Magic { (*damage) = ((*damage)*(135+(lpItem->m_Level*1)))/100; } else if(lpItem->m_Index == GET_ITEM(12,265)) // Wings of Life { (*damage) = ((*damage)*(135+(lpItem->m_Level*1)))/100; } else if(lpItem->m_Index == GET_ITEM(12,266)) // Wings of Conqueror { (*damage) = ((*damage)*(171+(lpItem->m_Level*0)))/100; } else if(lpItem->m_Index == GET_ITEM(12,267)) // Wings of Angel and Devil { (*damage) = ((*damage)*(160+(lpItem->m_Level*1)))/100; } else if(lpItem->m_Index == GET_ITEM(13,30)) // Cloak of Lord { (*damage) = ((*damage)*(120+(lpItem->m_Level*2)))/100; } else if(gCustomWing.CheckCustomWingByItem(lpItem->m_Index) != 0) { (*damage) = ((*damage)*gCustomWing.GetCustomWingIncDamage(lpItem->m_Index,lpItem->m_Level))/100; } } } if(lpTarget != 0 && lpTarget->Type == OBJECT_USER) { CItem* lpItem = &lpTarget->Inventory[7]; if(lpItem->IsItem() != 0 && lpItem->m_Durability > 0) { if((lpItem->m_Index >= GET_ITEM(12,0) && lpItem->m_Index <= GET_ITEM(12,2)) || lpItem->m_Index == GET_ITEM(12,41)) // 1st wing { (*damage) = ((*damage)*(88-(lpItem->m_Level*2)))/100; } else if((lpItem->m_Index >= GET_ITEM(12,3) && lpItem->m_Index <= GET_ITEM(12,6)) || lpItem->m_Index == GET_ITEM(12,42)) // 2sd wing { (*damage) = ((*damage)*(75-(lpItem->m_Level*2)))/100; } else if((lpItem->m_Index >= GET_ITEM(12,36) && lpItem->m_Index <= GET_ITEM(12,39)) || lpItem->m_Index == GET_ITEM(12,43) || lpItem->m_Index == GET_ITEM(12,50)) // 3rd wing { (*damage) = ((*damage)*(61-(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,40)) // Mantle of Monarch { (*damage) = ((*damage)*(76-(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,49)) // Cloak of Fighter { (*damage) = ((*damage)*(90-(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index >= GET_ITEM(12,130) && lpItem->m_Index <= GET_ITEM(12,135)) // Mini Wings { (*damage) = ((*damage)*(88-(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,262)) // Cloak of Death { (*damage) = ((*damage)*(87-(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,263)) // Wings of Chaos { (*damage) = ((*damage)*(70-(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,264)) // Wings of Magic { (*damage) = ((*damage)*(71-(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,265)) // Wings of Life { (*damage) = ((*damage)*(71-(lpItem->m_Level*2)))/100; } else if(lpItem->m_Index == GET_ITEM(12,266)) // Wings of Conqueror { (*damage) = ((*damage)*(29-(lpItem->m_Level*0)))/100; } else if(lpItem->m_Index == GET_ITEM(12,267)) // Wings of Angel and Devil { (*damage) = ((*damage)*(40-(lpItem->m_Level*1)))/100; } else if(lpItem->m_Index == GET_ITEM(13,30)) // Cloak of Lord { (*damage) = ((*damage)*(90-(lpItem->m_Level*1)))/100; } else if(gCustomWing.CheckCustomWingByItem(lpItem->m_Index) != 0) { (*damage) = ((*damage)*gCustomWing.GetCustomWingDecDamage(lpItem->m_Index,lpItem->m_Level))/100; } } } } void CAttack::HelperSprite(LPOBJ lpObj,LPOBJ lpTarget,int* damage) // OK { if(lpObj != 0 && lpObj->Type == OBJECT_USER) { CItem* lpItem = &lpObj->Inventory[8]; if(lpItem->IsItem() != 0 && lpItem->m_Durability > 0) { if(lpItem->m_Index == GET_ITEM(13,1)) // Satan { lpObj->Life -= 3; GCLifeSend(lpObj->Index,0xFF,(int)lpObj->Life,lpObj->Shield); (*damage) = ((*damage)*(100+gServerInfo.m_SatanIncDamageConstA))/100; } else if(lpItem->m_Index == GET_ITEM(13,3)) // Dinorant { lpObj->Life -= 1; GCLifeSend(lpObj->Index,0xFF,(int)lpObj->Life,lpObj->Shield); (*damage) = ((*damage)*(100+gServerInfo.m_DinorantIncDamageConstA))/100; } else if(lpItem->m_Index == GET_ITEM(13,37)) // Fenrir { if((lpItem->m_NewOption & 1) != 0) { (*damage) = ((*damage)*(100+gServerInfo.m_BlackFenrirIncDamageConstA))/100; } } else if(lpItem->m_Index == GET_ITEM(13,64)) // Demon { lpObj->Life -= 4; GCLifeSend(lpObj->Index,0xFF,(int)lpObj->Life,lpObj->Shield); (*damage) = ((*damage)*(100+gServerInfo.m_DemonIncDamageConstA))/100; } else if(lpItem->m_Index == GET_ITEM(13,123)) // Skeleton { lpObj->Life -= 2; GCLifeSend(lpObj->Index,0xFF,(int)lpObj->Life,lpObj->Shield); (*damage) = ((*damage)*(100+gServerInfo.m_SkeletonIncDamageConstA))/100; } } } if(lpTarget != 0 && lpTarget->Type == OBJECT_USER) { CItem* lpItem = &lpTarget->Inventory[8]; if(lpItem->IsItem() != 0 && lpItem->m_Durability > 0) { if(lpItem->m_Index == GET_ITEM(13,0)) // Angel { (*damage) = ((*damage)*(100-gServerInfo.m_AngelDecDamageConstA))/100; } else if(lpItem->m_Index == GET_ITEM(13,3)) // Dinorant { (*damage) = ((*damage)*(100-gServerInfo.m_DinorantDecDamageConstA-(((lpItem->m_NewOption & 1)==0)?0:gServerInfo.m_DinorantDecDamageConstB)))/100; } else if(lpItem->m_Index == GET_ITEM(13,4)) // Dark Horse { (*damage) = ((*damage)*(100-((gServerInfo.m_DarkHorseDecDamageConstA+lpItem->m_PetItemLevel)/gServerInfo.m_DarkHorseDecDamageConstB)))/100; } else if(lpItem->m_Index == GET_ITEM(13,37)) // Fenrir { if((lpItem->m_NewOption & 2) != 0) { (*damage) = ((*damage)*(100-gServerInfo.m_BlueFenrirDecDamageConstA))/100; } } else if(lpItem->m_Index == GET_ITEM(13,65)) // Maria { (*damage) = ((*damage)*(100-gServerInfo.m_MariaDecDamageConstA))/100; } } } } void CAttack::DamageSprite(LPOBJ lpObj,int damage) // OK { if(lpObj->Type != OBJECT_USER) { return; } CItem* lpItem = &lpObj->Inventory[8]; if(lpItem->IsItem() == 0 || lpItem->m_IsPeriodicItem != 0) { return; } float DurabilityValue = (1.0f/gServerInfo.m_GuardianDurabilityRate)*100; DurabilityValue = (DurabilityValue/lpObj->GuardianDurabilityRate)*100; if(lpItem->m_Index == GET_ITEM(13,0)) // Angel { lpItem->m_Durability -= (damage*(3.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,1)) // Satan { lpItem->m_Durability -= (damage*(2.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,2)) // Uniria { lpItem->m_Durability -= (damage*(1.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,3)) // Dinorant { lpItem->m_Durability -= (damage*(1.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,4)) // Dark Horse { if(this->DarkHorseSprite(lpObj,damage) == 0) { return; } } else if(lpItem->m_Index == GET_ITEM(13,37)) // Fenrir { if(this->FenrirSprite(lpObj,damage) == 0) { return; } } else if(lpItem->m_Index == GET_ITEM(13,64)) // Demon { lpItem->m_Durability -= (damage*(1.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,65)) // Maria { lpItem->m_Durability -= (damage*(2.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,67)) // Rudolf { lpItem->m_Durability -= (damage*(1.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,80)) // Panda { lpItem->m_Durability -= (damage*(1.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,106)) // Unicorn { lpItem->m_Durability -= (damage*(1.0f*DurabilityValue))/100; } else if(lpItem->m_Index == GET_ITEM(13,123)) // Skeleton { lpItem->m_Durability -= (damage*(1.0f*DurabilityValue))/100; } else { return; } gItemManager.GCItemDurSend(lpObj->Index,8,(BYTE)lpItem->m_Durability,0); if(lpItem->m_Durability < 1) { gItemManager.InventoryDelItem(lpObj->Index,8); gItemManager.GCItemDeleteSend(lpObj->Index,8,0); gObjectManager.CharacterMakePreviewCharSet(lpObj->Index); gItemManager.GCItemChangeSend(lpObj->Index,8); if(lpObj->Map == MAP_ICARUS && lpObj->Inventory[7].IsItem() == 0 && (lpItem->m_Index == GET_ITEM(13,3) || lpItem->m_Index == GET_ITEM(13,37))) { gObjMoveGate(lpObj->Index,22); } } } bool CAttack::DarkHorseSprite(LPOBJ lpObj,int damage) // OK { CItem* lpItem = &lpObj->Inventory[8]; if(lpItem->m_Durability < 1) { return 0; } lpItem->m_DurabilitySmall += ((damage*2)/100)+1; int MaxSmallDur = (1500*gServerInfo.m_PetDurabilityRate)/100; MaxSmallDur = (MaxSmallDur*lpObj->PetDurabilityRate)/100; if(lpItem->m_DurabilitySmall > MaxSmallDur) { lpItem->m_Durability = (((--lpItem->m_Durability)<1)?0:lpItem->m_Durability); lpItem->m_DurabilitySmall = 0; if(lpItem->CheckDurabilityState() != 0) { gObjectManager.CharacterCalcAttribute(lpObj->Index); } gItemManager.GCItemDurSend(lpObj->Index,8,(BYTE)lpItem->m_Durability,0); GCPetItemInfoSend(lpObj->Index,1,0,8,lpItem->m_PetItemLevel,lpItem->m_PetItemExp,(BYTE)lpItem->m_Durability); } return 0; } bool CAttack::FenrirSprite(LPOBJ lpObj,int damage) // OK { CItem* lpItem = &lpObj->Inventory[8]; if(lpItem->m_Durability < 1) { return 0; } lpItem->m_DurabilitySmall += ((damage*2)/100)+1; int MaxSmallDur = (200*gServerInfo.m_GuardianDurabilityRate)/100; MaxSmallDur = (MaxSmallDur*lpObj->GuardianDurabilityRate)/100; if(lpItem->m_DurabilitySmall > MaxSmallDur) { lpItem->m_Durability = (((--lpItem->m_Durability)<1)?0:lpItem->m_Durability); lpItem->m_DurabilitySmall = 0; if(lpItem->CheckDurabilityState() != 0) { gObjectManager.CharacterCalcAttribute(lpObj->Index); } gItemManager.GCItemDurSend(lpObj->Index,8,(BYTE)lpItem->m_Durability,0); } return 1; } void CAttack::WeaponDurabilityDown(LPOBJ lpObj,LPOBJ lpTarget) // OK { if(lpObj->Type != OBJECT_USER) { return; } if(gEffectManager.GetEffect(lpObj,EFFECT_TALISMAN_OF_PROTECTION) != 0) { return; } for(int n=0;n < 2;n++) { if(lpObj->Inventory[n].IsItem() != 0) { bool result = 0; switch((lpObj->Inventory[n].m_Index/MAX_ITEM_TYPE)) { case 0: result = lpObj->Inventory[n].WeaponDurabilityDown(lpObj->Index,lpTarget->Defense,0); break; case 1: result = lpObj->Inventory[n].WeaponDurabilityDown(lpObj->Index,lpTarget->Defense,0); break; case 2: result = lpObj->Inventory[n].WeaponDurabilityDown(lpObj->Index,lpTarget->Defense,0); break; case 3: result = lpObj->Inventory[n].WeaponDurabilityDown(lpObj->Index,lpTarget->Defense,0); break; case 4: result = lpObj->Inventory[n].WeaponDurabilityDown(lpObj->Index,lpTarget->Defense,1); break; case 5: result = lpObj->Inventory[n].WeaponDurabilityDown(lpObj->Index,lpTarget->Defense,((lpObj->Inventory[n].m_Slot==0)?2:3)); break; } if(result != 0) { gItemManager.GCItemDurSend(lpObj->Index,n,(BYTE)lpObj->Inventory[n].m_Durability,0); } } } } void CAttack::ArmorDurabilityDown(LPOBJ lpObj,LPOBJ lpTarget) // OK { if(lpTarget->Type != OBJECT_USER) { return; } if(gEffectManager.GetEffect(lpTarget,EFFECT_TALISMAN_OF_PROTECTION) != 0) { return; } int slot = 1+(GetLargeRand()%6); if(lpTarget->Inventory[slot].IsItem() != 0) { if(slot != 1 || (lpTarget->Inventory[slot].m_Index >= GET_ITEM(6,0) && lpTarget->Inventory[slot].m_Index < GET_ITEM(7,0))) { if(lpTarget->Inventory[slot].ArmorDurabilityDown(lpTarget->Index,lpObj->PhysiDamageMin) != 0) { gItemManager.GCItemDurSend(lpTarget->Index,slot,(BYTE)lpTarget->Inventory[slot].m_Durability,0); } } } } bool CAttack::CheckPlayerTarget(LPOBJ lpObj,LPOBJ lpTarget) // OK { if(lpObj->Type != OBJECT_USER || lpTarget->Type != OBJECT_USER) { return 1; } if(lpTarget->Authority == 32) { return 0; } if(lpObj->HelperDelayTime != 0 && gParty.IsMember(lpObj->PartyNumber,lpTarget->Index) != 0) { return 0; } if(gObjGetRelationShip(lpObj,lpTarget) == 2 && gMapManager.GetMapNonPK(lpTarget->Map) == 0) { return 1; } if(lpObj->Guild != 0 && lpTarget->Guild != 0) { if(lpObj->Guild->WarState != 0 && lpTarget->Guild->WarState != 0) { if(lpObj->Guild->Number == lpTarget->Guild->Number) { return 0; } } } if(gObjTargetGuildWarCheck(lpObj,lpTarget) == 0) { if(lpTarget->Guild != 0 && lpTarget->Guild->WarState != 0) { if(lpTarget->Guild->WarType == 1 && lpTarget->Map != MAP_ARENA && gMapManager.GetMapNonPK(lpTarget->Map) == 0) { return 1; } if(CA_MAP_RANGE(lpTarget->Map) == 0 && CC_MAP_RANGE(lpTarget->Map) == 0 && IT_MAP_RANGE(lpTarget->Map) == 0 && gDuel.CheckDuel(lpObj,lpTarget) == 0 && gGensSystem.CheckGens(lpObj,lpTarget) == 0) { return 0; } } } if(gDuel.CheckDuel(lpObj,lpTarget) == 0 && OBJECT_RANGE(lpTarget->DuelUser) != 0) { return 0; } if(gMapManager.GetMapGensBattle(lpObj->Map) != 0 && gMapManager.GetMapGensBattle(lpTarget->Map) != 0) { return ((gMapManager.GetMapNonPK(lpTarget->Map)==0)?gGensSystem.CheckGens(lpObj,lpTarget):0); } if(CA_MAP_RANGE(lpObj->Map) != 0 && CA_MAP_RANGE(lpTarget->Map) != 0) { return ((gCustomArena.CheckPlayerTarget(lpObj,lpTarget)==0)?0:1); } if(DS_MAP_RANGE(lpObj->Map) != 0 && DS_MAP_RANGE(lpTarget->Map) != 0) { return 0; } if(BC_MAP_RANGE(lpObj->Map) != 0 && BC_MAP_RANGE(lpTarget->Map) != 0) { return 0; } if(CC_MAP_RANGE(lpObj->Map) != 0 && CC_MAP_RANGE(lpTarget->Map) != 0) { return ((gChaosCastle.GetState(GET_CC_LEVEL(lpObj->Map))==CC_STATE_START)?1:0); } #if(GAMESERVER_TYPE==1) if(lpObj->Map == MAP_CASTLE_SIEGE && lpTarget->Map == MAP_CASTLE_SIEGE) { if(gCastleSiege.GetCastleState() == CASTLESIEGE_STATE_STARTSIEGE) { if(lpObj->CsJoinSide != 0 && lpTarget->CsJoinSide != 0) { if(gServerInfo.m_CastleSiegeDamageRate2 == 0 && lpObj->CsJoinSide == lpTarget->CsJoinSide) { return 0; } else { return 1; } } } } #endif if(lpObj->Map == MAP_KANTURU3 && lpTarget->Map == MAP_KANTURU3) { return 0; } if(IT_MAP_RANGE(lpObj->Map) != 0 && IT_MAP_RANGE(lpTarget->Map) != 0) { return gIllusionTemple.CheckPlayerTarget(lpObj,lpTarget); } if(lpObj->Map == MAP_RAKLION2 && lpTarget->Map == MAP_RAKLION2) { return 0; } if(DG_MAP_RANGE(lpObj->Map) != 0 && DG_MAP_RANGE(lpTarget->Map) != 0) { return 0; } if(IG_MAP_RANGE(lpObj->Map) != 0 && IG_MAP_RANGE(lpTarget->Map) != 0) { return 0; } if(lpObj->Level <= 5 || lpTarget->Level <= 5) { return 0; } if(gMapManager.GetMapNonPK(lpTarget->Map) != 0) { return 0; } return 1; } void CAttack::MissSend(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,int send,int count) // OK { WORD effect = 0; if(count > 0 && lpSkill != 0 && (lpSkill->m_skill == SKILL_UPPER_BEAST || lpSkill->m_skill == SKILL_DARK_SIDE)) { effect |= (((count%2)==0)?0x20:0x10); } if(count > 0 && lpSkill != 0 && (lpSkill->m_skill == SKILL_LARGE_RING_BLOWER || lpSkill->m_skill == SKILL_CHAIN_DRIVER || lpSkill->m_skill == SKILL_DRAGON_LORE || lpSkill->m_skill == SKILL_PHOENIX_SHOT)) { effect |= (((count%4)==0)?0x20:0x10); } GCDamageSend(lpObj->Index,lpTarget->Index,0,0,effect,0); if(send != 0 && lpSkill != 0) { gSkillManager.GCSkillAttackSend(lpObj,lpSkill->m_index,lpTarget->Index,0); } } bool CAttack::MissCheck(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,int send,int count,BYTE* miss) // OK { int AttackSuccessRate = lpObj->AttackSuccessRate; AttackSuccessRate += lpObj->EffectOption.AddAttackSuccessRate; AttackSuccessRate += (AttackSuccessRate*lpObj->EffectOption.MulAttackSuccessRate)/100; AttackSuccessRate -= (AttackSuccessRate*lpObj->EffectOption.DivAttackSuccessRate)/100; AttackSuccessRate = ((AttackSuccessRate<0)?0:AttackSuccessRate); int DefenseSuccessRate = lpTarget->DefenseSuccessRate; DefenseSuccessRate += lpTarget->EffectOption.AddDefenseSuccessRate; DefenseSuccessRate += (DefenseSuccessRate*lpTarget->EffectOption.MulDefenseSuccessRate)/100; DefenseSuccessRate -= (DefenseSuccessRate*lpTarget->EffectOption.DivDefenseSuccessRate)/100; DefenseSuccessRate = ((DefenseSuccessRate<0)?0:DefenseSuccessRate); if(AttackSuccessRate < DefenseSuccessRate) { (*miss) = 1; if((GetLargeRand()%100) >= 5) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 0; } } else { (*miss) = 0; if((GetLargeRand()%((AttackSuccessRate==0)?1:AttackSuccessRate)) < DefenseSuccessRate) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); return 0; } } return 1; } bool CAttack::MissCheckPvP(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,int send,int count,BYTE* miss) // OK { (*miss) = 0; int AttackSuccessRate = (int)(((100*(((lpObj->AttackSuccessRatePvP*10000.0f)/(lpObj->AttackSuccessRatePvP+lpTarget->DefenseSuccessRatePvP))/10000.0f))*gServerInfo.m_ShieldGaugeAttackRate)*(((lpObj->Level*10000.0f)/(lpObj->Level+lpTarget->Level))/10000.0f)); if((lpTarget->Level-lpObj->Level) >= 100) { AttackSuccessRate -= 5; } else if((lpTarget->Level-lpObj->Level) >= 200) { AttackSuccessRate -= 10; } else if((lpTarget->Level-lpObj->Level) >= 300) { AttackSuccessRate -= 15; } if((GetLargeRand()%100) > AttackSuccessRate) { this->MissSend(lpObj,lpTarget,lpSkill,send,count); if(gServerInfo.m_ShieldGaugeAttackComboMiss != 0 && lpObj->ComboSkill.m_index >= 0) { lpObj->ComboSkill.Init(); } return 0; } return 1; } bool CAttack::MissCheckElemental(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,int send,int count,BYTE* miss) // OK { #if(GAMESERVER_UPDATE>=701) int ElementalAttackSuccessRate = lpObj->ElementalAttackSuccessRate; if(lpObj->Type == OBJECT_USER) { ElementalAttackSuccessRate += (ElementalAttackSuccessRate*lpObj->PentagramOption.MulElementalAttackSuccessRate)/100; ElementalAttackSuccessRate += (ElementalAttackSuccessRate*lpObj->PentagramJewelOption.MulElementalAttackSuccessRate)/100; ElementalAttackSuccessRate = ((ElementalAttackSuccessRate<0)?0:ElementalAttackSuccessRate); } int ElementalDefenseSuccessRate = lpTarget->ElementalDefenseSuccessRate; if(lpTarget->Type == OBJECT_USER) { ElementalDefenseSuccessRate += (ElementalDefenseSuccessRate*lpTarget->PentagramOption.MulElementalDefenseSuccessRate)/100; ElementalDefenseSuccessRate += (ElementalDefenseSuccessRate*lpTarget->PentagramJewelOption.MulElementalDefenseSuccessRate)/100; ElementalDefenseSuccessRate = ((ElementalDefenseSuccessRate<0)?0:ElementalDefenseSuccessRate); } if(ElementalAttackSuccessRate < ElementalDefenseSuccessRate) { (*miss) = 1; if((GetLargeRand()%100) >= 5) { GCElementalDamageSend(lpObj->Index,lpTarget->Index,lpObj->ElementalAttribute,0); return 0; } } else { (*miss) = 0; if((GetLargeRand()%((ElementalAttackSuccessRate==0)?1:ElementalAttackSuccessRate)) < ElementalDefenseSuccessRate) { GCElementalDamageSend(lpObj->Index,lpTarget->Index,lpObj->ElementalAttribute,0); return 0; } } return 1; #else return 0; #endif } bool CAttack::ApplySkillEffect(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,int damage) // OK { if(lpTarget->Type != OBJECT_USER && ((lpTarget->Class >= 204 && lpTarget->Class <= 209) || (lpTarget->Class >= 215 && lpTarget->Class <= 219) || lpTarget->Class == 277 || lpTarget->Class == 278 || lpTarget->Class == 283 || lpTarget->Class == 288)) { return 0; } if(lpTarget->Type == OBJECT_USER && (gEffectManager.CheckEffect(lpTarget,EFFECT_IRON_DEFENSE) != 0 || gEffectManager.CheckEffect(lpTarget,EFFECT_IRON_DEFENSE_IMPROVED) != 0)) { return 0; } if(gSkillManager.GetSkillType(lpSkill->m_index) != -1 && gObjCheckResistance(lpTarget,gSkillManager.GetSkillType(lpSkill->m_index)) != 0) { return 0; } switch(lpSkill->m_skill) { case SKILL_POISON: gEffectManager.AddEffect(lpTarget,0,gSkillManager.GetSkillEffect(lpSkill->m_index),20,lpObj->Index,2,3,0); break; case SKILL_METEORITE: gSkillManager.ApplyMeteoriteEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_LIGHTNING: gObjAddMsgSendDelay(lpTarget,2,lpObj->Index,150,0); break; case SKILL_ICE: gEffectManager.AddEffect(lpTarget,0,gSkillManager.GetSkillEffect(lpSkill->m_index),10,0,0,0,0); break; case SKILL_FALLING_SLASH: gObjAddMsgSendDelay(lpTarget,2,lpObj->Index,150,0); break; case SKILL_LUNGE: gObjAddMsgSendDelay(lpTarget,2,lpObj->Index,150,0); break; case SKILL_UPPERCUT: gObjAddMsgSendDelay(lpTarget,2,lpObj->Index,150,0); break; case SKILL_CYCLONE: gObjAddMsgSendDelay(lpTarget,2,lpObj->Index,150,0); break; case SKILL_SLASH: gObjAddMsgSendDelay(lpTarget,2,lpObj->Index,150,0); break; case SKILL_DECAY: gEffectManager.AddEffect(lpTarget,0,gSkillManager.GetSkillEffect(lpSkill->m_index),10,lpObj->Index,2,3,0); break; case SKILL_ICE_STORM: gSkillManager.ApplyIceStormEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_ICE_ARROW: gEffectManager.AddEffect(lpTarget,0,gSkillManager.GetSkillEffect(lpSkill->m_index),7,0,0,0,0); break; case SKILL_TWISTING_SLASH: gSkillManager.ApplyTwistingSlashEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_RAGEFUL_BLOW: gSkillManager.ApplyRagefulBlowEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_DEATH_STAB: gSkillManager.ApplyDeathStabEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_FIRE_SLASH: gSkillManager.ApplyFireSlashEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_FIRE_BURST: gSkillManager.ApplyFireBurstEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_PLASMA_STORM: gSkillManager.ApplyPlasmaStormEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_FIRE_SCREAM: gSkillManager.ApplyFireScreamEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_EARTHQUAKE: gSkillManager.ApplyEarthquakeEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_DRAIN_LIFE: gSkillManager.ApplyDrainLifeEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_SAHAMUTT: gSkillManager.ApplySahamuttEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_NEIL: gSkillManager.ApplyNeilEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_GHOST_PHANTOM: gSkillManager.ApplyGhostPhantomEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_RED_STORM: gEffectManager.AddEffect(lpTarget,0,gSkillManager.GetSkillEffect(lpSkill->m_index),1,0,0,0,0); break; case SKILL_FROZEN_STAB: gSkillManager.ApplyFrozenStabEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_FIVE_SHOT: gSkillManager.ApplyFiveShotEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_SWORD_SLASH: gSkillManager.ApplySwordSlashEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_LIGHTNING_STORM: gEffectManager.AddEffect(lpTarget,0,gSkillManager.GetSkillEffect(lpSkill->m_index),1,0,0,0,0); break; case SKILL_LARGE_RING_BLOWER: gSkillManager.ApplyLargeRingBlowerEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_UPPER_BEAST: gSkillManager.ApplyUpperBeastEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_CHAIN_DRIVER: gSkillManager.ApplyChainDriverEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_DRAGON_LORE: gSkillManager.ApplyDragonLoreEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_DRAGON_SLAYER: gSkillManager.ApplyDragonSlayerEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_PHOENIX_SHOT: gSkillManager.ApplyPhoenixShotEffect(lpObj,lpTarget,lpSkill,damage); break; case SKILL_POISON_ARROW: gEffectManager.AddEffect(lpTarget,0,gSkillManager.GetSkillEffect(lpSkill->m_index),10,lpObj->Index,2,3,0); break; case SKILL_EARTH_PRISON: gSkillManager.ApplyEarthPrisonEffect(lpObj,lpTarget,lpSkill,damage); break; } return 1; } int CAttack::GetTargetDefense(LPOBJ lpObj,LPOBJ lpTarget,WORD* effect) // OK { int defense = lpTarget->Defense; defense += lpTarget->EffectOption.AddDefense; defense -= lpTarget->EffectOption.SubDefense; gSkillManager.SkillSwordPowerGetDefense(lpObj->Index,&defense); if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) { defense += lpTarget->DefensePvP; } if(lpTarget->MonsterSkillElementOption.CheckDefenseTime() != 0) { defense += lpTarget->MonsterSkillElementOption.m_SkillElementDefense; } if(lpTarget->EffectOption.MulDefense > 0) { defense += (defense*lpTarget->EffectOption.MulDefense)/100; } if(lpTarget->EffectOption.DivDefense > 0) { defense -= (defense*lpTarget->EffectOption.DivDefense)/100; } if(lpTarget->Type == OBJECT_USER) { defense = (defense*50)/100; } if((GetLargeRand()%100) < ((lpObj->IgnoreDefenseRate+lpObj->EffectOption.AddIgnoreDefenseRate)-lpTarget->ResistIgnoreDefenseRate)) { (*effect) = 1; defense = 0; } defense = ((defense<0)?0:defense); return defense; } int CAttack::GetTargetElementalDefense(LPOBJ lpObj,LPOBJ lpTarget,WORD* effect) // OK { #if(GAMESERVER_UPDATE>=701) int defense = lpTarget->ElementalDefense; if(lpTarget->Type == OBJECT_USER) { defense += (((lpTarget->Inventory[236].IsItem()==0)?0:lpTarget->Inventory[236].m_Defense)*lpTarget->PentagramOption.MulPentagramDefense)/100; defense += (lpTarget->Defense*lpTarget->PentagramOption.AddElementalDefenseTransferRate)/100; defense += lpTarget->PentagramJewelOption.AddElementalDefense; if(lpObj->Type == OBJECT_USER) { defense += lpTarget->PentagramJewelOption.AddElementalDefensePvP; if(lpObj->Class == CLASS_DW || lpObj->Class == CLASS_FE || lpObj->Class == CLASS_MG || lpObj->Class == CLASS_SU) { defense += lpTarget->PentagramJewelOption.AddElementalDefenseRange; } else { defense += lpTarget->PentagramJewelOption.AddElementalDefenseMelee; } } else { defense += lpTarget->PentagramJewelOption.AddElementalDefensePvM; } } gPentagramSystem.GetPentagramRelationshipDefense(lpTarget,lpObj,&defense); defense = ((defense<0)?0:defense); return defense; #else return 0; #endif } int CAttack::GetAttackDamage(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,WORD* effect,int TargetDefense) // OK { CItem* Right = &lpObj->Inventory[0]; CItem* Left = &lpObj->Inventory[1]; int damage = 0; int DamageMin = 0; int DamageMax = 0; int SkillDamageMin = 0; int SkillDamageMax = 0; bool DualHandWeapon = 0; if(lpObj->Type == OBJECT_MONSTER || lpObj->Type == OBJECT_NPC) { DamageMin = lpObj->PhysiDamageMin; DamageMax = lpObj->PhysiDamageMax; DamageMin += lpObj->EffectOption.AddPhysiDamage; DamageMax += lpObj->EffectOption.AddPhysiDamage; DamageMin += lpObj->EffectOption.AddMinPhysiDamage; DamageMax += lpObj->EffectOption.AddMaxPhysiDamage; DamageMin += (DamageMin*lpObj->EffectOption.MulPhysiDamage)/100; DamageMax += (DamageMax*lpObj->EffectOption.MulPhysiDamage)/100; DamageMin -= (DamageMin*lpObj->EffectOption.DivPhysiDamage)/100; DamageMax -= (DamageMax*lpObj->EffectOption.DivPhysiDamage)/100; int range = (DamageMax-DamageMin); range = ((range<1)?1:range); damage = DamageMin+(GetLargeRand()%range); } else { if(lpObj->Class == CLASS_DK || lpObj->Class == CLASS_MG || lpObj->Class == CLASS_DL || lpObj->Class == CLASS_RF) { if(Right->m_Index >= GET_ITEM(0,0) && Right->m_Index < GET_ITEM(4,0) && Left->m_Index >= GET_ITEM(0,0) && Left->m_Index < GET_ITEM(4,0)) { if(Right->m_IsValidItem != 0 && Left->m_IsValidItem != 0) { DualHandWeapon = 1; } } } if(lpSkill != 0) { SkillDamageMin = lpSkill->m_DamageMin; SkillDamageMax = lpSkill->m_DamageMax; SkillDamageMin += gMasterSkillTree.GetMasterSkillDamageMin(lpObj,lpSkill->m_skill); SkillDamageMax += gMasterSkillTree.GetMasterSkillDamageMax(lpObj,lpSkill->m_skill); SkillDamageMin += lpObj->SkillDamageBonus; SkillDamageMax += lpObj->SkillDamageBonus; int type = gSkillManager.GetSkillType(lpSkill->m_index); if(CHECK_RANGE(type,MAX_RESISTANCE_TYPE) != 0) { SkillDamageMin += lpObj->AddResistance[type]; SkillDamageMax += lpObj->AddResistance[type]; } if(lpObj->Class == CLASS_DL) { switch(lpSkill->m_skill) { case SKILL_EARTHQUAKE: SkillDamageMin += ((lpObj->Strength+lpObj->AddStrength)/gServerInfo.m_EarthquakeDamageConstA)+((lpObj->Leadership+lpObj->AddLeadership)/gServerInfo.m_EarthquakeDamageConstB)+(lpObj->Inventory[8].m_PetItemLevel*gServerInfo.m_EarthquakeDamageConstC); SkillDamageMax += ((lpObj->Strength+lpObj->AddStrength)/gServerInfo.m_EarthquakeDamageConstA)+((lpObj->Leadership+lpObj->AddLeadership)/gServerInfo.m_EarthquakeDamageConstB)+(lpObj->Inventory[8].m_PetItemLevel*gServerInfo.m_EarthquakeDamageConstC); break; case SKILL_ELECTRIC_SPARK: SkillDamageMin += ((lpObj->Leadership+lpObj->AddLeadership)/gServerInfo.m_ElectricSparkDamageConstA)+gServerInfo.m_ElectricSparkDamageConstB; SkillDamageMax += ((lpObj->Leadership+lpObj->AddLeadership)/gServerInfo.m_ElectricSparkDamageConstA)+gServerInfo.m_ElectricSparkDamageConstB; break; default: SkillDamageMin += ((lpObj->Strength+lpObj->AddStrength)/gServerInfo.m_DLSkillDamageConstA)+((lpObj->Energy+lpObj->AddEnergy)/gServerInfo.m_DLSkillDamageConstB); SkillDamageMax += ((lpObj->Strength+lpObj->AddStrength)/gServerInfo.m_DLSkillDamageConstA)+((lpObj->Energy+lpObj->AddEnergy)/gServerInfo.m_DLSkillDamageConstB); break; } } } if(DualHandWeapon != 0) { DamageMin = lpObj->PhysiDamageMinRight+lpObj->PhysiDamageMinLeft+SkillDamageMin; DamageMax = lpObj->PhysiDamageMaxRight+lpObj->PhysiDamageMaxLeft+SkillDamageMax; } else if((Right->m_Index >= GET_ITEM(0,0) && Right->m_Index < GET_ITEM(4,0)) || (Right->m_Index >= GET_ITEM(5,0) && Right->m_Index < GET_ITEM(6,0))) { DamageMin = lpObj->PhysiDamageMinRight+SkillDamageMin; DamageMax = lpObj->PhysiDamageMaxRight+SkillDamageMax; } else if(Right->m_Index >= GET_ITEM(4,0) && Right->m_Index < GET_ITEM(5,0) && Right->m_Index != GET_ITEM(4,15) && Right->m_Slot == 0) { DamageMin = lpObj->PhysiDamageMinRight+SkillDamageMin; DamageMax = lpObj->PhysiDamageMaxRight+SkillDamageMax; } else if(Left->m_Index >= GET_ITEM(4,0) && Left->m_Index < GET_ITEM(5,0) && Left->m_Index != GET_ITEM(4,7) && Left->m_Slot == 1) { DamageMin = lpObj->PhysiDamageMinLeft+SkillDamageMin; DamageMax = lpObj->PhysiDamageMaxLeft+SkillDamageMax; } else { DamageMin = lpObj->PhysiDamageMinLeft+SkillDamageMin; DamageMax = lpObj->PhysiDamageMaxLeft+SkillDamageMax; } DamageMin += lpObj->EffectOption.AddPhysiDamage; DamageMax += lpObj->EffectOption.AddPhysiDamage; DamageMin += lpObj->EffectOption.AddMinPhysiDamage; DamageMax += lpObj->EffectOption.AddMaxPhysiDamage; gSkillManager.SkillSwordPowerGetPhysiDamage(lpObj->Index,&DamageMin,&DamageMax); DamageMin += (DamageMin*lpObj->EffectOption.MulPhysiDamage)/100; DamageMax += (DamageMax*lpObj->EffectOption.MulPhysiDamage)/100; DamageMin -= (DamageMin*lpObj->EffectOption.DivPhysiDamage)/100; DamageMax -= (DamageMax*lpObj->EffectOption.DivPhysiDamage)/100; int range = (DamageMax-DamageMin); range = ((range<1)?1:range); damage = DamageMin+(GetLargeRand()%range); if((GetLargeRand()%100) < ((lpObj->CriticalDamageRate+lpObj->EffectOption.AddCriticalDamageRate)-lpTarget->ResistCriticalDamageRate)) { (*effect) = 3; damage = DamageMax; damage += lpObj->CriticalDamage; damage += lpObj->EffectOption.AddCriticalDamage; } if((GetLargeRand()%100) < ((lpObj->ExcellentDamageRate+lpObj->EffectOption.AddExcellentDamageRate)-lpTarget->ResistExcellentDamageRate)) { (*effect) = 2; damage = (DamageMax*120)/100; damage += lpObj->ExcellentDamage; damage += lpObj->EffectOption.AddExcellentDamage; } } if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) { damage += lpObj->DamagePvP; } if(lpObj->MonsterSkillElementOption.CheckAttackTime() != 0) { damage += lpObj->MonsterSkillElementOption.m_SkillElementAttack; } damage -= TargetDefense; damage = ((damage<0)?0:damage); return damage; } int CAttack::GetAttackDamageWizard(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,WORD* effect,int TargetDefense) // OK { CItem* Right = &lpObj->Inventory[0]; CItem* Left = &lpObj->Inventory[1]; int DamageMin = lpObj->MagicDamageMin; int DamageMax = lpObj->MagicDamageMax; if(lpSkill->m_skill == SKILL_NOVA && lpObj->SkillNovaCount >= 0) { DamageMin += (gServerInfo.m_NovaDamageConstA*(lpObj->SkillNovaCount*gServerInfo.m_NovaDamageConstB))+((lpObj->Strength+lpObj->AddStrength)/gServerInfo.m_NovaDamageConstC); DamageMax += (gServerInfo.m_NovaDamageConstA*(lpObj->SkillNovaCount*gServerInfo.m_NovaDamageConstB))+((lpObj->Strength+lpObj->AddStrength)/gServerInfo.m_NovaDamageConstC); } else { DamageMin += lpSkill->m_DamageMin; DamageMax += lpSkill->m_DamageMax; } DamageMin += gMasterSkillTree.GetMasterSkillDamageMin(lpObj,lpSkill->m_skill); DamageMax += gMasterSkillTree.GetMasterSkillDamageMax(lpObj,lpSkill->m_skill); DamageMin += lpObj->SkillDamageBonus; DamageMax += lpObj->SkillDamageBonus; DamageMin += lpObj->EffectOption.AddMagicDamage; DamageMax += lpObj->EffectOption.AddMagicDamage; DamageMin += lpObj->EffectOption.AddMinMagicDamage; DamageMax += lpObj->EffectOption.AddMaxMagicDamage; gSkillManager.SkillSwordPowerGetMagicDamage(lpObj->Index,&DamageMin,&DamageMax); int type = gSkillManager.GetSkillType(lpSkill->m_index); if(CHECK_RANGE(type,MAX_RESISTANCE_TYPE) != 0) { DamageMin += lpObj->AddResistance[type]; DamageMax += lpObj->AddResistance[type]; } DamageMin += (DamageMin*lpObj->EffectOption.MulMagicDamage)/100; DamageMax += (DamageMax*lpObj->EffectOption.MulMagicDamage)/100; DamageMin -= (DamageMin*lpObj->EffectOption.DivMagicDamage)/100; DamageMax -= (DamageMax*lpObj->EffectOption.DivMagicDamage)/100; if(Right->IsItem() != 0 && Right->m_IsValidItem != 0 && ((Right->m_Index >= GET_ITEM(0,0) && Right->m_Index < GET_ITEM(1,0)) || (Right->m_Index >= GET_ITEM(5,0) && Right->m_Index < GET_ITEM(6,0)))) { int rise = (int)(((Right->m_MagicDamageRate/2)+(Right->m_Level*2))*Right->m_CurrentDurabilityState); DamageMin += (DamageMin*rise)/100; DamageMax += (DamageMax*rise)/100; } int range = (DamageMax-DamageMin); range = ((range<1)?1:range); int damage = DamageMin+(GetLargeRand()%range); if((GetLargeRand()%100) < ((lpObj->CriticalDamageRate+lpObj->EffectOption.AddCriticalDamageRate)-lpTarget->ResistCriticalDamageRate)) { (*effect) = 3; damage = DamageMax; damage += lpObj->CriticalDamage; damage += lpObj->EffectOption.AddCriticalDamage; } if((GetLargeRand()%100) < ((lpObj->ExcellentDamageRate+lpObj->EffectOption.AddExcellentDamageRate)-lpTarget->ResistExcellentDamageRate)) { (*effect) = 2; damage = (DamageMax*120)/100; damage += lpObj->ExcellentDamage; damage += lpObj->EffectOption.AddExcellentDamage; } if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) { damage += lpObj->DamagePvP; } damage -= TargetDefense; damage = ((damage<0)?0:damage); return damage; } int CAttack::GetAttackDamageCursed(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,WORD* effect,int TargetDefense) // OK { CItem* Right = &lpObj->Inventory[0]; CItem* Left = &lpObj->Inventory[1]; int DamageMin = lpObj->CurseDamageMin; int DamageMax = lpObj->CurseDamageMax; DamageMin += lpSkill->m_DamageMin; DamageMax += lpSkill->m_DamageMax; DamageMin += gMasterSkillTree.GetMasterSkillDamageMin(lpObj,lpSkill->m_skill); DamageMax += gMasterSkillTree.GetMasterSkillDamageMax(lpObj,lpSkill->m_skill); DamageMin += lpObj->SkillDamageBonus; DamageMax += lpObj->SkillDamageBonus; DamageMin += lpObj->EffectOption.AddCurseDamage; DamageMax += lpObj->EffectOption.AddCurseDamage; DamageMin += lpObj->EffectOption.AddMinCurseDamage; DamageMax += lpObj->EffectOption.AddMaxCurseDamage; gSkillManager.SkillSwordPowerGetCurseDamage(lpObj->Index,&DamageMin,&DamageMax); int type = gSkillManager.GetSkillType(lpSkill->m_index); if(CHECK_RANGE(type,MAX_RESISTANCE_TYPE) != 0) { DamageMin += lpObj->AddResistance[type]; DamageMax += lpObj->AddResistance[type]; } DamageMin += (DamageMin*lpObj->EffectOption.MulCurseDamage)/100; DamageMax += (DamageMax*lpObj->EffectOption.MulCurseDamage)/100; DamageMin -= (DamageMin*lpObj->EffectOption.DivCurseDamage)/100; DamageMax -= (DamageMax*lpObj->EffectOption.DivCurseDamage)/100; if(Left->IsItem() != 0 && Left->m_IsValidItem != 0 && Left->m_Index >= GET_ITEM(5,21) && Left->m_Index <= GET_ITEM(5,23)) { int rise = (int)(((Left->m_MagicDamageRate/2)+(Left->m_Level*2))*Left->m_CurrentDurabilityState); DamageMin += (DamageMin*rise)/100; DamageMax += (DamageMax*rise)/100; } int range = (DamageMax-DamageMin); range = ((range<1)?1:range); int damage = DamageMin+(GetLargeRand()%range); if((GetLargeRand()%100) < ((lpObj->CriticalDamageRate+lpObj->EffectOption.AddCriticalDamageRate)-lpTarget->ResistCriticalDamageRate)) { (*effect) = 3; damage = DamageMax; damage += lpObj->CriticalDamage; damage += lpObj->EffectOption.AddCriticalDamage; } if((GetLargeRand()%100) < ((lpObj->ExcellentDamageRate+lpObj->EffectOption.AddExcellentDamageRate)-lpTarget->ResistExcellentDamageRate)) { (*effect) = 2; damage = (DamageMax*120)/100; damage += lpObj->ExcellentDamage; damage += lpObj->EffectOption.AddExcellentDamage; } if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) { damage += lpObj->DamagePvP; } damage -= TargetDefense; damage = ((damage<0)?0:damage); return damage; } int CAttack::GetAttackDamageFenrir(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,WORD* effect,int TargetDefense) // OK { int BaseDamage = 0; if(lpObj->Class == CLASS_DW) { BaseDamage = (lpObj->Strength/gServerInfo.m_DWPlasmaStormDamageConstA)+(lpObj->Dexterity/gServerInfo.m_DWPlasmaStormDamageConstB)+(lpObj->Vitality/gServerInfo.m_DWPlasmaStormDamageConstC)+(lpObj->Energy/gServerInfo.m_DWPlasmaStormDamageConstD); } else if(lpObj->Class == CLASS_DK) { BaseDamage = (lpObj->Strength/gServerInfo.m_DKPlasmaStormDamageConstA)+(lpObj->Dexterity/gServerInfo.m_DKPlasmaStormDamageConstB)+(lpObj->Vitality/gServerInfo.m_DKPlasmaStormDamageConstC)+(lpObj->Energy/gServerInfo.m_DKPlasmaStormDamageConstD); } else if(lpObj->Class == CLASS_FE) { BaseDamage = (lpObj->Strength/gServerInfo.m_FEPlasmaStormDamageConstA)+(lpObj->Dexterity/gServerInfo.m_FEPlasmaStormDamageConstB)+(lpObj->Vitality/gServerInfo.m_FEPlasmaStormDamageConstC)+(lpObj->Energy/gServerInfo.m_FEPlasmaStormDamageConstD); } else if(lpObj->Class == CLASS_MG) { BaseDamage = (lpObj->Strength/gServerInfo.m_MGPlasmaStormDamageConstA)+(lpObj->Dexterity/gServerInfo.m_MGPlasmaStormDamageConstB)+(lpObj->Vitality/gServerInfo.m_MGPlasmaStormDamageConstC)+(lpObj->Energy/gServerInfo.m_MGPlasmaStormDamageConstD); } else if(lpObj->Class == CLASS_DL) { BaseDamage = (lpObj->Strength/gServerInfo.m_DLPlasmaStormDamageConstA)+(lpObj->Dexterity/gServerInfo.m_DLPlasmaStormDamageConstB)+(lpObj->Vitality/gServerInfo.m_DLPlasmaStormDamageConstC)+(lpObj->Energy/gServerInfo.m_DLPlasmaStormDamageConstD)+(lpObj->Leadership/gServerInfo.m_DLPlasmaStormDamageConstE); } else if(lpObj->Class == CLASS_SU) { BaseDamage = (lpObj->Strength/gServerInfo.m_SUPlasmaStormDamageConstA)+(lpObj->Dexterity/gServerInfo.m_SUPlasmaStormDamageConstB)+(lpObj->Vitality/gServerInfo.m_SUPlasmaStormDamageConstC)+(lpObj->Energy/gServerInfo.m_SUPlasmaStormDamageConstD); } else if(lpObj->Class == CLASS_RF) { BaseDamage = (lpObj->Strength/gServerInfo.m_RFPlasmaStormDamageConstA)+(lpObj->Dexterity/gServerInfo.m_RFPlasmaStormDamageConstB)+(lpObj->Vitality/gServerInfo.m_RFPlasmaStormDamageConstC)+(lpObj->Energy/gServerInfo.m_RFPlasmaStormDamageConstD); } int range = (lpSkill->m_DamageMax-lpSkill->m_DamageMin); range = ((range<1)?1:range); int damage = (BaseDamage+lpSkill->m_DamageMin)+(GetLargeRand()%range); if((GetLargeRand()%100) < ((lpObj->CriticalDamageRate+lpObj->EffectOption.AddCriticalDamageRate)-lpTarget->ResistCriticalDamageRate)) { (*effect) = 3; damage = (BaseDamage+lpSkill->m_DamageMax); damage += lpObj->CriticalDamage; damage += lpObj->EffectOption.AddCriticalDamage; } if((GetLargeRand()%100) < ((lpObj->ExcellentDamageRate+lpObj->EffectOption.AddExcellentDamageRate)-lpTarget->ResistExcellentDamageRate)) { (*effect) = 2; damage = ((BaseDamage+lpSkill->m_DamageMax)*120)/100; damage += lpObj->ExcellentDamage; damage += lpObj->EffectOption.AddExcellentDamage; } if(lpObj->Type == OBJECT_USER && lpTarget->Type == OBJECT_USER) { damage += lpObj->DamagePvP; } damage -= TargetDefense; damage = ((damage<0)?0:damage); return damage; } int CAttack::GetAttackDamageElemental(LPOBJ lpObj,LPOBJ lpTarget,CSkill* lpSkill,WORD* effect,int AttackDamage,int TargetDefense) // OK { #if(GAMESERVER_UPDATE>=701) int DamageMin = lpObj->ElementalDamageMin; int DamageMax = lpObj->ElementalDamageMax; if(lpObj->Type == OBJECT_USER) { DamageMin += (((lpObj->Inventory[236].IsItem()==0)?0:lpObj->Inventory[236].m_DamageMin)*lpObj->PentagramOption.MulPentagramDamage)/100; DamageMax += (((lpObj->Inventory[236].IsItem()==0)?0:lpObj->Inventory[236].m_DamageMax)*lpObj->PentagramOption.MulPentagramDamage)/100; DamageMin += (AttackDamage*lpObj->PentagramOption.AddElementalAttackTransferRate)/100; DamageMax += (AttackDamage*lpObj->PentagramOption.AddElementalAttackTransferRate)/100; DamageMin += lpObj->PentagramJewelOption.AddElementalDamage; DamageMax += lpObj->PentagramJewelOption.AddElementalDamage; if(lpTarget->Type == OBJECT_USER) { DamageMin += lpObj->PentagramJewelOption.AddElementalDamagePvP; DamageMax += lpObj->PentagramJewelOption.AddElementalDamagePvP; if(lpTarget->Class == CLASS_DW || lpTarget->Class == CLASS_FE || lpTarget->Class == CLASS_MG || lpTarget->Class == CLASS_SU) { DamageMin += lpObj->PentagramJewelOption.AddElementalDamageRange; DamageMax += lpObj->PentagramJewelOption.AddElementalDamageRange; } else { DamageMin += lpObj->PentagramJewelOption.AddElementalDamageMelee; DamageMax += lpObj->PentagramJewelOption.AddElementalDamageMelee; } DamageMin += (DamageMin*lpTarget->PentagramJewelOption.MulElementalDamagePvP)/100; DamageMax += (DamageMax*lpTarget->PentagramJewelOption.MulElementalDamagePvP)/100; } else { DamageMin += lpObj->PentagramJewelOption.AddElementalDamagePvM; DamageMax += lpObj->PentagramJewelOption.AddElementalDamagePvM; DamageMin += (DamageMin*lpTarget->PentagramJewelOption.MulElementalDamagePvM)/100; DamageMax += (DamageMax*lpTarget->PentagramJewelOption.MulElementalDamagePvM)/100; } } int range = (DamageMax-DamageMin); range = ((range<1)?1:range); int damage = DamageMin+(GetLargeRand()%range); if((GetLargeRand()%100) < (lpObj->PentagramOption.AddElementalCriticalDamageRate+((lpTarget->Type==OBJECT_USER)?lpObj->PentagramJewelOption.AddElementalCriticalDamageRatePvP:lpObj->PentagramJewelOption.AddElementalCriticalDamageRatePvM))) { (*effect) = 6; damage = DamageMax; } if((GetLargeRand()%100) < ((lpTarget->Type==OBJECT_USER)?lpObj->PentagramJewelOption.AddElementalExcellentDamageRatePvP:lpObj->PentagramJewelOption.AddElementalExcellentDamageRatePvM)) { (*effect) = 7; damage = (DamageMax*120)/100; } gPentagramSystem.GetPentagramRelationshipDamage(lpObj,lpTarget,&damage); damage -= TargetDefense; damage = ((damage<0)?0:damage); return damage; #else return 0; #endif } int CAttack::GetShieldDamage(LPOBJ lpObj,LPOBJ lpTarget,int damage) // OK { int rate = lpTarget->ShieldGaugeRate; if((GetLargeRand()%100) < ((lpObj->IgnoreShieldGaugeRate)-lpTarget->ResistIgnoreShieldGaugeRate)) { rate = 0; } else { rate -= lpObj->DecreaseShieldGaugeRate; } rate = ((rate<0)?0:((rate>100)?100:rate)); int SDDamage = (damage*rate)/100; int HPDamage = damage-SDDamage; if(lpTarget->Shield < SDDamage) { HPDamage = HPDamage+(SDDamage-lpTarget->Shield); SDDamage = lpTarget->Shield; if(lpTarget->Shield > 0 && HPDamage > (((lpTarget->MaxLife+lpTarget->AddLife)*20)/100)) { if(CC_MAP_RANGE(lpTarget->Map) == 0 || IT_MAP_RANGE(lpTarget->Map) == 0) { GCEffectInfoSend(lpTarget->Index,17); } } } return SDDamage; } void CAttack::GetPreviewDefense(LPOBJ lpObj,DWORD* defense) // OK { (*defense) = lpObj->Defense; (*defense) += lpObj->EffectOption.AddDefense; (*defense) -= lpObj->EffectOption.SubDefense; gSkillManager.SkillSwordPowerGetDefense(lpObj->Index,(int*)defense); (*defense) += ((*defense)*lpObj->EffectOption.MulDefense)/100; (*defense) -= ((*defense)*lpObj->EffectOption.DivDefense)/100; } void CAttack::GetPreviewPhysiDamage(LPOBJ lpObj,DWORD* DamageMin,DWORD* DamageMax,DWORD* MulDamage,DWORD* DivDamage) // OK { CItem* Right = &lpObj->Inventory[0]; CItem* Left = &lpObj->Inventory[1]; bool DualHandWeapon = 0; if(lpObj->Class == CLASS_DK || lpObj->Class == CLASS_MG || lpObj->Class == CLASS_DL || lpObj->Class == CLASS_RF) { if(Right->m_Index >= GET_ITEM(0,0) && Right->m_Index < GET_ITEM(4,0) && Left->m_Index >= GET_ITEM(0,0) && Left->m_Index < GET_ITEM(4,0)) { if(Right->m_IsValidItem != 0 && Left->m_IsValidItem != 0) { DualHandWeapon = 1; } } } if(DualHandWeapon != 0) { (*DamageMin) = lpObj->PhysiDamageMinRight+lpObj->PhysiDamageMinLeft; (*DamageMax) = lpObj->PhysiDamageMaxRight+lpObj->PhysiDamageMaxLeft; } else if((Right->m_Index >= GET_ITEM(0,0) && Right->m_Index < GET_ITEM(4,0)) || (Right->m_Index >= GET_ITEM(5,0) && Right->m_Index < GET_ITEM(6,0))) { (*DamageMin) = lpObj->PhysiDamageMinRight; (*DamageMax) = lpObj->PhysiDamageMaxRight; } else if(Right->m_Index >= GET_ITEM(4,0) && Right->m_Index < GET_ITEM(5,0) && Right->m_Index != GET_ITEM(4,15) && Right->m_Slot == 0) { (*DamageMin) = lpObj->PhysiDamageMinRight; (*DamageMax) = lpObj->PhysiDamageMaxRight; } else if(Left->m_Index >= GET_ITEM(4,0) && Left->m_Index < GET_ITEM(5,0) && Left->m_Index != GET_ITEM(4,7) && Left->m_Slot == 1) { (*DamageMin) = lpObj->PhysiDamageMinLeft; (*DamageMax) = lpObj->PhysiDamageMaxLeft; } else { (*DamageMin) = lpObj->PhysiDamageMinLeft; (*DamageMax) = lpObj->PhysiDamageMaxLeft; } (*DamageMin) += lpObj->EffectOption.AddPhysiDamage; (*DamageMax) += lpObj->EffectOption.AddPhysiDamage; (*DamageMin) += lpObj->EffectOption.AddMinPhysiDamage; (*DamageMax) += lpObj->EffectOption.AddMaxPhysiDamage; gSkillManager.SkillSwordPowerGetPhysiDamage(lpObj->Index,(int*)DamageMin,(int*)DamageMax); (*MulDamage) = lpObj->EffectOption.MulPhysiDamage; (*DivDamage) = lpObj->EffectOption.DivPhysiDamage; } void CAttack::GetPreviewMagicDamage(LPOBJ lpObj,DWORD* DamageMin,DWORD* DamageMax,DWORD* MulDamage,DWORD* DivDamage,DWORD* DamageRate) // OK { CItem* Right = &lpObj->Inventory[0]; CItem* Left = &lpObj->Inventory[1]; (*DamageMin) = lpObj->MagicDamageMin; (*DamageMax) = lpObj->MagicDamageMax; (*DamageMin) += lpObj->EffectOption.AddMagicDamage; (*DamageMax) += lpObj->EffectOption.AddMagicDamage; (*DamageMin) += lpObj->EffectOption.AddMinMagicDamage; (*DamageMax) += lpObj->EffectOption.AddMaxMagicDamage; gSkillManager.SkillSwordPowerGetMagicDamage(lpObj->Index,(int*)DamageMin,(int*)DamageMax); (*MulDamage) = lpObj->EffectOption.MulMagicDamage; (*DivDamage) = lpObj->EffectOption.DivMagicDamage; if(Right->IsItem() != 0 && Right->m_IsValidItem != 0 && ((Right->m_Index >= GET_ITEM(0,0) && Right->m_Index < GET_ITEM(1,0)) || (Right->m_Index >= GET_ITEM(5,0) && Right->m_Index < GET_ITEM(6,0)))) { (*DamageRate) = (int)(((Right->m_MagicDamageRate/2)+(Right->m_Level*2))*Right->m_CurrentDurabilityState); } else { (*DamageRate) = 0; } } void CAttack::GetPreviewCurseDamage(LPOBJ lpObj,DWORD* DamageMin,DWORD* DamageMax,DWORD* MulDamage,DWORD* DivDamage,DWORD* DamageRate) // OK { CItem* Right = &lpObj->Inventory[0]; CItem* Left = &lpObj->Inventory[1]; (*DamageMin) = lpObj->CurseDamageMin; (*DamageMax) = lpObj->CurseDamageMax; (*DamageMin) += lpObj->EffectOption.AddCurseDamage; (*DamageMax) += lpObj->EffectOption.AddCurseDamage; (*DamageMin) += lpObj->EffectOption.AddMinCurseDamage; (*DamageMax) += lpObj->EffectOption.AddMaxCurseDamage; gSkillManager.SkillSwordPowerGetCurseDamage(lpObj->Index,(int*)DamageMin,(int*)DamageMax); (*MulDamage) = lpObj->EffectOption.MulCurseDamage; (*DivDamage) = lpObj->EffectOption.DivCurseDamage; if(Left->IsItem() != 0 && Left->m_IsValidItem != 0 && Left->m_Index >= GET_ITEM(5,21) && Left->m_Index <= GET_ITEM(5,23)) { (*DamageRate) = (int)(((Left->m_MagicDamageRate/2)+(Left->m_Level*2))*Left->m_CurrentDurabilityState); } else { (*DamageRate) = 0; } } void CAttack::GetPreviewDamageMultiplier(LPOBJ lpObj,DWORD* DamageMultiplier,DWORD* RFDamageMultiplierA,DWORD* RFDamageMultiplierB,DWORD* RFDamageMultiplierC) // OK { switch(lpObj->Class) { case CLASS_DW: (*DamageMultiplier) = 200; (*RFDamageMultiplierA) = 100; (*RFDamageMultiplierB) = 100; (*RFDamageMultiplierC) = 100; break; case CLASS_DK: (*DamageMultiplier) = lpObj->DKDamageMultiplierRate; (*RFDamageMultiplierA) = 100; (*RFDamageMultiplierB) = 100; (*RFDamageMultiplierC) = 100; break; case CLASS_FE: (*DamageMultiplier) = 200; (*RFDamageMultiplierA) = 100; (*RFDamageMultiplierB) = 100; (*RFDamageMultiplierC) = 100; break; case CLASS_MG: (*DamageMultiplier) = 200; (*RFDamageMultiplierA) = 100; (*RFDamageMultiplierB) = 100; (*RFDamageMultiplierC) = 100; break; case CLASS_DL: (*DamageMultiplier) = lpObj->DLDamageMultiplierRate; (*RFDamageMultiplierA) = 100; (*RFDamageMultiplierB) = 100; (*RFDamageMultiplierC) = 100; break; case CLASS_SU: (*DamageMultiplier) = 200; (*RFDamageMultiplierA) = 100; (*RFDamageMultiplierB) = 100; (*RFDamageMultiplierC) = 100; break; case CLASS_RF: (*DamageMultiplier) = 200; (*RFDamageMultiplierA) = lpObj->RFDamageMultiplierRate[0]; (*RFDamageMultiplierB) = lpObj->RFDamageMultiplierRate[1]; (*RFDamageMultiplierC) = lpObj->RFDamageMultiplierRate[2]; break; } } void CAttack::CGAttackRecv(PMSG_ATTACK_RECV* lpMsg,int aIndex) // OK { LPOBJ lpObj = &gObj[aIndex]; if(gObjIsConnected(aIndex) == 0) { return; } int bIndex = MAKE_NUMBERW(lpMsg->index[0],lpMsg->index[1]); if(OBJECT_RANGE(bIndex) == 0) { return; } LPOBJ lpTarget = &gObj[bIndex]; if(lpTarget->Live == 0) { return; } if(lpObj->Map != lpTarget->Map) { return; } #if(GAMESERVER_UPDATE>=402) if(gDuel.GetDuelArenaBySpectator(aIndex) != 0 || gDuel.GetDuelArenaBySpectator(bIndex) != 0) { return; } #endif if(gMap[lpObj->Map].CheckAttr(lpObj->X,lpObj->Y,1) != 0 || gMap[lpTarget->Map].CheckAttr(lpTarget->X,lpTarget->Y,1) != 0) { return; } if(lpObj->Type == OBJECT_USER && sqrt(pow(((float)lpObj->X-(float)lpTarget->X),2)+pow(((float)lpObj->Y-(float)lpTarget->Y),2)) > ((lpObj->Class==CLASS_FE)?6:3)) { return; } lpObj->Dir = lpMsg->dir; lpObj->MultiSkillIndex = 0; lpObj->MultiSkillCount = 0; GCActionSend(lpObj,lpMsg->action,aIndex,bIndex); lpObj->ComboSkill.Init(); this->Attack(lpObj,lpTarget,0,0,0,0,0,0); }
[ "ptr0x@live.com" ]
ptr0x@live.com
680ce5c57e8b1e4d009c838ecec145a98f7c973e
c952a9dfde3ee42f919db607e05b06166ac5e0b9
/codeforces/1512/E.cpp
5429d52519176dceca7337727b00334ea6b06e75
[]
no_license
ntloi95/Codeforces
1afaa753e3c84752907fb2e8bb79b0d1fc4e1a1b
3fab8d5a0d00cafc74e392f1db6ee20b9e68d1d1
refs/heads/master
2023-05-23T17:51:47.532503
2021-06-26T07:59:47
2021-06-26T07:59:47
335,175,316
0
0
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
#include <bits/stdc++.h> #define ll long long #define ii pair<int, int> #define fi first #define se second #define multitest \ int t; \ cin >> t; \ while (t--) using namespace std; const int N = 50; int main() { ios::sync_with_stdio(false); multitest { int n, l, r, s; cin >> n >> l >> r >> s; int sz = r - l + 1; int down = sz * (sz + 1) / 2; int up = n * (n + 1) / 2 - ((n - sz) * (n - sz + 1)) / 2; if (s < down || s > up) { cout << -1 << endl; continue; } vector<int> v(sz); for (int i = 0; i < sz; i++) { v[i] = i + 1; } int cur = down; int id = sz - 1; int limitId = n; while (cur != s) { v[id]++; cur++; if (v[id] == limitId) { id--; limitId--; } } map<int, bool> hash; for (int i = 0; i < sz; i++) { hash[v[i]] = true; } vector<int> remain; for (int i = 1; i <= n; i++) { if (!hash[i]) { remain.push_back(i); } } int it = 0; for (; it < l - 1; it++) { cout << remain[it] << ' '; } for (int i = 0; i < sz; i++) { cout << v[i] << ' '; } for (; it < remain.size(); it++) { cout << remain[it] << ' '; } cout << endl; } return 0; }
[ "ntloi95@gmail.com" ]
ntloi95@gmail.com
1438d0bcbcbae4f570a08c51c01fedbb935a0a6d
75acc74e3c0a3105c713829af7231073140dd263
/cppsrc/StarQuant/Data/tickwriter.h
295df802e86d8876bfe6e1b37de6756435fd833b
[ "Apache-2.0" ]
permissive
yssource/starquant
6333913ff58ba9470ed7eb7accf0f76ee3c40182
ab20c8ee23397f33258df8c6f29f8377ce5d3688
refs/heads/master
2020-05-04T17:42:40.691854
2019-04-03T15:25:31
2019-04-03T15:25:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,462
h
#ifndef __StarQuant_Data_TickWriter_H__ #define __StarQuant_Data_TickWriter_H__ #include <condition_variable> #include <mutex> #include <Common/config.h> #include <Common/timeutil.h> #include <Common/getRealTime.h> #include <bson.h> #include <bson/bcon.h> #include <mongoc.h> #include <time.h> using std::mutex; ////////////////////////////////////////////////////////////////////////// // tick recorder ////////////////////////////////////////////////////////////////////////// namespace StarQuant { struct TickWriter { int bufSize; FILE* fp = nullptr; int count = 0; //length of string in the buffer char* head = nullptr; // = raiibuf.get(); // mongodb writer //mongoc_client_t *client; //mongoc_database_t *database; //mongoc_collection_t *collection; //bson_t *command, reply, *insert; bson_error_t error; mongoc_client_pool_t *pool; mongoc_uri_t *uri; TickWriter() { bufSize = 1024; head = new char[bufSize]; mongoc_init (); uri = mongoc_uri_new("mongodb://localhost:27017"); pool = mongoc_client_pool_new(uri); //client = mongoc_client_new ("mongodb://localhost:27017"); //database = mongoc_client_get_database (client, "findata"); } ~TickWriter() { if (fp) { fwrite(head, sizeof(char), count, fp); fflush(fp); fclose(fp); } delete[] head; // mongoc_collection_destroy (collection); // mongoc_database_destroy (database); // mongoc_client_destroy (client); mongoc_client_pool_destroy(pool); mongoc_uri_destroy(uri); mongoc_cleanup (); } void put(const string& _str) { if (!_str.empty()) { char tmp[512] = {}; //sprintf(tmp, "%lu@%s\n", getMicroTime(), _str.c_str()); sprintf(tmp, "%s @%s\n", ymdhmsf().c_str(), _str.c_str()); uint32_t strsize = strlen(tmp); // + 1; uint32_t required_buffer_len = count + strsize; if (required_buffer_len > bufSize) { size_t r = fwrite(head, sizeof(char), count, fp); //printf("write files\n"); if (r == count) { memcpy(head, tmp, strsize * sizeof(char)); count = strsize; fflush(fp); return; } else { //error //http://www.cplusplus.com/reference/cstdio/fwrite/ } } memcpy(head + count, tmp, strsize * sizeof(char)); count = required_buffer_len; } } void insertdb(const string& _str){ if (!_str.empty()) { vector<string> vs = stringsplit(_str, SERIALIZATION_SEPARATOR); if ((MSG_TYPE)(atoi(vs[0].c_str())) == MSG_TYPE::MSG_TYPE_TICK_L1) { vector<string> fullsym = stringsplit(vs[1], ' '); string collectionname = fullsym[2]; mongoc_client_t *client = mongoc_client_pool_pop(pool); mongoc_collection_t *collection = mongoc_client_get_collection (client, "findata", collectionname.c_str()); bson_t *doc = bson_new(); BSON_APPEND_UTF8(doc, "contractno", fullsym[3].c_str()); BSON_APPEND_DATE_TIME(doc, "datetime", string2unixtimems(vs[2])+8*3600000); BSON_APPEND_DOUBLE(doc, "price", atof(vs[3].c_str())); BSON_APPEND_INT32(doc, "size", atoi(vs[4].c_str())); BSON_APPEND_DOUBLE(doc, "bidprice1", atof(vs[5].c_str())); BSON_APPEND_INT32(doc, "bidsize1", atoi(vs[6].c_str())); BSON_APPEND_DOUBLE(doc, "askprice1", atof(vs[7].c_str())); BSON_APPEND_INT32(doc, "asksize1", atoi(vs[8].c_str())); BSON_APPEND_INT32(doc, "openinterest", atoi(vs[9].c_str())); BSON_APPEND_INT32(doc, "dominant", 0); // BSON_APPEND_DOUBLE(doc, "upperLimit", atof(vs[14].c_str())); // BSON_APPEND_DOUBLE(doc, "lowerLimit", atof(vs[15].c_str())); // 将bson文档插入到集合 if (!mongoc_collection_insert(collection, MONGOC_INSERT_NONE, doc, NULL, &error)) { fprintf(stderr, "Count failed: %s\n", error.message); } bson_destroy(doc); mongoc_collection_destroy(collection); mongoc_client_pool_push(pool, client); } else if ((MSG_TYPE)(atoi(vs[0].c_str())) == MSG_TYPE::MSG_TYPE_TICK_L5){ // Tick_L5 k; // k.fullsymbol_ = vs[1]; // k.time_ = vs[2]; // k.price_ = atof(vs[3].c_str()); // k.size_ = atoi(vs[4].c_str()); // k.depth_ = 5; // k.bidprice_L1_ = atoi(vs[5].c_str()); // k.bidsize_L1_ = atoi(vs[6].c_str()); // k.askprice_L1_ = atoi(vs[7].c_str()); // k.asksize_L1_ = atoi(vs[8].c_str()); // k.bidprice_L2_ = atoi(vs[9].c_str()); // k.bidsize_L2_ = atoi(vs[10].c_str()); // k.askprice_L2_ = atoi(vs[11].c_str()); // k.asksize_L2_ = atoi(vs[12].c_str()); // k.bidprice_L3_ = atoi(vs[13].c_str()); // k.bidsize_L3_ = atoi(vs[14].c_str()); // k.askprice_L3_ = atoi(vs[15].c_str()); // k.asksize_L3_ = atoi(vs[16].c_str()); // k.bidprice_L4_ = atoi(vs[17].c_str()); // k.bidsize_L4_ = atoi(vs[18].c_str()); // k.askprice_L4_ = atoi(vs[19].c_str()); // k.asksize_L4_ = atoi(vs[20].c_str()); // k.bidprice_L5_ = atoi(vs[21].c_str()); // k.bidsize_L5_ = atoi(vs[22].c_str()); // k.askprice_L5_ = atoi(vs[23].c_str()); // k.asksize_L5_ = atoi(vs[24].c_str()); // k.open_interest = atoi(vs[25].c_str()); // k.open_ = atoi(vs[26].c_str()); // k.high_ = atoi(vs[27].c_str()); // k.low_ = atoi(vs[28].c_str()); // k.pre_close_ = atoi(vs[29].c_str()); // k.upper_limit_price_ = atoi(vs[30].c_str()); // k.lower_limit_price_ = atoi(vs[31].c_str()); } } } }; } #endif
[ "dr.wb@qq.com" ]
dr.wb@qq.com
796e2ddb789eddd15b8ec360552c21d217fa5d98
47b1e487d9bd5a228e106062b0647e6a7609b346
/Schemes/DDRCore/xdiv-test.cpp
a2443f81fc344144beffc4c673ddf6ca20a8087e
[]
no_license
aespadotto/HHO-PACS
c73f3a6f822b5a875a88a5686eb091bd30d26488
fdf81f45041927c64e0b05c550e62a42d7af27de
refs/heads/master
2023-07-18T05:09:15.846236
2021-08-25T13:17:21
2021-08-25T13:17:21
399,245,757
0
0
null
null
null
null
UTF-8
C++
false
false
5,521
cpp
// Author: Daniele Di Pietro (daniele.di-pietro@umontpellier.fr) #include <iostream> #include <fstream> #include <iomanip> #include <boost/math/constants/constants.hpp> #include <boost/program_options.hpp> #include <boost/timer/timer.hpp> #include <mesh.hpp> #include <mesh_builder.hpp> #include <xdiv.hpp> #include <parallel_for.hpp> #include "xdiv-test.hpp" #define FORMAT(W) \ std::setiosflags(std::ios_base::left) << std::setw(W) << std::setfill(' ') using namespace HArDCore3D; //------------------------------------------------------------------------------ // Mesh filenames //------------------------------------------------------------------------------ const std::string mesh_dir = "../../meshes/"; std::string default_mesh = mesh_dir + "Voro-small-0/RF_fmt/voro-2"; std::string default_meshtype = "RF"; //------------------------------------------------------------------------------ int main(int argc, const char* argv[]) { // Program options boost::program_options::options_description desc("Allowed options"); desc.add_options() ("help,h", "Display this help message") ("mesh,m", boost::program_options::value<std::string>(), "Set the mesh") ("meshtype,t", boost::program_options::value<std::string>(), "Set the mesh type (TG,MSH,RF)") ("degree,k", boost::program_options::value<size_t>()->default_value(1), "The polynomial degree of the sequence") ("pthread,p", boost::program_options::value<bool>()->default_value(true), "Use thread-based parallelism") ("function,f", boost::program_options::value<int>()->default_value(0), "Select the function to interpolate"); boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); // Display the help options if (vm.count("help")) { std::cout << desc << std::endl; return 0; } // Select the mesh std::string mesh_file = (vm.count("mesh") ? vm["mesh"].as<std::string>() : default_mesh); std::string mesh_type = (vm.count("meshtype") ? vm["meshtype"].as<std::string>() : default_meshtype); std::cout << FORMAT(25) << "[main] Mesh file" << mesh_file << std::endl; // Select the degree size_t K = vm["degree"].as<size_t>(); std::cout << FORMAT(25) << "[main] Degree" << K << std::endl; // Build the mesh MeshBuilder meshbuilder = MeshBuilder(mesh_file, mesh_type); std::unique_ptr<Mesh> mesh_ptr = meshbuilder.build_the_mesh(); // Create DDR core bool use_threads = (vm.count("pthread") ? vm["pthread"].as<bool>() : true); std::cout << "[main] " << (use_threads ? "Parallel execution" : "Sequential execution") << std:: endl; DDRCore ddr_core(*mesh_ptr, K, use_threads); // Create XDiv XDiv x_div(ddr_core, use_threads); // Interpolate a vector function int function_to_interpolate = (vm.count("function") ? vm["function"].as<int>() : 0); std::function<Eigen::Vector3d(const Eigen::Vector3d &)> v; std::function<double(const Eigen::Vector3d &)> div_v; switch (function_to_interpolate) { case 0: std::cout << "[main] Interpolating constant function" << std::endl; v = constant_vector; div_v = div_constant_vector; break; case 4: std::cout << "[main] Interpolating trigonometric function" << std::endl; v = trigonometric_vector; div_v = div_trigonometric_vector; break; default: std::cerr << "ERROR: Unknown function" << std::endl; exit(1); } std::cout << "[main] Interpolating on XDiv" << std::endl; auto vh = x_div.interpolate(v); //------------------------------------------------------------------------------ // Check the consistency of the divergence and potential reconstructions //------------------------------------------------------------------------------ Eigen::VectorXd DT_errors_cells = Eigen::VectorXd::Zero(mesh_ptr->n_cells()); Eigen::VectorXd PT_errors_cells = Eigen::VectorXd::Zero(mesh_ptr->n_cells()); auto compute_errors_cells = [&mesh_ptr, &x_div, &vh, &DT_errors_cells, &PT_errors_cells, v, div_v](size_t start, size_t end) { for (size_t iT = start; iT < end; iT++) { const Cell & T = *mesh_ptr->cell(iT); QuadratureRule quad_2k_T = generate_quadrature_rule(T, 2 * x_div.degree()); Eigen::VectorXd IT_v = x_div.restrictCell(iT, vh); Eigen::MatrixXd DT_IT_v = x_div.cellOperators(iT).divergence * IT_v; auto DT_basis_quad = evaluate_quad<Function>::compute(*x_div.cellBases(iT).Polyk, quad_2k_T); DT_errors_cells(iT) = squared_l2_error(div_v, DT_IT_v, DT_basis_quad, quad_2k_T); Eigen::MatrixXd PT_IT_v = x_div.cellOperators(iT).potential * IT_v; auto PT_basis_quad = evaluate_quad<Function>::compute(*x_div.cellBases(iT).Polyk3, quad_2k_T); PT_errors_cells(iT) = squared_l2_error(v, PT_IT_v, PT_basis_quad, quad_2k_T); } // for iT }; std::cout << "[main] Checking the approximation properties of the cell gradient" << std::endl; parallel_for(mesh_ptr->n_cells(), compute_errors_cells, use_threads); double DT_error = std::sqrt( DT_errors_cells.sum() ); double PT_error = std::sqrt( PT_errors_cells.sum() ); std::cout << FORMAT(25) << "[main] L2-error for the divergence at cells " << std::scientific << DT_error << std::endl; std::cout << FORMAT(25) << "[main] L2-error for the potential at cells " << std::scientific << PT_error << std::endl; std::cout << "[main] Done" << std::endl; exit(0); }
[ "aurelioedoardo.spadotto@mail.polimi.it" ]
aurelioedoardo.spadotto@mail.polimi.it
f88b8fdea4b230885967912db0d029dea4134239
9d929cc18fbc2fc7f06b083d9ab24a9207f89c65
/Common/GLArray2D.h
872fbc5fd901ea1fccb90fffb178779e9893a0db
[]
no_license
nhubd/SqueezeImg
ad41107cda0a94bcc8e11affd95f08aab8638163
a416e4087cb0cdaa75a5f78b64e07f2c2550da65
refs/heads/main
2023-05-20T00:12:25.543541
2021-06-07T03:02:14
2021-06-07T03:02:14
374,248,990
0
0
null
null
null
null
UTF-8
C++
false
false
1,957
h
#pragma once namespace GLC { template <typename T> class CGLArray2D { public: CGLArray2D(int nRows, int nColumns); virtual ~CGLArray2D(); int GetWidth() const { return m_nColumns; } int GetHeight() const { return m_nRows; } inline T& Value(int nRow, int nColumn); inline const T& Value(int nRow, int nColumn) const; protected: private: T** m_nBuf; int m_nRows; int m_nColumns; CGLArray2D(const CGLArray2D&); CGLArray2D& operator=(const CGLArray2D&); void deleteBuf(); void createBuf(int nRows, int nColumns); }; template <typename T> CGLArray2D<T>::CGLArray2D<T>(int nRows, int nColumns) : m_nBuf(0) { assert(nRows > 0); assert(nColumns > 0); createBuf(nRows, nColumns); assert(m_nBuf != 0); assert(m_nRows > 0); assert(m_nColumns > 0); } template <typename T> CGLArray2D<T>::~CGLArray2D<T>() { deleteBuf(); } template <typename T> T& CGLArray2D<T>::Value(int nRow, int nColumn) { assert(nRow >= 0 && nRow < m_nRows); assert(nColumn >= 0 && nColumn < m_nColumns); return m_nBuf[nRow][nColumn]; } template <typename T> const T& CGLArray2D<T>::Value(int nRow, int nColumn) const { assert(nRow >= 0 && nRow < m_nRows); assert(nColumn >= 0 && nColumn < m_nColumns); return m_nBuf[nRow][nColumn]; } template <typename T> void CGLArray2D<T>::createBuf(int nRows, int nColumns) { assert(m_nBuf == 0); m_nBuf = new T*[nRows]; if (m_nBuf == 0) throw CGLException::OutOfMemoryException; m_nRows = nRows; int i; for (i = 0; i < nRows; i++) { m_nBuf[i] = 0; } try { for (i = 0; i < nRows; i++) { m_nBuf[i] = new T[nColumns]; if (m_nBuf[i] == 0) throw CGLException::OutOfMemoryException; } m_nColumns = nColumns; } catch (...) { deleteBuf(); throw; } } template <typename T> void CGLArray2D<T>::deleteBuf() { assert(m_nBuf != 0); assert(m_nRows > 0); for (int i = 0; i < m_nRows; i++) { delete[] m_nBuf[i]; } delete[] m_nBuf; m_nBuf = 0; m_nRows = 0; m_nColumns = 0; } } // namespace GLC
[ "nikolay.huber@googlemail.com" ]
nikolay.huber@googlemail.com
d45f479847ebb0171f141d29092423f110f8d9c6
868c6e50875faf2220ac28b0a5e3ddda640005d9
/rank_support/rank_overheard.cpp
81ed79da5aad0ac193b4168918329223f0afa98e
[]
no_license
amirmohsen-am/bioinformatics-fall2020-hw1
8230fcb10ad3046034c6ece0b92c7b39be1a6b56
7ff27a8600cfa0a5233cb5dcd8b1f9ac3c42c198
refs/heads/main
2023-07-21T05:28:00.064383
2020-11-27T19:09:49
2020-11-27T19:09:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
315
cpp
#include <iostream> #include "rank_support.hpp" using namespace std; int main() { uint64_t n = 1ull << 62; // for (uint64_t i = 100, cnt = 0; i < n, cnt < 100; i += 1000000, cnt++) for (uint64_t i = 10, cnt = 0; i < n, cnt < 15; i*= 4, cnt++) { cout << i << " " << hypo_overhead(i) << endl; } return 0; }
[ "ahanchi@gmail.com" ]
ahanchi@gmail.com
c7c6baceaecd374f3798417cdc56b05498602ee3
e5e9953897285dcdf87504895b20b02912f9b85f
/src/dialog.cpp
f67fa54dfc309d3d0d3f33699f1d788bfd6383f8
[]
no_license
nagyistoce/puml
8049b09788fa453773b12832fc2a228a502064db
3ce3af362482dce217a1bce791802b75462567c6
refs/heads/master
2016-09-05T09:56:23.923196
2012-06-02T01:00:08
2012-06-02T01:00:08
32,746,228
0
0
null
null
null
null
UTF-8
C++
false
false
7,109
cpp
// Copyright (C) 2011-2012 pUML Group #include <QtGui> #include "./dialog.h" /*! This constructor creates the widgets for this dialog and connects the Ok and Cancel buttons with the accept and reject slots. Uses createIcons, createNewPage and createOpenPage helper functions. */ ConfigDialog::ConfigDialog(ConfigDialogType type) { // contentsWidget is the sidebar navigation widget contentsWidget = new QListWidget; contentsWidget->setViewMode(QListView::IconMode); contentsWidget->setIconSize(QSize(96, 84)); contentsWidget->setMovement(QListView::Static); contentsWidget->setMaximumWidth(128); contentsWidget->setSpacing(12); createIcons(type); // create our two pages newPage = new QWidget; openPage = new QWidget; createOpenPage(); createNewPage(); // add the pages to the stacked widget pagesWidget = new QStackedWidget; pagesWidget->addWidget(newPage); pagesWidget->addWidget(openPage); contentsWidget->setCurrentRow(0); // set up the buttons using the built in dialog buttons QDialogButtonBox *buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); // The horizontal layout is the navigation and the stacked widget QHBoxLayout *horizontalLayout = new QHBoxLayout; horizontalLayout->addWidget(contentsWidget); horizontalLayout->addWidget(pagesWidget, 1); // the main layout is the above layout and the buttons QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(horizontalLayout); mainLayout->addWidget(buttonBox); setLayout(mainLayout); setWindowTitle(tr("pUML - Open a new or existing diagram")); } /*! This is a helper function for ConfigDialog that creates the items in the sidebar widget. */ void ConfigDialog::createIcons(ConfigDialogType type) { QListWidgetItem *newbutton; QListWidgetItem *openbutton; switch (type) { case NewOnly: newbutton = new QListWidgetItem(contentsWidget); newbutton->setIcon(QIcon(":/Images/New.png")); newbutton->setText(tr("New")); newbutton->setTextAlignment(Qt::AlignHCenter); newbutton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); break; case OpenAndNew: newbutton = new QListWidgetItem(contentsWidget); newbutton->setIcon(QIcon(":/Images/New.png")); newbutton->setText(tr("New")); newbutton->setTextAlignment(Qt::AlignHCenter); newbutton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); openbutton = new QListWidgetItem(contentsWidget); openbutton->setIcon(QIcon(":/Images/Open.png")); openbutton->setText(tr("Open")); openbutton->setTextAlignment(Qt::AlignHCenter); openbutton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); break; } connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(changePage(QListWidgetItem*, QListWidgetItem*))); } /*! Helper function for ConfigDialog that creates the new diagram type list widget items. */ void ConfigDialog::createNewPage() { // List of widgets // There should be one for each diagram type doctypeList = new QListWidget(newPage); QListWidgetItem *usecaseItem = new QListWidgetItem(doctypeList); usecaseItem->setText(tr("Use Case")); usecaseItem->setSelected(true); QListWidgetItem *classItem = new QListWidgetItem(doctypeList); classItem->setText(tr("Class")); QListWidgetItem *statechartItem = new QListWidgetItem(doctypeList); statechartItem->setText(tr("State Chart")); QListWidgetItem *collaborationItem = new QListWidgetItem(doctypeList); collaborationItem->setText(tr("Collaboration")); // end of list of widgets // Add the listwidget to a groupbox QVBoxLayout *doctypeLayout = new QVBoxLayout; doctypeLayout->addWidget(doctypeList); QGroupBox *doctypeGroup = new QGroupBox(tr("Choose Diagram Type")); doctypeGroup->setLayout(doctypeLayout); // add that groupbox to the widget QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(doctypeGroup); mainLayout->addSpacing(12); newPage->setLayout(mainLayout); } /*! Helper function for ConfigDialog that creates the browse button for opening up an existing file. @todo Change this widget so that the selected filename appears and that the browse button only shows xml files. */ void ConfigDialog::createOpenPage() { // create the browse button QPushButton *openButton = new QPushButton(tr("Browse"), openPage); connect(openButton, SIGNAL(clicked()), this, SLOT(browseForFile())); // create the box to show the filename filenameBox = new QLineEdit(openPage); filenameBox->setReadOnly(true); QGroupBox *packagesGroup = new QGroupBox(tr("Open File")); QGridLayout *packagesLayout = new QGridLayout(openPage); packagesLayout->addWidget(filenameBox); packagesGroup->setLayout(packagesLayout); QVBoxLayout *mainLayout = new QVBoxLayout(openPage); mainLayout->addWidget(packagesGroup); mainLayout->addSpacing(12); mainLayout->addWidget(openButton); mainLayout->addStretch(1); openPage->setLayout(mainLayout); } /*! This slot updates the currently visible widget in the widget stack. */ void ConfigDialog::changePage(QListWidgetItem *current, QListWidgetItem *previous) { if (!current) current = previous; pagesWidget->setCurrentIndex(contentsWidget->row(current)); } /*! This slot opens a file browser to select a file to open. */ void ConfigDialog::browseForFile() { fileName = QFileDialog::getOpenFileName(this, tr("Open Document"), "", tr("pUML files (*.puml)")); filenameBox->setText(fileName); } /*! This overriden slot emits various signals so that the MainWindow can pick up on what the user selected in this dialog. @todo Have better abstraction on what types of diagrams there are. A developer should be be able to add different diagram types at runtime. */ void ConfigDialog::accept() { QListWidgetItem *operation = contentsWidget->currentItem(); // Maybe change this to a switch statement? if (operation->text() == "New") { QListWidgetItem *selected = doctypeList->selectedItems().at(0); if (selected->text() == "State Chart") { emit newDiagramType(BaseNode::StateChart); } else if (selected->text() == "Collaboration") { emit newDiagramType(BaseNode::Collaboration); } else if (selected->text() == "Class") { emit newDiagramType(BaseNode::Class); } else if (selected->text() == "Use Case") { emit newDiagramType(BaseNode::UseCase); } else { QMessageBox::information(this, "pUML", "Not a valid diagram type!"); } } else if (operation->text() == "Open") { emit openDiagramFile(fileName); } else { QMessageBox::information(this, "pUML", "Not a valid operation!"); emit newDiagramType(BaseNode::Nothing); } QDialog::accept(); } void ConfigDialog::reject() { QDialog::reject(); emit newDiagramType(BaseNode::Nothing); }
[ "gomaxxy@gmail.com" ]
gomaxxy@gmail.com
ef0ee8f3584f1045dde41db9ea6405482341e996
54ad439992b8c07ddd0adb8a56588b392ebae14c
/Engine/Engine/input.h
ce3a4813c57850c2e0dc4301dae4018f669cbb73
[]
no_license
ZSnowbank/opengl-template
53b444783c9478f0eb02f8f9acde707dc9f7e134
9e5a5b2fe02fe9f2c153cec4b22c88bb348fc8e4
refs/heads/master
2021-07-11T10:33:42.812225
2017-10-12T06:48:34
2017-10-12T06:48:34
105,852,043
0
0
null
null
null
null
UTF-8
C++
false
false
152
h
#pragma once #include "system.h" class Input : public System { public: Input(); ~Input(); bool Initialize(); void Shutdown(); void Update(); };
[ "ZSnowbank@student.neumont.edu" ]
ZSnowbank@student.neumont.edu
3daac50a213657e1075c47baf563085ac187ebdb
1a97d04600bbc5a176b0b3c2cb0c004dc375fb28
/ActionSave.cpp
eddc7b9372a842968498dee37f7c2dcd0768ccae
[]
no_license
balean12/Mortage-Database-App
35d428bc791d711043091289911bcea7e0bc263e
1ed2f29ef95c8f2f4a1ab03c76d1c8828f25fcdd
refs/heads/master
2023-01-19T14:19:32.226877
2020-11-23T12:38:48
2020-11-23T12:38:48
315,311,036
1
0
null
null
null
null
UTF-8
C++
false
false
187
cpp
#include "ActionSave.h" void ActionSave::executeUndo() { transf.deleteFromTransferList(savedVictim); } void ActionSave::executeRedo() { this->transf.addToTransferList(savedVictim); }
[ "flaviu.balean@gmail.com" ]
flaviu.balean@gmail.com
fbb1867a2de333564f5c9fce9bd7aa9a26c27481
90c95fd7a5687b1095bf499892b8c9ba40f59533
/sprout/numeric/dft/fit/dft.hpp
ad406e2a8272dd797fbe5bb144fdecfc294857ed
[ "BSL-1.0" ]
permissive
CreativeLabs0X3CF/Sprout
af60a938fd12e8439a831d4d538c4c48011ca54f
f08464943fbe2ac2030060e6ff20e4bb9782cd8e
refs/heads/master
2021-01-20T17:03:24.630813
2016-08-15T04:44:46
2016-08-15T04:44:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,154
hpp
/*============================================================================= Copyright (c) 2011-2016 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_NUMERIC_DFT_FIT_DFT_HPP #define SPROUT_NUMERIC_DFT_FIT_DFT_HPP #include <sprout/config.hpp> #include <sprout/iterator/distance.hpp> #include <sprout/container/traits.hpp> #include <sprout/container/functions.hpp> #include <sprout/numeric/dft/fixed/dft.hpp> #include <sprout/algorithm/fit/results.hpp> #include <sprout/sub_array/sub_array.hpp> #include <sprout/sub_array/sub.hpp> #include <sprout/pit/pit.hpp> namespace sprout { namespace fit { namespace detail { template<typename ForwardIterator, typename Result> inline SPROUT_CONSTEXPR typename sprout::fit::results::algorithm<Result>::type dft_impl( ForwardIterator const& first, ForwardIterator const& last, Result const& result, typename sprout::container_traits<Result>::difference_type offset ) { return sprout::sub_copy( sprout::get_internal(sprout::fixed::dft(first, last, result)), offset, offset + sprout::fit_size(result, sprout::distance(first, last)) ); } } // namespace detail // // dft // template<typename ForwardIterator, typename Result> inline SPROUT_CONSTEXPR typename sprout::fit::results::algorithm<Result>::type dft(ForwardIterator first, ForwardIterator last, Result const& result) { return sprout::fit::detail::dft_impl(first, last, result, sprout::internal_begin_offset(result)); } template<typename Result, typename ForwardIterator> inline SPROUT_CONSTEXPR typename sprout::fixed::results::algorithm<Result>::type dft(ForwardIterator first, ForwardIterator last) { return sprout::fit::dft(first, last, sprout::pit<Result>()); } } // namespace fit } // namespace sprout #endif // #ifndef SPROUT_NUMERIC_DFT_FIT_DFT_HPP
[ "bolero.murakami@gmail.com" ]
bolero.murakami@gmail.com
1de77d67dcc45779d48145f9f73cb444bdaca7fa
55f5e9ea8c985f20cbad60d03ab2906516dbb641
/smartpoint/smartpoint.cpp
13b5ff995bf21ae00a0493afba5aaeb85db780b3
[]
no_license
498143049/windows_project
a4ebaaf0c912ad5aa1081d8bb8c8eddf4f43e857
8dd80b3f892305ba16c4b04e80e8f2472242bae6
refs/heads/master
2021-01-06T04:05:43.227470
2017-08-15T14:17:18
2017-08-15T14:17:18
99,521,400
0
0
null
null
null
null
UTF-8
C++
false
false
1,537
cpp
// // Created by dubing on 2017/6/28. // #include<iostream> #include <cstddef> #include<vector> #include<algorithm> #include <memory.h> #include <cstdint> using namespace std; class object{ public : int a; int b; }; // 仔细自考一下,这个类维护一个这块内存的内容 template <typename T,typename count_type = uint32_t> class smart_pointsing{ friend class smart_point; public: smart_pointsing() { target = NULL; count =0; } smart_pointsing(T* dst) { count=1; target = dst; } ~smart_pointsing(){ delete target; } private: T * target; count_type count; }; template <typename T> class smart_point{ public: smart_point(T * p){ qd = new smart_pointsing(p); } ~smart_point(){ --qd->count; if(qd->count==0) delete qd; } //拷贝构造函数 smart_point(smart_point &copy){ qd = copy.qd; ++qd->count; } smart_point& operator = (smart_point &copy) { ++copy.qd->count; //原来的对象做析构处理 --qd->count; if(qd->count == 0) delete qd; qd = copy.qd; return *this; } T* operator -> (){ return qd->target; } T& operator *(){ return *(qd->target); } private : smart_pointsing * qd; }; //智能指针的使用 // 有3个智能指针 unique_ptr shared_ptr int main() { smart_point<object> a(new object()); //线程安全的考虑 }
[ "dubing0624@gmail.com" ]
dubing0624@gmail.com
530249ba8287045d79c1520dbfb47be2a284b8df
94f0dbd128a4a4cce88906f33b9bc01c46acfc24
/modules/drivers/radar/conti_eth_radar/driver/input.h
bb860113c77e0832e97b53a0e898f2163957298e
[ "Apache-2.0" ]
permissive
viks8dm/apollo
8973237a442e28d85bf427f9a99800750839346d
1db6b6b313f3b7c7b728b9316a5040231614f121
refs/heads/master
2020-05-24T05:11:05.836149
2019-06-13T21:52:31
2019-06-13T21:52:31
187,106,437
0
0
null
2019-05-16T21:55:56
2019-05-16T21:55:56
null
UTF-8
C++
false
false
1,560
h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <stdio.h> #include <unistd.h> #include <memory> #include "cyber/cyber.h" #include "modules/drivers/radar/conti_eth_radar/proto/conti_eth_radar.pb.h" namespace apollo { namespace drivers { namespace conti_eth_radar { static const size_t MAX_DATA_PACKET_SIZE = 1200;//max payload 1112, header 42 static const size_t ETHERNET_HEADER_SIZE = 42; static const int SOCKET_TIMEOUT = -2; static const int RECIEVE_FAIL = -3; /** @brief Pure virtual ContiEthRadar input base class */ class Input { public: Input() {} virtual ~Input() {} virtual int get_radar_scan_packet(ContiRDI_Packet* pkt) = 0; virtual void init() {} virtual void init(const int& port) {} }; } // namespace conti_eth_radar } // namespace drivers } // namespace apollo
[ "vikalp.mishra@gmail.com" ]
vikalp.mishra@gmail.com
73c30662b4dffaa1c56288834a5692f3e1a3cd84
5d57d9e0f40f5313b3951ab236ae27bf8e365f44
/Jeju Run/Timer.cpp
1f2cedf958579972e09a0a6b1ccdc86a3f415f66
[]
no_license
Nocha12/Jeju-Run
ec85ceda3d0ed59fd55914567e6779e22c1e5c2d
91b6947d4683a519c6ebd34202e48fde2ef15d17
refs/heads/master
2020-03-28T08:07:31.929890
2018-09-08T15:42:29
2018-09-08T15:42:29
147,946,021
0
0
null
null
null
null
UTF-8
C++
false
false
566
cpp
#include "DXUT.h" #include "Timer.h" #include "World.h" Timer::Timer() : active(false) { world.timers.push_back(this); onTick = [](){}; onFin = [](){}; } Timer::~Timer() { world.timers.remove(this); } void Timer::reset(float d, int c) { duration = pair<float, float>(0, d); count = pair<int, int>(0, c); active = true; } void Timer::update(float dt) { if (!active) return; duration.first += dt; if (duration.first > duration.second) { onTick(); duration.first = 0; if (++count.first > count.second) { onFin(); active = false; } } }
[ "jsyang789@gmail.com" ]
jsyang789@gmail.com
21f328e4a375b752d3573244587b9bf0bf8f0a80
927d718336c3df467d70d517a94dc8ccafdcd298
/llvm/lib/CodeGen/ShrinkWrapping.cpp
2b01fdd8d06628dcf3010db254ae3c726c68bc3e
[ "NCSA" ]
permissive
rofl0r/ellcc
3f54f0e9614d0920d8b648b64048a383c7304b3d
a40bd7b9d4a74992c4ac8273e44ecee44241ebde
refs/heads/master
2021-01-19T08:46:05.647311
2013-09-29T13:12:16
2013-09-29T13:12:16
4,942,860
6
1
null
null
null
null
UTF-8
C++
false
false
40,263
cpp
//===-- ShrinkWrapping.cpp - Reduce spills/restores of callee-saved regs --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a shrink wrapping variant of prolog/epilog insertion: // - Spills and restores of callee-saved registers (CSRs) are placed in the // machine CFG to tightly surround their uses so that execution paths that // do not use CSRs do not pay the spill/restore penalty. // // - Avoiding placment of spills/restores in loops: if a CSR is used inside a // loop the spills are placed in the loop preheader, and restores are // placed in the loop exit nodes (the successors of loop _exiting_ nodes). // // - Covering paths without CSR uses: // If a region in a CFG uses CSRs and has multiple entry and/or exit points, // the use info for the CSRs inside the region is propagated outward in the // CFG to ensure validity of the spill/restore placements. This decreases // the effectiveness of shrink wrapping but does not require edge splitting // in the machine CFG. // // This shrink wrapping implementation uses an iterative analysis to determine // which basic blocks require spills and restores for CSRs. // // This pass uses MachineDominators and MachineLoopInfo. Loop information // is used to prevent placement of callee-saved register spills/restores // in the bodies of loops. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "shrink-wrap" #include "PrologEpilogInserter.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SparseBitVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include <sstream> using namespace llvm; STATISTIC(numSRReduced, "Number of CSR spills+restores reduced."); // Shrink Wrapping: static cl::opt<bool> ShrinkWrapping("shrink-wrap", cl::desc("Shrink wrap callee-saved register spills/restores")); // Shrink wrap only the specified function, a debugging aid. static cl::opt<std::string> ShrinkWrapFunc("shrink-wrap-func", cl::Hidden, cl::desc("Shrink wrap the specified function"), cl::value_desc("funcname"), cl::init("")); // Debugging level for shrink wrapping. enum ShrinkWrapDebugLevel { Disabled, BasicInfo, Iterations, Details }; static cl::opt<enum ShrinkWrapDebugLevel> ShrinkWrapDebugging("shrink-wrap-dbg", cl::Hidden, cl::desc("Print shrink wrapping debugging information"), cl::values( clEnumVal(Disabled , "disable debug output"), clEnumVal(BasicInfo , "print basic DF sets"), clEnumVal(Iterations, "print SR sets for each iteration"), clEnumVal(Details , "print all DF sets"), clEnumValEnd)); void PEI::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); if (ShrinkWrapping || ShrinkWrapFunc != "") { AU.addRequired<MachineLoopInfo>(); AU.addRequired<MachineDominatorTree>(); } AU.addPreserved<MachineLoopInfo>(); AU.addPreserved<MachineDominatorTree>(); AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } //===----------------------------------------------------------------------===// // ShrinkWrapping implementation //===----------------------------------------------------------------------===// // Convienences for dealing with machine loops. MachineBasicBlock* PEI::getTopLevelLoopPreheader(MachineLoop* LP) { assert(LP && "Machine loop is NULL."); MachineBasicBlock* PHDR = LP->getLoopPreheader(); MachineLoop* PLP = LP->getParentLoop(); while (PLP) { PHDR = PLP->getLoopPreheader(); PLP = PLP->getParentLoop(); } return PHDR; } MachineLoop* PEI::getTopLevelLoopParent(MachineLoop *LP) { if (LP == 0) return 0; MachineLoop* PLP = LP->getParentLoop(); while (PLP) { LP = PLP; PLP = PLP->getParentLoop(); } return LP; } bool PEI::isReturnBlock(MachineBasicBlock* MBB) { return (MBB && !MBB->empty() && MBB->back().isReturn()); } // Initialize shrink wrapping DFA sets, called before iterations. void PEI::clearAnticAvailSets() { AnticIn.clear(); AnticOut.clear(); AvailIn.clear(); AvailOut.clear(); } // Clear all sets constructed by shrink wrapping. void PEI::clearAllSets() { ReturnBlocks.clear(); clearAnticAvailSets(); UsedCSRegs.clear(); CSRUsed.clear(); TLLoops.clear(); CSRSave.clear(); CSRRestore.clear(); } // Initialize all shrink wrapping data. void PEI::initShrinkWrappingInfo() { clearAllSets(); EntryBlock = 0; #ifndef NDEBUG HasFastExitPath = false; #endif ShrinkWrapThisFunction = ShrinkWrapping; // DEBUG: enable or disable shrink wrapping for the current function // via --shrink-wrap-func=<funcname>. #ifndef NDEBUG if (ShrinkWrapFunc != "") { std::string MFName = MF->getName().str(); ShrinkWrapThisFunction = (MFName == ShrinkWrapFunc); } #endif } /// placeCSRSpillsAndRestores - determine which MBBs of the function /// need save, restore code for callee-saved registers by doing a DF analysis /// similar to the one used in code motion (GVNPRE). This produces maps of MBBs /// to sets of registers (CSRs) for saves and restores. MachineLoopInfo /// is used to ensure that CSR save/restore code is not placed inside loops. /// This function computes the maps of MBBs -> CSRs to spill and restore /// in CSRSave, CSRRestore. /// /// If shrink wrapping is not being performed, place all spills in /// the entry block, all restores in return blocks. In this case, /// CSRSave has a single mapping, CSRRestore has mappings for each /// return block. /// void PEI::placeCSRSpillsAndRestores(MachineFunction &Fn) { DEBUG(MF = &Fn); initShrinkWrappingInfo(); DEBUG(if (ShrinkWrapThisFunction) { dbgs() << "Place CSR spills/restores for " << MF->getName() << "\n"; }); if (calculateSets(Fn)) placeSpillsAndRestores(Fn); } /// calcAnticInOut - calculate the anticipated in/out reg sets /// for the given MBB by looking forward in the MCFG at MBB's /// successors. /// bool PEI::calcAnticInOut(MachineBasicBlock* MBB) { bool changed = false; // AnticOut[MBB] = INTERSECT(AnticIn[S] for S in SUCCESSORS(MBB)) SmallVector<MachineBasicBlock*, 4> successors; for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) { MachineBasicBlock* SUCC = *SI; if (SUCC != MBB) successors.push_back(SUCC); } unsigned i = 0, e = successors.size(); if (i != e) { CSRegSet prevAnticOut = AnticOut[MBB]; MachineBasicBlock* SUCC = successors[i]; AnticOut[MBB] = AnticIn[SUCC]; for (++i; i != e; ++i) { SUCC = successors[i]; AnticOut[MBB] &= AnticIn[SUCC]; } if (prevAnticOut != AnticOut[MBB]) changed = true; } // AnticIn[MBB] = UNION(CSRUsed[MBB], AnticOut[MBB]); CSRegSet prevAnticIn = AnticIn[MBB]; AnticIn[MBB] = CSRUsed[MBB] | AnticOut[MBB]; if (prevAnticIn != AnticIn[MBB]) changed = true; return changed; } /// calcAvailInOut - calculate the available in/out reg sets /// for the given MBB by looking backward in the MCFG at MBB's /// predecessors. /// bool PEI::calcAvailInOut(MachineBasicBlock* MBB) { bool changed = false; // AvailIn[MBB] = INTERSECT(AvailOut[P] for P in PREDECESSORS(MBB)) SmallVector<MachineBasicBlock*, 4> predecessors; for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) { MachineBasicBlock* PRED = *PI; if (PRED != MBB) predecessors.push_back(PRED); } unsigned i = 0, e = predecessors.size(); if (i != e) { CSRegSet prevAvailIn = AvailIn[MBB]; MachineBasicBlock* PRED = predecessors[i]; AvailIn[MBB] = AvailOut[PRED]; for (++i; i != e; ++i) { PRED = predecessors[i]; AvailIn[MBB] &= AvailOut[PRED]; } if (prevAvailIn != AvailIn[MBB]) changed = true; } // AvailOut[MBB] = UNION(CSRUsed[MBB], AvailIn[MBB]); CSRegSet prevAvailOut = AvailOut[MBB]; AvailOut[MBB] = CSRUsed[MBB] | AvailIn[MBB]; if (prevAvailOut != AvailOut[MBB]) changed = true; return changed; } /// calculateAnticAvail - build the sets anticipated and available /// registers in the MCFG of the current function iteratively, /// doing a combined forward and backward analysis. /// void PEI::calculateAnticAvail(MachineFunction &Fn) { // Initialize data flow sets. clearAnticAvailSets(); // Calculate Antic{In,Out} and Avail{In,Out} iteratively on the MCFG. bool changed = true; unsigned iterations = 0; while (changed) { changed = false; ++iterations; for (MachineFunction::iterator MBBI = Fn.begin(), MBBE = Fn.end(); MBBI != MBBE; ++MBBI) { MachineBasicBlock* MBB = MBBI; // Calculate anticipated in, out regs at MBB from // anticipated at successors of MBB. changed |= calcAnticInOut(MBB); // Calculate available in, out regs at MBB from // available at predecessors of MBB. changed |= calcAvailInOut(MBB); } } DEBUG({ if (ShrinkWrapDebugging >= Details) { dbgs() << "-----------------------------------------------------------\n" << " Antic/Avail Sets:\n" << "-----------------------------------------------------------\n" << "iterations = " << iterations << "\n" << "-----------------------------------------------------------\n" << "MBB | USED | ANTIC_IN | ANTIC_OUT | AVAIL_IN | AVAIL_OUT\n" << "-----------------------------------------------------------\n"; for (MachineFunction::iterator MBBI = Fn.begin(), MBBE = Fn.end(); MBBI != MBBE; ++MBBI) { MachineBasicBlock* MBB = MBBI; dumpSets(MBB); } dbgs() << "-----------------------------------------------------------\n"; } }); } /// propagateUsesAroundLoop - copy used register info from MBB to all blocks /// of the loop given by LP and its parent loops. This prevents spills/restores /// from being placed in the bodies of loops. /// void PEI::propagateUsesAroundLoop(MachineBasicBlock* MBB, MachineLoop* LP) { if (! MBB || !LP) return; std::vector<MachineBasicBlock*> loopBlocks = LP->getBlocks(); for (unsigned i = 0, e = loopBlocks.size(); i != e; ++i) { MachineBasicBlock* LBB = loopBlocks[i]; if (LBB == MBB) continue; if (CSRUsed[LBB].contains(CSRUsed[MBB])) continue; CSRUsed[LBB] |= CSRUsed[MBB]; } } /// calculateSets - collect the CSRs used in this function, compute /// the DF sets that describe the initial minimal regions in the /// Machine CFG around which CSR spills and restores must be placed. /// /// Additionally, this function decides if shrink wrapping should /// be disabled for the current function, checking the following: /// 1. the current function has more than 500 MBBs: heuristic limit /// on function size to reduce compile time impact of the current /// iterative algorithm. /// 2. all CSRs are used in the entry block. /// 3. all CSRs are used in all immediate successors of the entry block. /// 4. all CSRs are used in a subset of blocks, each of which dominates /// all return blocks. These blocks, taken as a subgraph of the MCFG, /// are equivalent to the entry block since all execution paths pass /// through them. /// bool PEI::calculateSets(MachineFunction &Fn) { // Sets used to compute spill, restore placement sets. const std::vector<CalleeSavedInfo> &CSI = Fn.getFrameInfo()->getCalleeSavedInfo(); // If no CSRs used, we are done. if (CSI.empty()) { DEBUG(if (ShrinkWrapThisFunction) dbgs() << "DISABLED: " << Fn.getName() << ": uses no callee-saved registers\n"); return false; } // Save refs to entry and return blocks. EntryBlock = Fn.begin(); for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end(); MBB != E; ++MBB) if (isReturnBlock(MBB)) ReturnBlocks.push_back(MBB); // Determine if this function has fast exit paths. DEBUG(if (ShrinkWrapThisFunction) findFastExitPath()); // Limit shrink wrapping via the current iterative bit vector // implementation to functions with <= 500 MBBs. if (Fn.size() > 500) { DEBUG(if (ShrinkWrapThisFunction) dbgs() << "DISABLED: " << Fn.getName() << ": too large (" << Fn.size() << " MBBs)\n"); ShrinkWrapThisFunction = false; } // Return now if not shrink wrapping. if (! ShrinkWrapThisFunction) return false; // Collect set of used CSRs. for (unsigned inx = 0, e = CSI.size(); inx != e; ++inx) { UsedCSRegs.set(inx); } // Walk instructions in all MBBs, create CSRUsed[] sets, choose // whether or not to shrink wrap this function. MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>(); MachineDominatorTree &DT = getAnalysis<MachineDominatorTree>(); const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo(); bool allCSRUsesInEntryBlock = true; for (MachineFunction::iterator MBBI = Fn.begin(), MBBE = Fn.end(); MBBI != MBBE; ++MBBI) { MachineBasicBlock* MBB = MBBI; for (MachineBasicBlock::iterator I = MBB->begin(); I != MBB->end(); ++I) { for (unsigned inx = 0, e = CSI.size(); inx != e; ++inx) { unsigned Reg = CSI[inx].getReg(); // If instruction I reads or modifies Reg, add it to UsedCSRegs, // CSRUsed map for the current block. for (unsigned opInx = 0, opEnd = I->getNumOperands(); opInx != opEnd; ++opInx) { const MachineOperand &MO = I->getOperand(opInx); if (! (MO.isReg() && (MO.isUse() || MO.isDef()))) continue; unsigned MOReg = MO.getReg(); if (!MOReg) continue; if (MOReg == Reg || (TargetRegisterInfo::isPhysicalRegister(MOReg) && TargetRegisterInfo::isPhysicalRegister(Reg) && TRI->isSubRegister(Reg, MOReg))) { // CSR Reg is defined/used in block MBB. CSRUsed[MBB].set(inx); // Check for uses in EntryBlock. if (MBB != EntryBlock) allCSRUsesInEntryBlock = false; } } } } if (CSRUsed[MBB].empty()) continue; // Propagate CSRUsed[MBB] in loops if (MachineLoop* LP = LI.getLoopFor(MBB)) { // Add top level loop to work list. MachineBasicBlock* HDR = getTopLevelLoopPreheader(LP); MachineLoop* PLP = getTopLevelLoopParent(LP); if (! HDR) { HDR = PLP->getHeader(); assert(HDR->pred_size() > 0 && "Loop header has no predecessors?"); MachineBasicBlock::pred_iterator PI = HDR->pred_begin(); HDR = *PI; } TLLoops[HDR] = PLP; // Push uses from inside loop to its parent loops, // or to all other MBBs in its loop. if (LP->getLoopDepth() > 1) { for (MachineLoop* PLP = LP->getParentLoop(); PLP; PLP = PLP->getParentLoop()) { propagateUsesAroundLoop(MBB, PLP); } } else { propagateUsesAroundLoop(MBB, LP); } } } if (allCSRUsesInEntryBlock) { DEBUG(dbgs() << "DISABLED: " << Fn.getName() << ": all CSRs used in EntryBlock\n"); ShrinkWrapThisFunction = false; } else { bool allCSRsUsedInEntryFanout = true; for (MachineBasicBlock::succ_iterator SI = EntryBlock->succ_begin(), SE = EntryBlock->succ_end(); SI != SE; ++SI) { MachineBasicBlock* SUCC = *SI; if (CSRUsed[SUCC] != UsedCSRegs) allCSRsUsedInEntryFanout = false; } if (allCSRsUsedInEntryFanout) { DEBUG(dbgs() << "DISABLED: " << Fn.getName() << ": all CSRs used in imm successors of EntryBlock\n"); ShrinkWrapThisFunction = false; } } if (ShrinkWrapThisFunction) { // Check if MBB uses CSRs and dominates all exit nodes. // Such nodes are equiv. to the entry node w.r.t. // CSR uses: every path through the function must // pass through this node. If each CSR is used at least // once by these nodes, shrink wrapping is disabled. CSRegSet CSRUsedInChokePoints; for (MachineFunction::iterator MBBI = Fn.begin(), MBBE = Fn.end(); MBBI != MBBE; ++MBBI) { MachineBasicBlock* MBB = MBBI; if (MBB == EntryBlock || CSRUsed[MBB].empty() || MBB->succ_size() < 1) continue; bool dominatesExitNodes = true; for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) if (! DT.dominates(MBB, ReturnBlocks[ri])) { dominatesExitNodes = false; break; } if (dominatesExitNodes) { CSRUsedInChokePoints |= CSRUsed[MBB]; if (CSRUsedInChokePoints == UsedCSRegs) { DEBUG(dbgs() << "DISABLED: " << Fn.getName() << ": all CSRs used in choke point(s) at " << getBasicBlockName(MBB) << "\n"); ShrinkWrapThisFunction = false; break; } } } } // Return now if we have decided not to apply shrink wrapping // to the current function. if (! ShrinkWrapThisFunction) return false; DEBUG({ dbgs() << "ENABLED: " << Fn.getName(); if (HasFastExitPath) dbgs() << " (fast exit path)"; dbgs() << "\n"; if (ShrinkWrapDebugging >= BasicInfo) { dbgs() << "------------------------------" << "-----------------------------\n"; dbgs() << "UsedCSRegs = " << stringifyCSRegSet(UsedCSRegs) << "\n"; if (ShrinkWrapDebugging >= Details) { dbgs() << "------------------------------" << "-----------------------------\n"; dumpAllUsed(); } } }); // Build initial DF sets to determine minimal regions in the // Machine CFG around which CSRs must be spilled and restored. calculateAnticAvail(Fn); return true; } /// addUsesForMEMERegion - add uses of CSRs spilled or restored in /// multi-entry, multi-exit (MEME) regions so spill and restore /// placement will not break code that enters or leaves a /// shrink-wrapped region by inducing spills with no matching /// restores or restores with no matching spills. A MEME region /// is a subgraph of the MCFG with multiple entry edges, multiple /// exit edges, or both. This code propagates use information /// through the MCFG until all paths requiring spills and restores /// _outside_ the computed minimal placement regions have been covered. /// bool PEI::addUsesForMEMERegion(MachineBasicBlock* MBB, SmallVectorImpl<MachineBasicBlock *> &blks) { if (MBB->succ_size() < 2 && MBB->pred_size() < 2) { bool processThisBlock = false; for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) { MachineBasicBlock* SUCC = *SI; if (SUCC->pred_size() > 1) { processThisBlock = true; break; } } if (!CSRRestore[MBB].empty() && MBB->succ_size() > 0) { for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) { MachineBasicBlock* PRED = *PI; if (PRED->succ_size() > 1) { processThisBlock = true; break; } } } if (! processThisBlock) return false; } CSRegSet prop; if (!CSRSave[MBB].empty()) prop = CSRSave[MBB]; else if (!CSRRestore[MBB].empty()) prop = CSRRestore[MBB]; else prop = CSRUsed[MBB]; if (prop.empty()) return false; // Propagate selected bits to successors, predecessors of MBB. bool addedUses = false; for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) { MachineBasicBlock* SUCC = *SI; // Self-loop if (SUCC == MBB) continue; if (! CSRUsed[SUCC].contains(prop)) { CSRUsed[SUCC] |= prop; addedUses = true; blks.push_back(SUCC); DEBUG(if (ShrinkWrapDebugging >= Iterations) dbgs() << getBasicBlockName(MBB) << "(" << stringifyCSRegSet(prop) << ")->" << "successor " << getBasicBlockName(SUCC) << "\n"); } } for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) { MachineBasicBlock* PRED = *PI; // Self-loop if (PRED == MBB) continue; if (! CSRUsed[PRED].contains(prop)) { CSRUsed[PRED] |= prop; addedUses = true; blks.push_back(PRED); DEBUG(if (ShrinkWrapDebugging >= Iterations) dbgs() << getBasicBlockName(MBB) << "(" << stringifyCSRegSet(prop) << ")->" << "predecessor " << getBasicBlockName(PRED) << "\n"); } } return addedUses; } /// addUsesForTopLevelLoops - add uses for CSRs used inside top /// level loops to the exit blocks of those loops. /// bool PEI::addUsesForTopLevelLoops(SmallVectorImpl<MachineBasicBlock *> &blks) { bool addedUses = false; // Place restores for top level loops where needed. for (DenseMap<MachineBasicBlock*, MachineLoop*>::iterator I = TLLoops.begin(), E = TLLoops.end(); I != E; ++I) { MachineBasicBlock* MBB = I->first; MachineLoop* LP = I->second; MachineBasicBlock* HDR = LP->getHeader(); SmallVector<MachineBasicBlock*, 4> exitBlocks; CSRegSet loopSpills; loopSpills = CSRSave[MBB]; if (CSRSave[MBB].empty()) { loopSpills = CSRUsed[HDR]; assert(!loopSpills.empty() && "No CSRs used in loop?"); } else if (CSRRestore[MBB].contains(CSRSave[MBB])) continue; LP->getExitBlocks(exitBlocks); assert(exitBlocks.size() > 0 && "Loop has no top level exit blocks?"); for (unsigned i = 0, e = exitBlocks.size(); i != e; ++i) { MachineBasicBlock* EXB = exitBlocks[i]; if (! CSRUsed[EXB].contains(loopSpills)) { CSRUsed[EXB] |= loopSpills; addedUses = true; DEBUG(if (ShrinkWrapDebugging >= Iterations) dbgs() << "LOOP " << getBasicBlockName(MBB) << "(" << stringifyCSRegSet(loopSpills) << ")->" << getBasicBlockName(EXB) << "\n"); if (EXB->succ_size() > 1 || EXB->pred_size() > 1) blks.push_back(EXB); } } } return addedUses; } /// calcSpillPlacements - determine which CSRs should be spilled /// in MBB using AnticIn sets of MBB's predecessors, keeping track /// of changes to spilled reg sets. Add MBB to the set of blocks /// that need to be processed for propagating use info to cover /// multi-entry/exit regions. /// bool PEI::calcSpillPlacements(MachineBasicBlock* MBB, SmallVectorImpl<MachineBasicBlock *> &blks, CSRegBlockMap &prevSpills) { bool placedSpills = false; // Intersect (CSRegs - AnticIn[P]) for P in Predecessors(MBB) CSRegSet anticInPreds; SmallVector<MachineBasicBlock*, 4> predecessors; for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), PE = MBB->pred_end(); PI != PE; ++PI) { MachineBasicBlock* PRED = *PI; if (PRED != MBB) predecessors.push_back(PRED); } unsigned i = 0, e = predecessors.size(); if (i != e) { MachineBasicBlock* PRED = predecessors[i]; anticInPreds = UsedCSRegs - AnticIn[PRED]; for (++i; i != e; ++i) { PRED = predecessors[i]; anticInPreds &= (UsedCSRegs - AnticIn[PRED]); } } else { // Handle uses in entry blocks (which have no predecessors). // This is necessary because the DFA formulation assumes the // entry and (multiple) exit nodes cannot have CSR uses, which // is not the case in the real world. anticInPreds = UsedCSRegs; } // Compute spills required at MBB: CSRSave[MBB] |= (AnticIn[MBB] - AvailIn[MBB]) & anticInPreds; if (! CSRSave[MBB].empty()) { if (MBB == EntryBlock) { for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) CSRRestore[ReturnBlocks[ri]] |= CSRSave[MBB]; } else { // Reset all regs spilled in MBB that are also spilled in EntryBlock. if (CSRSave[EntryBlock].intersects(CSRSave[MBB])) { CSRSave[MBB] = CSRSave[MBB] - CSRSave[EntryBlock]; } } } placedSpills = (CSRSave[MBB] != prevSpills[MBB]); prevSpills[MBB] = CSRSave[MBB]; // Remember this block for adding restores to successor // blocks for multi-entry region. if (placedSpills) blks.push_back(MBB); DEBUG(if (! CSRSave[MBB].empty() && ShrinkWrapDebugging >= Iterations) dbgs() << "SAVE[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(CSRSave[MBB]) << "\n"); return placedSpills; } /// calcRestorePlacements - determine which CSRs should be restored /// in MBB using AvailOut sets of MBB's succcessors, keeping track /// of changes to restored reg sets. Add MBB to the set of blocks /// that need to be processed for propagating use info to cover /// multi-entry/exit regions. /// bool PEI::calcRestorePlacements(MachineBasicBlock* MBB, SmallVectorImpl<MachineBasicBlock *> &blks, CSRegBlockMap &prevRestores) { bool placedRestores = false; // Intersect (CSRegs - AvailOut[S]) for S in Successors(MBB) CSRegSet availOutSucc; SmallVector<MachineBasicBlock*, 4> successors; for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) { MachineBasicBlock* SUCC = *SI; if (SUCC != MBB) successors.push_back(SUCC); } unsigned i = 0, e = successors.size(); if (i != e) { MachineBasicBlock* SUCC = successors[i]; availOutSucc = UsedCSRegs - AvailOut[SUCC]; for (++i; i != e; ++i) { SUCC = successors[i]; availOutSucc &= (UsedCSRegs - AvailOut[SUCC]); } } else { if (! CSRUsed[MBB].empty() || ! AvailOut[MBB].empty()) { // Handle uses in return blocks (which have no successors). // This is necessary because the DFA formulation assumes the // entry and (multiple) exit nodes cannot have CSR uses, which // is not the case in the real world. availOutSucc = UsedCSRegs; } } // Compute restores required at MBB: CSRRestore[MBB] |= (AvailOut[MBB] - AnticOut[MBB]) & availOutSucc; // Postprocess restore placements at MBB. // Remove the CSRs that are restored in the return blocks. // Lest this be confusing, note that: // CSRSave[EntryBlock] == CSRRestore[B] for all B in ReturnBlocks. if (MBB->succ_size() && ! CSRRestore[MBB].empty()) { if (! CSRSave[EntryBlock].empty()) CSRRestore[MBB] = CSRRestore[MBB] - CSRSave[EntryBlock]; } placedRestores = (CSRRestore[MBB] != prevRestores[MBB]); prevRestores[MBB] = CSRRestore[MBB]; // Remember this block for adding saves to predecessor // blocks for multi-entry region. if (placedRestores) blks.push_back(MBB); DEBUG(if (! CSRRestore[MBB].empty() && ShrinkWrapDebugging >= Iterations) dbgs() << "RESTORE[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(CSRRestore[MBB]) << "\n"); return placedRestores; } /// placeSpillsAndRestores - place spills and restores of CSRs /// used in MBBs in minimal regions that contain the uses. /// void PEI::placeSpillsAndRestores(MachineFunction &Fn) { CSRegBlockMap prevCSRSave; CSRegBlockMap prevCSRRestore; SmallVector<MachineBasicBlock*, 4> cvBlocks, ncvBlocks; bool changed = true; unsigned iterations = 0; // Iterate computation of spill and restore placements in the MCFG until: // 1. CSR use info has been fully propagated around the MCFG, and // 2. computation of CSRSave[], CSRRestore[] reach fixed points. while (changed) { changed = false; ++iterations; DEBUG(if (ShrinkWrapDebugging >= Iterations) dbgs() << "iter " << iterations << " --------------------------------------------------\n"); // Calculate CSR{Save,Restore} sets using Antic, Avail on the MCFG, // which determines the placements of spills and restores. // Keep track of changes to spills, restores in each iteration to // minimize the total iterations. bool SRChanged = false; for (MachineFunction::iterator MBBI = Fn.begin(), MBBE = Fn.end(); MBBI != MBBE; ++MBBI) { MachineBasicBlock* MBB = MBBI; // Place spills for CSRs in MBB. SRChanged |= calcSpillPlacements(MBB, cvBlocks, prevCSRSave); // Place restores for CSRs in MBB. SRChanged |= calcRestorePlacements(MBB, cvBlocks, prevCSRRestore); } // Add uses of CSRs used inside loops where needed. changed |= addUsesForTopLevelLoops(cvBlocks); // Add uses for CSRs spilled or restored at branch, join points. if (changed || SRChanged) { while (! cvBlocks.empty()) { MachineBasicBlock* MBB = cvBlocks.pop_back_val(); changed |= addUsesForMEMERegion(MBB, ncvBlocks); } if (! ncvBlocks.empty()) { cvBlocks = ncvBlocks; ncvBlocks.clear(); } } if (changed) { calculateAnticAvail(Fn); CSRSave.clear(); CSRRestore.clear(); } } // Check for effectiveness: // SR0 = {r | r in CSRSave[EntryBlock], CSRRestore[RB], RB in ReturnBlocks} // numSRReduced = |(UsedCSRegs - SR0)|, approx. SR0 by CSRSave[EntryBlock] // Gives a measure of how many CSR spills have been moved from EntryBlock // to minimal regions enclosing their uses. CSRegSet notSpilledInEntryBlock = (UsedCSRegs - CSRSave[EntryBlock]); unsigned numSRReducedThisFunc = notSpilledInEntryBlock.count(); numSRReduced += numSRReducedThisFunc; DEBUG(if (ShrinkWrapDebugging >= BasicInfo) { dbgs() << "-----------------------------------------------------------\n"; dbgs() << "total iterations = " << iterations << " ( " << Fn.getName() << " " << numSRReducedThisFunc << " " << Fn.size() << " )\n"; dbgs() << "-----------------------------------------------------------\n"; dumpSRSets(); dbgs() << "-----------------------------------------------------------\n"; if (numSRReducedThisFunc) verifySpillRestorePlacement(); }); } // Debugging methods. #ifndef NDEBUG /// findFastExitPath - debugging method used to detect functions /// with at least one path from the entry block to a return block /// directly or which has a very small number of edges. /// void PEI::findFastExitPath() { if (! EntryBlock) return; // Fina a path from EntryBlock to any return block that does not branch: // Entry // | ... // v | // B1<-----+ // | // v // Return for (MachineBasicBlock::succ_iterator SI = EntryBlock->succ_begin(), SE = EntryBlock->succ_end(); SI != SE; ++SI) { MachineBasicBlock* SUCC = *SI; // Assume positive, disprove existence of fast path. HasFastExitPath = true; // Check the immediate successors. if (isReturnBlock(SUCC)) { if (ShrinkWrapDebugging >= BasicInfo) dbgs() << "Fast exit path: " << getBasicBlockName(EntryBlock) << "->" << getBasicBlockName(SUCC) << "\n"; break; } // Traverse df from SUCC, look for a branch block. std::string exitPath = getBasicBlockName(SUCC); for (df_iterator<MachineBasicBlock*> BI = df_begin(SUCC), BE = df_end(SUCC); BI != BE; ++BI) { MachineBasicBlock* SBB = *BI; // Reject paths with branch nodes. if (SBB->succ_size() > 1) { HasFastExitPath = false; break; } exitPath += "->" + getBasicBlockName(SBB); } if (HasFastExitPath) { if (ShrinkWrapDebugging >= BasicInfo) dbgs() << "Fast exit path: " << getBasicBlockName(EntryBlock) << "->" << exitPath << "\n"; break; } } } /// verifySpillRestorePlacement - check the current spill/restore /// sets for safety. Attempt to find spills without restores or /// restores without spills. /// Spills: walk df from each MBB in spill set ensuring that /// all CSRs spilled at MMBB are restored on all paths /// from MBB to all exit blocks. /// Restores: walk idf from each MBB in restore set ensuring that /// all CSRs restored at MBB are spilled on all paths /// reaching MBB. /// void PEI::verifySpillRestorePlacement() { unsigned numReturnBlocks = 0; for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end(); MBBI != MBBE; ++MBBI) { MachineBasicBlock* MBB = MBBI; if (isReturnBlock(MBB) || MBB->succ_size() == 0) ++numReturnBlocks; } for (CSRegBlockMap::iterator BI = CSRSave.begin(), BE = CSRSave.end(); BI != BE; ++BI) { MachineBasicBlock* MBB = BI->first; CSRegSet spilled = BI->second; CSRegSet restored; if (spilled.empty()) continue; DEBUG(dbgs() << "SAVE[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(spilled) << " RESTORE[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(CSRRestore[MBB]) << "\n"); if (CSRRestore[MBB].intersects(spilled)) { restored |= (CSRRestore[MBB] & spilled); } // Walk depth first from MBB to find restores of all CSRs spilled at MBB: // we must find restores for all spills w/no intervening spills on all // paths from MBB to all return blocks. for (df_iterator<MachineBasicBlock*> BI = df_begin(MBB), BE = df_end(MBB); BI != BE; ++BI) { MachineBasicBlock* SBB = *BI; if (SBB == MBB) continue; // Stop when we encounter spills of any CSRs spilled at MBB that // have not yet been seen to be restored. if (CSRSave[SBB].intersects(spilled) && !restored.contains(CSRSave[SBB] & spilled)) break; // Collect the CSRs spilled at MBB that are restored // at this DF successor of MBB. if (CSRRestore[SBB].intersects(spilled)) restored |= (CSRRestore[SBB] & spilled); // If we are at a retun block, check that the restores // we have seen so far exhaust the spills at MBB, then // reset the restores. if (isReturnBlock(SBB) || SBB->succ_size() == 0) { if (restored != spilled) { CSRegSet notRestored = (spilled - restored); DEBUG(dbgs() << MF->getName() << ": " << stringifyCSRegSet(notRestored) << " spilled at " << getBasicBlockName(MBB) << " are never restored on path to return " << getBasicBlockName(SBB) << "\n"); } restored.clear(); } } } // Check restore placements. for (CSRegBlockMap::iterator BI = CSRRestore.begin(), BE = CSRRestore.end(); BI != BE; ++BI) { MachineBasicBlock* MBB = BI->first; CSRegSet restored = BI->second; CSRegSet spilled; if (restored.empty()) continue; DEBUG(dbgs() << "SAVE[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(CSRSave[MBB]) << " RESTORE[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(restored) << "\n"); if (CSRSave[MBB].intersects(restored)) { spilled |= (CSRSave[MBB] & restored); } // Walk inverse depth first from MBB to find spills of all // CSRs restored at MBB: for (idf_iterator<MachineBasicBlock*> BI = idf_begin(MBB), BE = idf_end(MBB); BI != BE; ++BI) { MachineBasicBlock* PBB = *BI; if (PBB == MBB) continue; // Stop when we encounter restores of any CSRs restored at MBB that // have not yet been seen to be spilled. if (CSRRestore[PBB].intersects(restored) && !spilled.contains(CSRRestore[PBB] & restored)) break; // Collect the CSRs restored at MBB that are spilled // at this DF predecessor of MBB. if (CSRSave[PBB].intersects(restored)) spilled |= (CSRSave[PBB] & restored); } if (spilled != restored) { CSRegSet notSpilled = (restored - spilled); DEBUG(dbgs() << MF->getName() << ": " << stringifyCSRegSet(notSpilled) << " restored at " << getBasicBlockName(MBB) << " are never spilled\n"); } } } // Debugging print methods. std::string PEI::getBasicBlockName(const MachineBasicBlock* MBB) { if (!MBB) return ""; if (MBB->getBasicBlock()) return MBB->getBasicBlock()->getName().str(); std::ostringstream name; name << "_MBB_" << MBB->getNumber(); return name.str(); } std::string PEI::stringifyCSRegSet(const CSRegSet& s) { const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo(); const std::vector<CalleeSavedInfo> &CSI = MF->getFrameInfo()->getCalleeSavedInfo(); std::ostringstream srep; if (CSI.size() == 0) { srep << "[]"; return srep.str(); } srep << "["; CSRegSet::iterator I = s.begin(), E = s.end(); if (I != E) { unsigned reg = CSI[*I].getReg(); srep << TRI->getName(reg); for (++I; I != E; ++I) { reg = CSI[*I].getReg(); srep << ","; srep << TRI->getName(reg); } } srep << "]"; return srep.str(); } void PEI::dumpSet(const CSRegSet& s) { DEBUG(dbgs() << stringifyCSRegSet(s) << "\n"); } void PEI::dumpUsed(MachineBasicBlock* MBB) { DEBUG({ if (MBB) dbgs() << "CSRUsed[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(CSRUsed[MBB]) << "\n"; }); } void PEI::dumpAllUsed() { for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end(); MBBI != MBBE; ++MBBI) { MachineBasicBlock* MBB = MBBI; dumpUsed(MBB); } } void PEI::dumpSets(MachineBasicBlock* MBB) { DEBUG({ if (MBB) dbgs() << getBasicBlockName(MBB) << " | " << stringifyCSRegSet(CSRUsed[MBB]) << " | " << stringifyCSRegSet(AnticIn[MBB]) << " | " << stringifyCSRegSet(AnticOut[MBB]) << " | " << stringifyCSRegSet(AvailIn[MBB]) << " | " << stringifyCSRegSet(AvailOut[MBB]) << "\n"; }); } void PEI::dumpSets1(MachineBasicBlock* MBB) { DEBUG({ if (MBB) dbgs() << getBasicBlockName(MBB) << " | " << stringifyCSRegSet(CSRUsed[MBB]) << " | " << stringifyCSRegSet(AnticIn[MBB]) << " | " << stringifyCSRegSet(AnticOut[MBB]) << " | " << stringifyCSRegSet(AvailIn[MBB]) << " | " << stringifyCSRegSet(AvailOut[MBB]) << " | " << stringifyCSRegSet(CSRSave[MBB]) << " | " << stringifyCSRegSet(CSRRestore[MBB]) << "\n"; }); } void PEI::dumpAllSets() { for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end(); MBBI != MBBE; ++MBBI) { MachineBasicBlock* MBB = MBBI; dumpSets1(MBB); } } void PEI::dumpSRSets() { DEBUG({ for (MachineFunction::iterator MBB = MF->begin(), E = MF->end(); MBB != E; ++MBB) { if (!CSRSave[MBB].empty()) { dbgs() << "SAVE[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(CSRSave[MBB]); if (CSRRestore[MBB].empty()) dbgs() << '\n'; } if (!CSRRestore[MBB].empty() && !CSRSave[MBB].empty()) dbgs() << " " << "RESTORE[" << getBasicBlockName(MBB) << "] = " << stringifyCSRegSet(CSRRestore[MBB]) << "\n"; } }); } #endif
[ "rich@ellcc.org" ]
rich@ellcc.org
1d22771f38c5cd34884567aa39ffddb6fd06eeab
1bafb0727799fba7cce07af2662aca8212d6a2b7
/src/simulation.cpp
d52235e1f54eed6f33425385fc7342747ee0de9c
[]
no_license
bpatmiller/apic
86c818657f1db9bc9f69590f5259b19ceb5653ff
ba2a35b6a2bf508d1ca5ec9d9a7c504291bba160
refs/heads/master
2020-05-31T05:43:11.899849
2019-06-30T19:14:00
2019-06-30T19:14:00
190,124,695
0
1
null
null
null
null
UTF-8
C++
false
false
13,501
cpp
#include "simulation.h" // given a position, return the trilinear interpolation // of the velocity field at that position glm::vec3 Simulation::trilerp_uvw(glm::vec3 p) { glm::ivec3 index; glm::vec3 coords; glm::vec3 result; // u position_to_grid(p, U_OFFSET, index, coords); result.x = grid.u.trilerp(index, coords); // v position_to_grid(p, V_OFFSET, index, coords); result.y = grid.v.trilerp(index, coords); // w position_to_grid(p, W_OFFSET, index, coords); result.z = grid.w.trilerp(index, coords); return result; } glm::vec3 Simulation::trilerp_dudvdw(glm::vec3 p) { glm::ivec3 index; glm::vec3 coords; glm::vec3 result; // u position_to_grid(p, U_OFFSET, index, coords); result.x = grid.du.trilerp(index, coords); // v position_to_grid(p, V_OFFSET, index, coords); result.y = grid.dv.trilerp(index, coords); // w position_to_grid(p, W_OFFSET, index, coords); result.z = grid.dw.trilerp(index, coords); return result; } // does the same as above, but rounds down for easier grid transfer // use offset = glm::vec3(0) for values sampled at center void Simulation::position_to_grid(glm::vec3 p, glm::vec3 offset, glm::ivec3 &index, glm::vec3 &coords) { float nx = (p.x / grid.h) - 0.5f + offset.x; float ny = (p.y / grid.h) - 0.5f + offset.y; float nz = (p.z / grid.h) - 0.5f + offset.z; int i = static_cast<int>(nx); int j = static_cast<int>(ny); int k = static_cast<int>(nz); // set index index = glm::ivec3(i, j, k); float bx = nx - std::floor(nx); float by = ny - std::floor(ny); float bz = nz - std::floor(nz); // set barycentric coordinates coords = glm::vec3(bx, by, bz); } // arr = Array3f to be added to // quantity = quantity to add in (e.g. x component of particle velocity) // index = lowest index of grid nodes to be added to // coords = coordinates relative to those lowest grid nodes (0.0-1.0) template <class T> void Simulation::grid_add_quantities(T &arr, T &weights, float q, glm::ivec3 index, glm::vec3 coords, float mass) { for (int i = 0; i <= 1; i++) { // {0,1} for (int j = 0; j <= 1; j++) { for (int k = 0; k <= 1; k++) { float w = (1 - std::fabs(i - coords.x)) * // {1 - coords.x | coords.x} (1 - std::fabs(j - coords.y)) * // {""} (1 - std::fabs(k - coords.z)); //{""} arr(index.x + i, index.y + j, index.z + k) += mass * w * q; //{0,1} weights(index.x + i, index.y + j, index.z + k) += mass * w; } } } } template <class T> void Simulation::grid_add_quantities_constant(T &arr, float q, glm::ivec3 index, glm::vec3 coords) { for (int i = 0; i <= 1; i++) { for (int j = 0; j <= 1; j++) { for (int k = 0; k <= 1; k++) { arr(index.x + i, index.y + j, index.z + k) += q; } } } } template <class T> void Simulation::affine_set(T &accum, glm::vec3 c, glm::ivec3 index, glm::vec3 coords, float mass) { for (int i = 0; i <= 1; i++) { // {0,1} for (int j = 0; j <= 1; j++) { for (int k = 0; k <= 1; k++) { float w = (1 - std::fabs(i - coords.x)) * // {1 - coords.x | coords.x} (1 - std::fabs(j - coords.y)) * // {""} (1 - std::fabs(k - coords.z)); //{""} float coef = glm::dot( c, glm::vec3(i - coords.x, j - coords.y, k - coords.z) * grid.h); accum(index.x + i, index.y + j, index.z + k) += mass * w * coef; //{0,1} } } } } // for each particle, trilinearly interpolate velocity // to all grid points nearby void Simulation::particles_to_grid() { // u grid.u.clear(); grid.u_w.clear(); for (uint i = 0; i < particles.size(); i++) { Particle &p = particles[i]; glm::ivec3 index; glm::vec3 coords; position_to_grid(p.position, U_OFFSET, index, coords); grid_add_quantities(grid.u, grid.u_w, p.velocity.x, index, coords, p.mass); if (mode == APIC) { affine_set(grid.u, cx[i], index, coords, p.mass); } } // average velocities for (int i = 0; i < grid.u.sx; i++) { for (int j = 0; j < grid.u.sy; j++) { for (int k = 0; k < grid.u.sz; k++) { if (grid.u_w(i, j, k) != 0) grid.u(i, j, k) /= grid.u_w(i, j, k); } } } // v grid.v.clear(); grid.v_w.clear(); for (uint i = 0; i < particles.size(); i++) { Particle &p = particles[i]; glm::ivec3 index; glm::vec3 coords; position_to_grid(p.position, V_OFFSET, index, coords); grid_add_quantities(grid.v, grid.v_w, p.velocity.y, index, coords, p.mass); if (mode == APIC) { affine_set(grid.v, cy[i], index, coords, p.mass); } } // average velocities for (int i = 0; i < grid.v.sx; i++) { for (int j = 0; j < grid.v.sy; j++) { for (int k = 0; k < grid.v.sz; k++) { if (grid.v_w(i, j, k) != 0) { grid.v(i, j, k) /= grid.v_w(i, j, k); } } } } // w grid.w.clear(); grid.w_w.clear(); for (uint i = 0; i < particles.size(); i++) { Particle &p = particles[i]; glm::ivec3 index; glm::vec3 coords; position_to_grid(p.position, W_OFFSET, index, coords); grid_add_quantities(grid.w, grid.w_w, p.velocity.z, index, coords, p.mass); if (mode == APIC) { affine_set(grid.w, cz[i], index, coords, p.mass); } } // average velocities for (int i = 0; i < grid.w.sx; i++) { for (int j = 0; j < grid.w.sy; j++) { for (int k = 0; k < grid.w.sz; k++) { if (grid.w_w(i, j, k) != 0) grid.w(i, j, k) /= grid.w_w(i, j, k); } } } } // return gradient of weighted field glm::vec3 Simulation::compute_C(Array3f &field, glm::ivec3 index, glm::vec3 coords, float mass) { glm::vec3 wg; glm::vec3 c = glm::vec3(0.0f, 0.0f, 0.0f); glm::mat3x3 D = glm::mat3x3(0.0f); // offset position slightly to prevent a singular D coords = glm::clamp(coords, 0.0000001f, 0.9999999f); // compute D for (int i = 0; i <= 1; i++) { // {0,1} for (int j = 0; j <= 1; j++) { for (int k = 0; k <= 1; k++) { float w = (1 - std::fabs(i - coords.x)) * // {1 - coords.x | coords.x} (1 - std::fabs(j - coords.y)) * // {""} (1 - std::fabs(k - coords.z)); //{""} glm::vec3 v = glm::vec3(i - coords.x, j - coords.y, k - coords.z) * grid.h; D += w * glm::outerProduct(v, v); } } } // weight gradient = w * D^-1 * (x_i - x_p) for (int i = 0; i <= 1; i++) { // {0,1} for (int j = 0; j <= 1; j++) { for (int k = 0; k <= 1; k++) { float w = (1 - std::fabs(i - coords.x)) * // {1 - coords.x | coords.x} (1 - std::fabs(j - coords.y)) * // {""} (1 - std::fabs(k - coords.z)); //{""} glm::vec3 v = glm::vec3(i - coords.x, j - coords.y, k - coords.z) * grid.h; assert(glm::determinant(D) != 0); wg = w * glm::inverse(D) * glm::vec3(v); c += mass * wg * field(index.x + i, index.y + j, index.z + k); } } } return c; } void Simulation::grid_to_particles() { // pic flip velocity differences if (mode == PIC_FLIP) { for (int nu = 0; nu < grid.u.size; nu++) { grid.du.data[nu] = grid.u.data[nu] - grid.du.data[nu]; } for (int nv = 0; nv < grid.v.size; nv++) { grid.dv.data[nv] = grid.v.data[nv] - grid.dv.data[nv]; } for (int nw = 0; nw < grid.w.size; nw++) { grid.dw.data[nw] = grid.w.data[nw] - grid.dw.data[nw]; } } for (uint i = 0; i < particles.size(); i++) { Particle &p = particles[i]; if (mode == PIC_FLIP) { p.velocity = (1.0f - flip_blend) * trilerp_uvw(p.position) + flip_blend * (p.velocity + trilerp_dudvdw(p.position)); } else { p.velocity = trilerp_uvw(p.position); if (mode == APIC) { // transfer C to particles glm::ivec3 index; glm::vec3 coords; position_to_grid(p.position, U_OFFSET, index, coords); cx[i] = compute_C(grid.u, index, coords, p.mass); position_to_grid(p.position, V_OFFSET, index, coords); cy[i] = compute_C(grid.v, index, coords, p.mass); position_to_grid(p.position, W_OFFSET, index, coords); cz[i] = compute_C(grid.w, index, coords, p.mass); } } } } void Simulation::advect(float dt) { glm::vec3 mid, gu; // boundaries float xmin = 1.01 * grid.h; float ymin = 1.01 * grid.h; float zmin = 1.01 * grid.h; float xmax = grid.lx - 1.01 * grid.h; float ymax = grid.ly - 1.01 * grid.h; float zmax = grid.lz - 1.01 * grid.h; for (uint i = 0; i < particles.size(); i++) { Particle &p = particles[i]; // first stage of RK2 gu = trilerp_uvw(p.position); mid = p.position + 0.5f * dt * gu; mid.x = glm::clamp(mid.x, xmin, xmax); mid.y = glm::clamp(mid.y, ymin, ymax); mid.z = glm::clamp(mid.z, zmin, zmax); // second stage gu = trilerp_uvw(mid); p.position += dt * gu; p.position.x = glm::clamp(p.position.x, xmin, xmax); p.position.y = glm::clamp(p.position.y, ymin, ymax); p.position.z = glm::clamp(p.position.z, zmin, zmax); // push out of solid obstacles if (reseed) { glm::vec3 coords; glm::ivec3 index; position_to_grid(p.position, CENTER_OFFSET, index, coords); if (grid.marker(index.x, index.y, index.z) == SOLID_CELL) { // reesed particles elsewhere glm::ivec4 best_candidate = candidates.back(); p.position = glm::vec3((best_candidate.x + 0.5f) * grid.h, (best_candidate.y + 0.5f) * grid.h, (best_candidate.z + 0.5f) * grid.h); // resample velocity and C p.velocity = trilerp_uvw(p.position); cx[i] = glm::vec3(0); cy[i] = glm::vec3(0); cz[i] = glm::vec3(0); candidates.pop_back(); } } } } void Simulation::mark_cells() { // mark all non-solid cells as empty for (int i = 0; i < grid.marker.size; i++) { if (grid.marker.data[i] != SOLID_CELL) { grid.marker.data[i] = AIR_CELL; } } // mark liquid cells glm::ivec3 index; glm::vec3 coords; for (Particle &p : particles) { position_to_grid(p.position, CENTER_OFFSET, index, coords); grid.marker(index.x, index.y, index.z) = FLUID_CELL; } } void Simulation::intialize_boundaries() { // top and bottom (y axis) for (int i = 0; i < grid.marker.sx; i++) { for (int k = 0; k < grid.marker.sy; k++) { grid.marker(i, grid.marker.sy - 1, k) = SOLID_CELL; grid.marker(i, 0, k) = SOLID_CELL; } } // left and right (x axis) for (int j = 0; j < grid.marker.sy; j++) { for (int k = 0; k < grid.marker.sz; k++) { grid.marker(grid.marker.sx - 1, j, k) = SOLID_CELL; grid.marker(0, j, k) = SOLID_CELL; } } // front and back (z axis) for (int i = 0; i < grid.marker.sx; i++) { for (int j = 0; j < grid.marker.sy; j++) { grid.marker(i, j, grid.marker.sz - 1) = SOLID_CELL; grid.marker(i, j, 0) = SOLID_CELL; } } } void Simulation::make_candidate_reseeds() { // populate pc array with effect of each particle // on each grid node for (auto &p : particles) { glm::vec3 coords; glm::ivec3 index; position_to_grid(p.position, CENTER_OFFSET, index, coords); grid_add_quantities_constant(grid.pc, 1.0f, index, coords); } // loop through all fluid cells, if they // are surrounded on all sides by fluid, // add them to a candidate list sor candidates.clear(); for (int i = 0; i < grid.marker.sx; i++) { for (int j = 0; j < grid.marker.sy; j++) { for (int k = 0; k < grid.marker.sz; k++) { if (grid.marker(i, j, k) == FLUID_CELL && grid.marker(i + 1, j, k) == FLUID_CELL && grid.marker(i - 1, j, k) == FLUID_CELL && grid.marker(i, j + 1, k) == FLUID_CELL && grid.marker(i, j - 1, k) == FLUID_CELL && grid.marker(i, j, k + 1) == FLUID_CELL && grid.marker(i, j, k - 1) == FLUID_CELL) { candidates.push_back(glm::ivec4(i, j, k, grid.pc(i, j, k))); } } } } // sort with highest pc first // and later pop candidates during reseed std::sort( candidates.begin(), candidates.end(), [](const glm::ivec4 &a, const glm::ivec4 &b) { return a[3] > b[3]; }); } void Simulation::advance(float dt) { if (reseed) { reseed_count = 0; make_candidate_reseeds(); } emit_particles(); advect(dt); particles_to_grid(); grid.save_velocity(); grid.add_gravity(dt); mark_cells(); grid.compute_phi(); grid.enforce_boundary(); grid.apply_viscosity(dt); grid.project(dt); grid.extend_velocity(); grid_to_particles(); } void Simulation::step_frame(float time) { float t = 0; float dt; while (t < time) { dt = 2.0 * grid.CFL(); if (t + dt >= time) { dt = time - t; } advance(dt); t += dt; } } void Simulation::step_and_save(float t, std::string fname) { float tm = 0.0f; float tstep = 0.05f; while (tm < t) { if (tm + tstep > t) tstep = t - tm; tm += tstep; std::cout << " t: " << tm << std::endl; step_frame(tstep); generate_mesh(); save_mesh(fname + std::string("_") + std::to_string(tm) + std::string(".ply")); } }
[ "brendanmiller.ca@gmail.com" ]
brendanmiller.ca@gmail.com
8333615df77d7519aed7be7f1abb478807a88313
8573708615f759d000964f11f3110a7f39cfdba0
/QrCodeReader/creekQrCodeReaderServiceSk.cpp
276ea109c41ea542b5b1e5c1b277424c3726eaf3
[]
no_license
s-creek/rtc
0e260d3865770e08f58c4b8863ae00e0fef96512
a56354af1a51cc7003c4513607678d2037f1c00c
refs/heads/master
2021-01-19T17:44:37.893603
2015-10-03T18:38:22
2015-10-03T18:38:22
37,808,225
2
1
null
null
null
null
UTF-8
C++
false
false
6,230
cpp
// This file is generated by omniidl (C++ backend)- omniORB_4_1. Do not edit. #include "creekQrCodeReaderService.hh" #include <omniORB4/IOP_S.h> #include <omniORB4/IOP_C.h> #include <omniORB4/callDescriptor.h> #include <omniORB4/callHandle.h> #include <omniORB4/objTracker.h> OMNI_USING_NAMESPACE(omni) static const char* _0RL_library_version = omniORB_4_1; OpenHRP::creekQrCodeReaderService_ptr OpenHRP::creekQrCodeReaderService_Helper::_nil() { return ::OpenHRP::creekQrCodeReaderService::_nil(); } ::CORBA::Boolean OpenHRP::creekQrCodeReaderService_Helper::is_nil(::OpenHRP::creekQrCodeReaderService_ptr p) { return ::CORBA::is_nil(p); } void OpenHRP::creekQrCodeReaderService_Helper::release(::OpenHRP::creekQrCodeReaderService_ptr p) { ::CORBA::release(p); } void OpenHRP::creekQrCodeReaderService_Helper::marshalObjRef(::OpenHRP::creekQrCodeReaderService_ptr obj, cdrStream& s) { ::OpenHRP::creekQrCodeReaderService::_marshalObjRef(obj, s); } OpenHRP::creekQrCodeReaderService_ptr OpenHRP::creekQrCodeReaderService_Helper::unmarshalObjRef(cdrStream& s) { return ::OpenHRP::creekQrCodeReaderService::_unmarshalObjRef(s); } void OpenHRP::creekQrCodeReaderService_Helper::duplicate(::OpenHRP::creekQrCodeReaderService_ptr obj) { if( obj && !obj->_NP_is_nil() ) omni::duplicateObjRef(obj); } OpenHRP::creekQrCodeReaderService_ptr OpenHRP::creekQrCodeReaderService::_duplicate(::OpenHRP::creekQrCodeReaderService_ptr obj) { if( obj && !obj->_NP_is_nil() ) omni::duplicateObjRef(obj); return obj; } OpenHRP::creekQrCodeReaderService_ptr OpenHRP::creekQrCodeReaderService::_narrow(::CORBA::Object_ptr obj) { if( !obj || obj->_NP_is_nil() || obj->_NP_is_pseudo() ) return _nil(); _ptr_type e = (_ptr_type) obj->_PR_getobj()->_realNarrow(_PD_repoId); return e ? e : _nil(); } OpenHRP::creekQrCodeReaderService_ptr OpenHRP::creekQrCodeReaderService::_unchecked_narrow(::CORBA::Object_ptr obj) { if( !obj || obj->_NP_is_nil() || obj->_NP_is_pseudo() ) return _nil(); _ptr_type e = (_ptr_type) obj->_PR_getobj()->_uncheckedNarrow(_PD_repoId); return e ? e : _nil(); } OpenHRP::creekQrCodeReaderService_ptr OpenHRP::creekQrCodeReaderService::_nil() { #ifdef OMNI_UNLOADABLE_STUBS static _objref_creekQrCodeReaderService _the_nil_obj; return &_the_nil_obj; #else static _objref_creekQrCodeReaderService* _the_nil_ptr = 0; if( !_the_nil_ptr ) { omni::nilRefLock().lock(); if( !_the_nil_ptr ) { _the_nil_ptr = new _objref_creekQrCodeReaderService; registerNilCorbaObject(_the_nil_ptr); } omni::nilRefLock().unlock(); } return _the_nil_ptr; #endif } const char* OpenHRP::creekQrCodeReaderService::_PD_repoId = "IDL:OpenHRP/creekQrCodeReaderService:1.0"; OpenHRP::_objref_creekQrCodeReaderService::~_objref_creekQrCodeReaderService() { } OpenHRP::_objref_creekQrCodeReaderService::_objref_creekQrCodeReaderService(omniIOR* ior, omniIdentity* id) : omniObjRef(::OpenHRP::creekQrCodeReaderService::_PD_repoId, ior, id, 1) { _PR_setobj(this); } void* OpenHRP::_objref_creekQrCodeReaderService::_ptrToObjRef(const char* id) { if( id == ::OpenHRP::creekQrCodeReaderService::_PD_repoId ) return (::OpenHRP::creekQrCodeReaderService_ptr) this; if( id == ::CORBA::Object::_PD_repoId ) return (::CORBA::Object_ptr) this; if( omni::strMatch(id, ::OpenHRP::creekQrCodeReaderService::_PD_repoId) ) return (::OpenHRP::creekQrCodeReaderService_ptr) this; if( omni::strMatch(id, ::CORBA::Object::_PD_repoId) ) return (::CORBA::Object_ptr) this; return 0; } // Proxy call descriptor class. Mangled signature: // void class _0RL_cd_cd7a18f3159ad6bf_00000000 : public omniCallDescriptor { public: inline _0RL_cd_cd7a18f3159ad6bf_00000000(LocalCallFn lcfn,const char* op_,size_t oplen,_CORBA_Boolean upcall=0): omniCallDescriptor(lcfn, op_, oplen, 0, _user_exns, 0, upcall) { } static const char* const _user_exns[]; }; const char* const _0RL_cd_cd7a18f3159ad6bf_00000000::_user_exns[] = { 0 }; // Local call call-back function. static void _0RL_lcfn_cd7a18f3159ad6bf_10000000(omniCallDescriptor*, omniServant* svnt) { OpenHRP::_impl_creekQrCodeReaderService* impl = (OpenHRP::_impl_creekQrCodeReaderService*) svnt->_ptrToInterface(OpenHRP::creekQrCodeReaderService::_PD_repoId); impl->test(); } void OpenHRP::_objref_creekQrCodeReaderService::test() { _0RL_cd_cd7a18f3159ad6bf_00000000 _call_desc(_0RL_lcfn_cd7a18f3159ad6bf_10000000, "test", 5); _invoke(_call_desc); } OpenHRP::_pof_creekQrCodeReaderService::~_pof_creekQrCodeReaderService() {} omniObjRef* OpenHRP::_pof_creekQrCodeReaderService::newObjRef(omniIOR* ior, omniIdentity* id) { return new ::OpenHRP::_objref_creekQrCodeReaderService(ior, id); } ::CORBA::Boolean OpenHRP::_pof_creekQrCodeReaderService::is_a(const char* id) const { if( omni::ptrStrMatch(id, ::OpenHRP::creekQrCodeReaderService::_PD_repoId) ) return 1; return 0; } const OpenHRP::_pof_creekQrCodeReaderService _the_pof_OpenHRP_mcreekQrCodeReaderService; OpenHRP::_impl_creekQrCodeReaderService::~_impl_creekQrCodeReaderService() {} ::CORBA::Boolean OpenHRP::_impl_creekQrCodeReaderService::_dispatch(omniCallHandle& _handle) { const char* op = _handle.operation_name(); if( omni::strMatch(op, "test") ) { _0RL_cd_cd7a18f3159ad6bf_00000000 _call_desc(_0RL_lcfn_cd7a18f3159ad6bf_10000000, "test", 5, 1); _handle.upcall(this,_call_desc); return 1; } return 0; } void* OpenHRP::_impl_creekQrCodeReaderService::_ptrToInterface(const char* id) { if( id == ::OpenHRP::creekQrCodeReaderService::_PD_repoId ) return (::OpenHRP::_impl_creekQrCodeReaderService*) this; if( id == ::CORBA::Object::_PD_repoId ) return (void*) 1; if( omni::strMatch(id, ::OpenHRP::creekQrCodeReaderService::_PD_repoId) ) return (::OpenHRP::_impl_creekQrCodeReaderService*) this; if( omni::strMatch(id, ::CORBA::Object::_PD_repoId) ) return (void*) 1; return 0; } const char* OpenHRP::_impl_creekQrCodeReaderService::_mostDerivedRepoId() { return ::OpenHRP::creekQrCodeReaderService::_PD_repoId; } POA_OpenHRP::creekQrCodeReaderService::~creekQrCodeReaderService() {}
[ "ogawa@oga-pc04.(none)" ]
ogawa@oga-pc04.(none)
eff015fc18b1a3637ef237e7a6c14635a33e3e4b
c52bf4ec52bb11d8a2a913412ec0aedb5748f888
/bomberman/inc/Daemon/Core/Object/MushRoom.hh
781a0a04c847e12497d9db99f06da812fea4ebc7
[]
no_license
platelk/project
5f8e1a155bac7f7f9b65a27c668cbfc9d06a3b0f
53eda72963f667e2c07d741ba0b03b8bec5926cf
refs/heads/master
2021-01-18T22:34:53.703760
2016-05-10T14:45:57
2016-05-10T14:45:57
13,128,086
2
6
null
null
null
null
UTF-8
C++
false
false
552
hh
// // MushRoom.hh for MushRoom in /home/guiho_r/depot/bomberman/src/Daemon/Core/ObjectCreation // // Made by ronan guiho // Login <guiho_r@epitech.net> // // Started on Fri Jun 7 02:41:54 2013 ronan guiho // Last update Fri Jun 7 02:47:01 2013 ronan guiho // #ifndef __MUSHROOM_H__ #define __MUSHROOM_H__ #include "Decor.hh" class MushRoom : public Decor { public: static const std::string NAME; MushRoom(Listener *parent = 0, const int life = 3, const int x = 0, const int y = 0, const int z = 0); virtual ~MushRoom(); }; #endif
[ "kevin.platel@epitech.eu" ]
kevin.platel@epitech.eu
00b3a79331620964ed08c64e7ea388087d323d3c
2cbefb3137cdf8cd85a2976990cf506038cf5a2f
/client/getCommand.h
b59f0f37b9e3a6a93327915e82a4f35c3193cff4
[]
no_license
ytn86/LikeFTP
7a5fbf2dbc0c54c04497ce29574680232b0ec3f5
1b1ba21180387b12936c2c8a940479b7dc404de0
refs/heads/master
2021-01-20T22:20:23.024527
2016-08-04T17:15:25
2016-08-04T17:15:25
64,953,252
1
0
null
null
null
null
UTF-8
C++
false
false
400
h
#ifndef GETCOMMAND_H #define GETCOMMAND_H #include "command.h" class GetCommand : public Command { public: GetCommand(FILE *in, FILE *out, std::vector<std::string>& files); int execute(); private: //std::vector<std::string> files; //int recvData(const std::string& name, const int size); int recvData(const std::string& name); void sendRequest(const char *filename); }; #endif
[ "mail@ytn86.net" ]
mail@ytn86.net
ea7af54c12325f195017f05d72a6e88fc75f17f9
4101b168de5ae77e08ff986595399e59512aba9d
/src/qt/banner.cpp
41571bc96f846ac6faa6e323d991a1ead603a46c
[ "MIT" ]
permissive
InvisibleHands42/cleanwatercoin
ca4971e41387123e9143447769217872520bcfeb
f7fdba3d7d1769398f8eeea2fac80638ef40e378
refs/heads/master
2021-01-12T20:15:34.428159
2014-04-23T09:29:09
2014-04-23T09:29:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,095
cpp
/** * ek **/ #include <string> #include <QtGui> #include <QtNetwork> #include <QUrl> #include <QDesktopServices> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include "util.h" #include "banner.h" const std::string BANNER_URL = "http://www.cleanwatercoin.org/ad/wallet/"; //const std::string BANNER_URL = "http://springboard.sol/"; const std::string FILE_TXT = "banner.txt"; const std::string FILE_IMG = "banner.png"; const std::string FILE_TMP = ".banner.tmp"; enum {IDLE, GET_IMG, GET_TXT }; Banner::Banner(QWidget * parent) : QLabel(parent) { tmpPath = GetDataDir() / "banners"; if (!boost::filesystem::is_directory(tmpPath)) boost::filesystem::create_directory(tmpPath); state = IDLE; timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateBanner())); timer->start(0); setCursor(Qt::PointingHandCursor); } Banner::~Banner() { delete timer; } void Banner::enterEvent ( QEvent * event ) {} void Banner::leaveEvent ( QEvent * event ) {} void Banner::mouseMoveEvent ( QMouseEvent * event ) {} void Banner::mousePressEvent ( QMouseEvent * event ) {} void Banner::mouseReleaseEvent ( QMouseEvent * event ) { QDesktopServices::openUrl(url); } void Banner::download(int s) { QUrl u; if (state != IDLE) return; state = s; if(state == GET_IMG) { u = QString((BANNER_URL + FILE_IMG).c_str()); } else { u = QString((BANNER_URL + FILE_TXT).c_str()); } boost::filesystem::path tmpfile = tmpPath / FILE_TMP; file = new QFile(QString(tmpfile.c_str())); if (!file->open(QIODevice::WriteOnly)) { delete file; file = 0; timer->start(BANNER_DELAY); return; } reply = qnam.get(QNetworkRequest(u)); connect(reply, SIGNAL(finished()), this, SLOT(httpFinished())); connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead())); connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDataReadProgress(qint64,qint64))); } void Banner::updateBanner() { if (boost::filesystem::exists(tmpPath / FILE_TXT) && boost::filesystem::exists(tmpPath / FILE_IMG)) { QImage image((tmpPath / FILE_IMG).c_str()); setPixmap(QPixmap::fromImage(image)); QFile inputFile((tmpPath / FILE_TXT).c_str()); if (inputFile.open(QIODevice::ReadOnly)) { QTextStream in(&inputFile); while ( !in.atEnd() ) { QString line = in.readLine(); url = QUrl(line, QUrl::TolerantMode); } inputFile.close(); } } download(GET_IMG); timer->start(BANNER_DELAY); } void Banner::httpFinished() { file->flush(); file->close(); if(state == GET_IMG) { boost::filesystem::rename(tmpPath / FILE_TMP, tmpPath / FILE_IMG); state = IDLE; download(GET_TXT); } else { boost::filesystem::rename(tmpPath / FILE_TMP, tmpPath / FILE_TXT); updateBanner(); state = IDLE; } } void Banner::httpReadyRead() { if (file) file->write(reply->readAll()); } void Banner::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes) {}
[ "cryptowest@gmail.com" ]
cryptowest@gmail.com
766142b37dd475e8e3b372624736742343be1462
907d69ceeda841b03d426143a97049d49fe5b545
/wasm/Matrix.cpp
3daf621c8d4b8b26e059bb6c7b3add16bb0f30c7
[ "Apache-2.0" ]
permissive
Huangxy0106/Renderer
0072a89d6f60d70c20a674a71e698bac22b940de
be40956f7172bb9cfb7e5acb5a605e956da3ed1b
refs/heads/master
2023-03-27T11:42:45.215734
2021-03-27T12:39:41
2021-03-27T12:39:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,006
cpp
#include "include/Matrix.h" Matrix::Matrix(int r, int c) :rows(r), columns(c) { buffer = new double[(size_t)rows * (size_t)columns]; std::fill(buffer, buffer + (size_t)rows * (size_t)columns, 0.0); } Matrix::Matrix(const Matrix& src) :rows(src.rows), columns(src.columns) { buffer = new double[(size_t)rows * (size_t)columns]; std::copy(src.buffer, src.buffer + ((size_t)rows * (size_t)columns), buffer); } Matrix::~Matrix() { delete buffer; } Matrix Matrix::operator*(const Matrix& b) const { if (this->columns != b.rows) { throw "矩阵行数和列数无法满足相乘条件"; } Matrix result(this->rows, b.columns); for (int r = 0; r < this->rows; r++) { for (int c = 0; c < b.columns; c++) { result[r][c] = 0; for (int i = 0; i < this->columns; i++) { result[r][c] = result[r][c] + (*this)[r][i] * b[i][c]; } } } return result; } double* Matrix::operator[](int index) const { return &buffer[index * columns]; } Matrix& Matrix::operator=(const Matrix& b) { // TODO: 在此处插入 return 语句 if (this->rows != b.rows || this->columns != b.columns) { throw "两矩阵行列数不一致,无法赋值"; } std::copy(b.buffer, b.buffer + (size_t)b.rows * (size_t)b.columns, buffer); return *this; } Matrix Matrix::Perspective(double l, double r, double b, double t, double n, double f) { Matrix result(4, 4); result[0][0] = (2 * n) / (r - l); result[0][2] = -(r + l) / (r - l); result[1][1] = (2 * n) / (t - b); result[1][2] = -(t + b) / (t - b); result[2][2] = (f + n) / (f - n); result[2][3] = (2 * n * f) / (n - f); result[3][2] = 1; return result; } Matrix Matrix::RotateX(double angle) { const double PI = 3.141592653589793; double radian = angle * PI / 180; Matrix result(4, 4); result[0][0] = 1; result[1][1] = std::cos(radian); result[1][2] = std::sin(radian); result[2][1] = -std::sin(radian); result[2][2] = std::cos(radian); result[3][3] = 1; return result; } Matrix Matrix::RotateY(double angle) { const double PI = 3.141592653589793; double radian = angle * PI / 180; Matrix result(4, 4); result[0][0] = std::cos(radian); result[0][2] = -std::sin(radian); result[1][1] = 1; result[2][0] = std::sin(radian); result[2][2] = std::cos(radian); result[3][3] = 1; return result; } Matrix Matrix::RotateZ(double angle) { const double PI = 3.141592653589793; double radian = angle * PI / 180; Matrix result(4, 4); result[0][0] = std::cos(radian); result[0][1] = -std::sin(radian); result[1][0] = std::sin(radian); result[1][1] = std::cos(radian); result[2][2] = 1; result[3][3] = 1; return result; } Matrix Matrix::Translate(double x, double y, double z) { Matrix result(4, 4); result[0][0] = 1; result[1][1] = 1; result[2][2] = 1; result[3][3] = 1; result[0][3] = x; result[1][3] = y; result[2][3] = z; return result; } Matrix Matrix::Scale(double x, double y, double z) { Matrix result(4, 4); result[0][0] = x; result[1][1] = y; result[2][2] = z; result[3][3] = 1; return result; }
[ "775697360@qq.com" ]
775697360@qq.com
7715290527dc943fba9008f71fa13a5767394975
e14559ad9c575bff417a24b35922d61879d68830
/CodeForces/CodeForces ProblemSet/D-600/959A.cpp
1fe1f542b4c731dba92984a4829e8d593d0d378a
[]
no_license
Biditmangal/CompetitiveProgramming
eb34b2c11d362b899b826fadfddc7caa761e5786
19a0efcef60eeff451f62cfbd2ef56cd2067d82e
refs/heads/master
2021-07-09T21:15:43.453882
2021-04-02T17:58:40
2021-04-02T17:58:40
232,278,122
2
4
null
2021-02-17T18:17:42
2020-01-07T08:23:43
C++
UTF-8
C++
false
false
917
cpp
#include <math.h> #include <time.h> #include <ctype.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define sp system("pause") #define FOR(i,a,b) for(int i=a;i<=b;++i) #define FORD(i,a,b) for(int i=a;i>=b;--i) #define REP(i,n) FOR(i,0,(int)n-1) #define pb(x) push_back(x) #define mp(a,b) make_pair(a,b) #define MS0(x) memset(x,0,sizeof(x)) #define MS1(x) memset(x,1,sizeof(x)) #define SORT(a,n) sort(begin(a),begin(a)+n) #define REV(a,n) reverse(begin(a),begin(a)+n) #define ll long long #define pii pair<int,int> #define MOD 1000000007 int a[100000]; int main(){ int n, m; scanf("%d", &n); if(n%2==0){ n=0; cout<<"Mahmoud"; } else{ n=1; cout<<"Ehab"; } return 0; }
[ "biditmangal9506@gmail.com" ]
biditmangal9506@gmail.com
346988f954f74946a701bcfc77eba4eb924ff394
d51f3b5d0a8b85d0de7f275f59f65a9b7b978b8a
/UVA/10963/19628000_AC_0ms_0kB.cpp
c6d964a18cc63a339f4117e2f647ecbbf65f7043
[]
no_license
CIA66/Competitive-Programming
418af2c3eb30f78fc5e143d47972fb202f0b61c0
9afd528959a7fc2c31cafb143ed0a87e2a10ef88
refs/heads/main
2023-02-09T08:09:06.874776
2020-10-30T06:52:14
2020-10-30T06:52:14
308,543,870
0
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include<stdio.h> int main(){ int T = 0; scanf("%d", &T); int W = 0; int y1[1000] = {0}, y2[1000] = {0}; for(int a=0; a<T; a++){ getchar(); scanf("%d", &W); int beda = 0; for(int b=0; b<W; b++){ scanf("%d %d", &y1[b], &y2[b]); } beda = y2[0] - y1[0]; int tru = 1; for(int c = 0; c < W ; c++){ if((y2[c] - y1[c]) != beda){ tru = 0; break; } } if(!tru) printf("no\n"); else printf("yes\n"); if(a != (T-1)) printf("\n"); } return 0; }
[ "54312493+CIA66@users.noreply.github.com" ]
54312493+CIA66@users.noreply.github.com
39d9d78ef6e729663820a0b1308fe0d0c377e597
2252d70a654948b5aadb06a1158d97e646b8097f
/Competitive Programming/Codeforces/Edu94(practice)/1.cpp
bc23631fff4b3979eeff78d43eb5edd2a603fc15
[]
no_license
spashal/Competitive-Programming
1b02aea6496f82920924b714eb857189c1542d63
f68e7bdf05dad9eab41bee0c2d9558f92068c244
refs/heads/master
2023-07-26T16:26:36.633063
2021-09-09T04:15:21
2021-09-09T04:15:21
267,501,288
0
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; ll n, m, t, a[100005]; vector< ll > adj[100005]; #define ari for( int i = 0 ; i < n ; i++ ) cin >> a[i]; #define ginp for( int i = 0 ; i < m ; i++ ){ int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u);} #define pb push_back #define ss second #define ff first #define fs first.second #define fff first.first #define sss second.second #define sf second.first #define mp make_pair void printar(vector< ll > ar, ll l, ll r){ for(int i = l ; i < r ; i++) cout << ar[i] << " "; cout << endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> t; while( t-- ){ cin >> n; string s; cin >> s; for(int i = 0 ; i <= 2 * n - 2 ; i += 2) cout << s[i]; cout << endl; } return(0); }
[ "palash.sharma@students.iiit.ac.in" ]
palash.sharma@students.iiit.ac.in
5ac0a4c9a8731d861ba3e4b6e89b2207e6c4f6b7
98c148cd57704ebcd480e2f3acfc1bab4025b985
/EsLib/BillboardObject.h
31a5be20dcfca67b75d1579f7a5b1aeb55424c43
[]
no_license
tomas0716/Square
40c1306603a5b3b56eab1ba3cc3db0409438e50d
f9751f4e6c2f1478c03855115f417cb7a9bf01d3
refs/heads/main
2023-04-13T06:29:57.747244
2021-05-03T04:18:12
2021-05-03T04:18:12
363,809,360
0
0
null
null
null
null
UTF-8
C++
false
false
122
h
#pragma once class IBillboardObject : public IGwRefObject { public: IBillboardObject(); virtual ~IBillboardObject(); };
[ "tomas0716@gmail.com" ]
tomas0716@gmail.com
dee2fee53148eedde782c7517d006444bd66b958
1305023dc5933375d916d3d0221fa8b5f8526628
/Seminar/Week7-staticTemplate/Solutions/Matrix/Matrix.h
c88105813aa41f4c0d0a8be100e0232c56a72d8e
[]
no_license
RosinaGeorgieva/ObjectOrientedProgramming2021
60720fbd9f5e4d3532c747ff3ec20324c1411ec7
5ae0ca4b553e10df1e7a5d6566932c68643402da
refs/heads/main
2023-05-23T18:18:46.296181
2021-06-21T16:44:03
2021-06-21T16:44:03
341,258,041
0
0
null
2021-02-22T16:08:18
2021-02-22T16:08:17
null
UTF-8
C++
false
false
676
h
#ifndef MATRIX_H #define MATRIX_H #include <iostream> #include <fstream> template <typename T> class Matrix { private: T **mData; size_t mRows; size_t mCols; void copy(const Matrix &rhs); void free(); static const int INITIAL_DIMENTION = 3; public: Matrix(size_t rows = INITIAL_DIMENTION, size_t cols = INITIAL_DIMENTION); Matrix(const Matrix &rhs); Matrix &operator=(const Matrix &rhs); ~Matrix(); void setElement(size_t i, size_t j, T element); Matrix<T> operator+(const Matrix &rhs); Matrix<T> operator*(const Matrix &rhs); void print() const; template <typename U> friend std::ostream &operator<<(std::ostream &os, const Matrix<U> &matrix); }; #endif
[ "ajabaja16@gmail.com" ]
ajabaja16@gmail.com
8accec26f53872dd25f48bf9b9f3b6c13e454182
7dcdecdf8fee6671be0f3f24ef8918853978a2e7
/seb/arm_code/TWI_slaveArm/TWI_slaveArm.ino
2522d8c6cf0c320a10c211ec239f1a2b7977aefe
[]
no_license
sebhero/Consuela
15e03de86f5dc9af2505f8c9692cc67bde07c489
217acc3220c6e7076b84a5654d7a180578b9da1c
refs/heads/master
2021-01-19T03:07:36.602903
2017-05-30T11:45:26
2017-05-30T11:45:26
87,305,072
2
1
null
null
null
null
UTF-8
C++
false
false
8,243
ino
// // Created by Sebastian Boreback on 2017-05-12. // #include <Arduino.h> #include <Wire.h> typedef enum { SOCK = 2, SQUARE = 3, GLASS = 4, BOXGOAL = 5 } Object; typedef struct { //distances are in cm from center of robot uint8_t boxDistance; //angles in degrees uint8_t boxAngle; //distances are in cm from center of robot uint8_t objectDistance; uint8_t objectAngle; //Boolean. true that arm can collect all obj. then dropoff //false if need to dropoff each obj. after pickup uint8_t collectAll; //just to check if the struct is set uint8_t hasData; } arminfo_t; //Holds info about each object position typedef struct { //the type of object Object theObject; // x position of object int16_t xpos; //y position of object int16_t ypos; } objectinfo_t; //TWI state typedef enum { TWI_CMD_ARM_INIT = 0x20, TWI_CMD_DROPOFF_START = 0x21, TWI_CMD_PICKUP_START = 0x22, TWI_CMD_DROPOFF_STATUS = 0x23, TWI_CMD_PICKUP_STATUS = 0x24, TWI_CMD_ERROR = 0x25, IDLE = 0x0 } TwiCmd; typedef enum { //retuns distance to box goal, and angle to set robot for dropoff TWI_CMD_ARM_REQ_BOX_INFO = 2, //returns distance to object and angle for collect TWI_CMD_ARM_REQ_OBJ_INFO = 3, TWI_CMD_ARM_REQ_COLLECT_INFO = 4 } TwiCmdInitReq; typedef enum { PICKUP_DONE = 2, PICKUP_FORWARD = 3, PICKUP_BACKWARD = 4, PICKUP_RUNNING = 5, PICKUP_FAILED = 6, PICKUP_DONE_DRIVE = 7, PICKUP_IDLE = 8, PICKUP_ROTATE_L = 9, PICKUP_ROTATE_R = 10 } PickupStatus; typedef enum { DROPOFF_DONE = 2, DROPOFF_RUNNING = 3, DROPOFF_FAILED = 4, DROPOFF_IDLE = 5 } DropoffStatus; //todo remove typedef enum FSMSTATES { ARM_IDLE = 2, ARM_PICKUP = 3, ARM_DROPOFF = 4 } STATE; //PickupStatus currentPickupState = PICKUP_IDLE; //PickupStatus nextPickupState= PICKUP_IDLE; //DropoffStatus currentDropOffState = DROPOFF_IDLE; //DropoffStatus nextDropOffState= DROPOFF_IDLE; //FSM state for the arm TwiCmd rxCurrent; TwiCmd rxNext; /***********************/ //variables uint8_t recivedData[3] = {0}; uint8_t txBuff[3] = {0}; arminfo_t theArm; //send to master PickupStatus txPickupStatus; //recive from master PickupStatus rxPickupStatus; DropoffStatus rxDropoffStatus; DropoffStatus txDropoffStatus; uint8_t run; void handleReadCmd() { //data to send //uint8_t data[3] = {}; Serial.println("handleReadCmd"); uint8_t cmd = recivedData[0]; switch (cmd) { case TWI_CMD_ARM_INIT: Serial.println("TWI_CMD_ARM_INIT"); txBuff[0] = cmd; switch (recivedData[1]) { case TWI_CMD_ARM_REQ_BOX_INFO: //Serial.println("TWI_CMD_ARM_REQ_BOX_INFO"); txBuff[1] = theArm.boxDistance; txBuff[2] = theArm.boxAngle; break; case TWI_CMD_ARM_REQ_OBJ_INFO: //Serial.println("TWI_CMD_ARM_REQ_OBJ_INFO:"); txBuff[1] = theArm.objectDistance; txBuff[2] = theArm.objectAngle; break; case TWI_CMD_ARM_REQ_COLLECT_INFO: //Serial.println("TWI_CMD_ARM_REQ_COLLECT_INFO:"); txBuff[1] = theArm.collectAll; break; default: Serial.println("ERR Unhandle armInfo"); break; } break; case TWI_CMD_DROPOFF_START: //todo implement // //Serial.println("TWI_CMD_DROPOFF_START"); // //set nextstate to dropoff in FSM // rxCurrent = (TwiCmd) cmd; // //rxDropoffStatus = DROPOFF_RUNNING; // txBuff[0] = cmd; // txBuff[1] = rxDropoffStatus; break; case TWI_CMD_PICKUP_START: Serial.println("TWI_CMD_PICKUP_START"); //start pickup in FSM, mainloop rxNext = (TwiCmd) cmd; //txPickupStatus = PICKUP_RUNNING; rxPickupStatus = PICKUP_RUNNING; txBuff[0] = TWI_CMD_PICKUP_STATUS; txBuff[1] = txPickupStatus; break; case TWI_CMD_PICKUP_STATUS: Serial.println("TWI_CMD_PICKUP_STATUS"); if (recivedData[1] == PICKUP_DONE_DRIVE) { rxPickupStatus = (PickupStatus) recivedData[1]; } txBuff[0] = TWI_CMD_PICKUP_STATUS; txBuff[1] = txPickupStatus; break; case TWI_CMD_DROPOFF_STATUS: //todo implement // //Serial.println("TWI_CMD_DROPOFF_STATUS"); // txBuff[0] = cmd; // txBuff[1] = rxDropoffStatus; break; case TWI_CMD_ERROR: Serial.println("TWI_CMD_ERROR"); break; default: printf("error\n"); break; } } // function that executes whenever data is requested by master // this function is registered as an event, see setup() void requestEvent() { //todo del // Serial.println("sendREQ"); //Serial.println("sending"); //Serial.println(txBuff[0],HEX); //Serial.println(txBuff[1]); //Serial.println(txBuff[2]); //todo del Wire.write(txBuff, 3); //reset states if (txBuff[0] == PICKUP_DONE) { Serial.println("Sent to master = PICKUP_DONE"); txPickupStatus = PICKUP_IDLE; rxDropoffStatus = DROPOFF_IDLE; rxCurrent = IDLE; } //reset states if (txBuff[0] == DROPOFF_DONE) { Serial.println("Sent to master = DROPOFF_DONE"); txDropoffStatus = DROPOFF_IDLE; rxPickupStatus = PICKUP_IDLE; rxCurrent = IDLE; } txBuff[0] = 0; txBuff[1] = 0; txBuff[2] = 0; //end of request } // function that executes whenever data is received from master // this function is registered as an event, see setup() void receiveEvent(int howMany) { // Serial.println("Handling new cmd Req"); Serial.print("how many: "); Serial.println(howMany); if (3 <= howMany) { int i = 0; while (Wire.available()) { recivedData[i] = (uint8_t) Wire.read(); i++; } handleReadCmd(); } //if its a command from master. if (howMany <= 1) { Wire.read(); // receive byte as an integer //Serial.println("on or less"); } //end of receive } //todo dummy int movedArmDown; int movedArmUp; void setup() { Wire.begin(2); // join i2c bus with address #2 Wire.onRequest(requestEvent); // register event Wire.onReceive(receiveEvent); // register event Serial.begin(9600); // start serial for output run = 1; theArm.boxDistance = 30;//cm to goalbox theArm.boxAngle = 20;//infront angle theArm.objectDistance = 40;//distance from obj theArm.objectAngle = 90;//from behind theArm.collectAll = 1;//collect all //init state for data to send txPickupStatus = PICKUP_IDLE; txDropoffStatus = DROPOFF_IDLE; //init state for data to recive rxPickupStatus = PICKUP_IDLE; rxDropoffStatus = DROPOFF_IDLE; //todo for test remove movedArmDown = 0; movedArmUp = 0; //todo remove end //cmds that got in -> state for arm Serial.println("SETUP DONE"); } void loop() { //check if we are done //since we are already in a loop if (run) { //handle pickup request switch (rxCurrent) { case TWI_CMD_ARM_INIT: //do nottin break; case TWI_CMD_PICKUP_START: Serial.println("TWI_CMD_PICKUP_START"); txPickupStatus = PICKUP_RUNNING; movedArmDown++; Serial.println("txPickupStatus= PICKUP_RUNNING"); break; case TWI_CMD_PICKUP_STATUS: Serial.println("TWI_CMD_PICKUP_STATUS"); movedArmDown++; if (movedArmDown >= 100) { //arm is donw move frwd txPickupStatus = PICKUP_FORWARD; Serial.println("txPickupStatus= PICKUP_FORWARD"); } //wait for done moving if (rxPickupStatus == PICKUP_DONE_DRIVE) { Serial.println("rxPickupStatus= PICKUP_DONE_DRIVE"); movedArmUp++; txPickupStatus = PICKUP_RUNNING; Serial.println("txPickupStatus= PICKUP_RUNNING"); } if (movedArmUp >= 100) { //we are done txPickupStatus = PICKUP_DONE; Serial.println("txPickupStatus= PICKUP_DONE"); //twi resets status to idle in //requestEvent() } break; case TWI_CMD_DROPOFF_START: break; case TWI_CMD_DROPOFF_STATUS: break; case TWI_CMD_ERROR: break; case IDLE: //Serial.println("IDLE"); //delay(300); break; } delay(100); rxCurrent = rxNext; } }
[ "trevligt.att.ses@gmail.com" ]
trevligt.att.ses@gmail.com
26671f46f3bf6eeb5b004ccfcbdf3dc1640d9ea3
d1853dc32105f49790ed299bcca2db3b1d718ece
/codeforces/467/B.cpp
c390f73a5f6e9b989dd796e76fa61a1a27eaf495
[]
no_license
towhid1zaman/Problem__Solving
a8abbd77c68c6f1e9ff8ceecd9332a3d15f741cd
1407bc0d44165827e8db5599e75115961d569315
refs/heads/master
2023-06-05T10:56:17.151354
2021-06-20T19:46:00
2021-06-26T04:47:16
326,334,514
0
0
null
null
null
null
UTF-8
C++
false
false
1,545
cpp
#include "bits/stdc++.h" using namespace std; typedef long long LL; #define nl "\n" #define X first #define Y second #define MAX INT_MAX #define pb(a) push_back(a) #define mp(a,b) make_pair(a,b) #define check() {printf("OK\n");} #define srt(v) sort(v.begin(),v.end()) #define rev(v) reverse(v.begin(),v.end()) #define mem(a,x) memset(a,x,sizeof(a)) #define rep(i, n) for(int i = 0; i < (n); ++i) #define rep1(i, n) for(int i = 1; i <= (n); ++i) #define rep2(i,a,b) for(int i =(a); i <=(b); ++i) #define maxv(v) *max_element(v.begin(),v.end()) #define minv(v) *min_element(v.begin(),v.end()) #define each(it,s) for(auto it = s.begin(); it != s.end(); ++it) #define f() {ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);} #define unq(v) srt(v),(v).erase(unique((v).begin(),(v).end()),(v).end()) #define MOD 1000000007 // (int)1e9+7 typedef vector <int> vi; typedef pair <int, int> pii; typedef vector<pii>vip; int countsetbit(int n) { int cnt = 0; while(n>0) { cnt+=(n&1); n = n>>1; } return cnt; } int main(){f(); int n,k,m; cin>>n>>m>>k; vector<int>v(m); for(int i = 0; i<m;i++) { cin>>v[i]; } int x; cin>>x; int res=0; /// __builtin_popcount(int) function is used to count the number of one’s(set bits) in an integer. for(int i = 0; i<m;i++) { if(__builtin_popcount(v[i]^x)<=k){ res++; } } cout<<res<<nl; return 0; }
[ "towhid1zaman@gmail.com" ]
towhid1zaman@gmail.com
95bca7ad31d2f198e6b82c42f5533930960732d8
58b57a2e4194a54225380725f77989ece3262371
/kernel/kernelUtil.cpp
8ab9c4eb7d241b14ec4489a8579bb057f2d353b9
[]
no_license
edmundosik/x86_64
936980f9618dee6319c70040812ed81fb6064c7e
4fe1865c6face80a02364b325a816ef9894724e4
refs/heads/master
2023-07-04T11:37:12.513481
2021-08-02T22:33:40
2021-08-02T22:33:40
387,918,316
0
1
null
null
null
null
UTF-8
C++
false
false
5,000
cpp
#include "kernelUtil.h" KernelInfo kernelInfo; uint32_t bgColor; uint32_t fgColor; ACPI::SDTHeader* xsdt; ACPI::MCFGHeader* mcfg; void PrepareMemory(BootInfo* bootInfo) { uint64_t mMapEntries = bootInfo->mMapSize / bootInfo->mMapDescSize; PageAllocator = PageFrameAllocator(); PageAllocator.ReadEFIMemoryMap(bootInfo->mMap, bootInfo->mMapSize, bootInfo->mMapDescSize); uint64_t kernelSize = (uint64_t)&_KernelEnd - (uint64_t)&_KernelStart; uint64_t kernelPages = (uint64_t)kernelSize / 4096 + 1; PageAllocator.LockPages(&_KernelStart, kernelPages); PageTable* PML4 = (PageTable*)PageAllocator.RequestPage(); memset(PML4, 0, 0x1000); gPageTableManager = PageTableManager(PML4); for(uint64_t i = 0; i < GetMemorySize(bootInfo->mMap, mMapEntries, bootInfo->mMapDescSize); i += 0x1000) { gPageTableManager.MapMemory((void*)i, (void*)i); } uint64_t fbBase = (uint64_t)bootInfo->framebuffer->BaseAddress; uint64_t fbSize = (uint64_t)bootInfo->framebuffer->BufferSize + 0x1000; PageAllocator.LockPages((void*)fbBase, fbSize / 0x1000 + 1); for(uint64_t i = fbBase; i < fbBase + fbSize; i += 4096) { gPageTableManager.MapMemory((void*)i, (void*)i); } asm("mov %0, %%cr3" : : "r" (PML4)); kernelInfo.pageTableManager = &gPageTableManager; } IDTR idtr; void SetIDTGate(void* handler, uint8_t entryOffset, uint8_t typeAttr, uint8_t selector) { IDTDescEntry* interrupt = (IDTDescEntry*)(idtr.Offset + entryOffset * sizeof(IDTDescEntry)); interrupt->SetOffset((uint64_t)handler); interrupt->type_attr = typeAttr; interrupt->selector = selector; } void PrepareInterrupts() { idtr.Limit = 0x0fff; idtr.Offset = (uint64_t)PageAllocator.RequestPage(); SetIDTGate((void*)PageFault_Handler, 0xE, IDT_TA_InterruptGate, 0x08); SetIDTGate((void*)DoubleFault_Handler, 0x8, IDT_TA_InterruptGate, 0x08); SetIDTGate((void*)GPFault_Handler, 0xD, IDT_TA_InterruptGate, 0x08); SetIDTGate((void*)KeyboardInt_Handler, 0x21, IDT_TA_InterruptGate, 0x08); SetIDTGate((void*)MouseInt_Handler, 0x2C, IDT_TA_InterruptGate, 0x08); SetIDTGate((void*)PITInt_Handler, 0x20, IDT_TA_InterruptGate, 0x08); asm("lidt %0" : : "m" (idtr)); RemapPIC(); } void PrepareACPI(BootInfo* bootInfo) { xsdt = (ACPI::SDTHeader*)(bootInfo->rsdp->XSDTAddress); mcfg = (ACPI::MCFGHeader*)ACPI::FindTable(xsdt, (char*)"MCFG"); //PCI::EnumeratePCI(mcfg); } BasicRenderer r = BasicRenderer(NULL, NULL); KernelInfo InitializeKernel(BootInfo* bootInfo) { r = BasicRenderer(bootInfo->framebuffer, bootInfo->psf1_font); renderer = &r; PrepareMemory(bootInfo); memset(bootInfo->framebuffer->BaseAddress, 0, bootInfo->framebuffer->BufferSize); // clear screen bgColor = 0xff4B5263; fgColor = 0xffC9CBD0; renderer->clearColor = bgColor; renderer->clear(); renderer->color = fgColor; GDTDescriptor gdtDescriptor; gdtDescriptor.Size = sizeof(GDT) - 1; gdtDescriptor.Offset = (uint64_t)&DefaultGDT; LoadGDT(&gdtDescriptor); renderer->print("[ "); renderer->color = 0xff00ff00; renderer->print("OK"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("GDT loaded"); renderer->nextLine(); InitHeap((void*)0x0000100000000000, 0x10); renderer->print("[ "); renderer->color = 0xff00ff00; renderer->print("OK"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("Heap initialized"); renderer->nextLine(); PrepareInterrupts(); renderer->print("[ "); renderer->color = 0xff00ff00; renderer->print("OK"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("Interrupts initialized"); renderer->nextLine(); InitPS2Mouse(); renderer->print("[ "); renderer->color = 0xff00ff00; renderer->print("OK"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("PS/2 Mouse initialized"); renderer->nextLine(); PrepareACPI(bootInfo); renderer->print("[ "); renderer->color = 0xff00ff00; renderer->print("OK"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("ACPI initialized"); renderer->nextLine(); outb(PIC1_DATA, 0b11111000); outb(PIC2_DATA, 0b11101111); renderer->print("[ "); renderer->color = 0xff00ff00; renderer->print("OK"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("Unmasked interrupts"); renderer->nextLine(); PIT::SetDivisor(65535); renderer->print("[ "); renderer->color = 0xff00ff00; renderer->print("OK"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("PIT initialized"); renderer->nextLine(); if(InitSerial() == 0) { renderer->print("[ "); renderer->color = 0xff00ff00; renderer->print("OK"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("Serial initialized"); renderer->nextLine(); } else { renderer->print("[ "); renderer->color = 0xffff0000; renderer->print("ERROR"); renderer->color = fgColor; renderer->print(" ] "); renderer->print("Serial initialization failed"); renderer->nextLine(); } asm("sti"); return kernelInfo; }
[ "biorlive@gmail.com" ]
biorlive@gmail.com
bcfa676d27393e77cf85ea47e4d5ff5d06f4cf90
c8102b373a50ca85302f2322def4dcd344e92c82
/백준/Minimum Binary Number.cpp
d7f7f34030eda2495c9b401b2ea14a8add482db7
[]
no_license
deokhk/Algorithm
ef4a0a366bb36a24b5b1f33275d22bbf61d0d56d
8df39077e75276005ce9532e29d33d803a4c7dbb
refs/heads/master
2020-03-14T11:33:08.233542
2019-06-27T04:19:23
2019-06-27T04:19:23
131,592,638
1
0
null
null
null
null
UTF-8
C++
false
false
362
cpp
#include <iostream> #include <string> using namespace std; int main() { int length; int count = 0; string s; cin >> length >> s; for (int i = 0; i < length; i++) { if (s[i] == '1') { count++; } } string res = ""; if (count >= 1) { res = res + "1"; } for (int k = 0; k < length - count; k++) { res = res + "0"; } cout << res << endl; }
[ "deokhk@postech.ac.kr" ]
deokhk@postech.ac.kr