blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
cadb80bc4f86e04c8d186e4b85a0be1b3aa6271f
d5b276d168f4c2c2f70aeedf36d94e856134f670
/src/AirlineGraph.cpp
ebb1a8a1874abc39dbb2c023456a7c1b3ab9c9a2
[ "MIT" ]
permissive
lixiaoyu0611/AirlineSystem
0be5b30fef6c431d4012f7e5a5a093e75650f925
dd567c0d011568013992db245cd4e29bfbde615a
refs/heads/master
2021-05-05T20:18:57.644606
2017-12-29T08:02:08
2017-12-29T08:02:08
115,320,573
0
0
MIT
2017-12-29T08:02:09
2017-12-25T08:18:28
C++
GB18030
C++
false
false
26,605
cpp
#include "AirlineGraph.h" AirlineGraph::AirlineGraph() { LoadAirport(); LoadAirline(); } AirlineGraph::~AirlineGraph() { //dtor } //读入机场信息 void AirlineGraph::LoadAirport() { Array AirportArray; ifstream infile; string s; infile.open("data/Airport.json"); ostringstream tmp; tmp<<infile.rdbuf(); s=tmp.str(); AirportArray.parse(s); //解析json mAirportNumber=AirportArray.size(); mAirportHeadArray=new Airport*[mAirportNumber]; for(int i=0;i<mAirportNumber;i++) //生成顶点表 { mAirportHeadArray[i]=new Airport(); mAirportHeadArray[i]->No=AirportArray.get<Object>(i).get<Number>("序号"); mAirportHeadArray[i]->mAirportName=AirportArray.get<Object>(i).get<String>("机场"); mAirportHeadArray[i]->mShortName=AirportArray.get<Object>(i).get<String>("机场代号"); mAirportHeadArray[i]->mLocation=AirportArray.get<Object>(i).get<String>("城市"); } //cout<<AirportArray.json(); } //读入航线信息 void AirlineGraph::LoadAirline() { Array AirlineArray; ifstream infile; string s; infile.open("data/Airline.json"); ostringstream tmp; tmp<<infile.rdbuf(); s=tmp.str(); AirlineArray.parse(s); //解析json mAirlineVector=new vector<Airline*>(); for(int i=0;i<AirlineArray.size();i++) //保存航线到vector { Airline* airline=new Airline(); airline->mAirlineName=AirlineArray.get<Object>(i).get<String>("航班号"); airline->mCompany=AirlineArray.get<Object>(i).get<String>("公司"); airline->mDepartureAirport=AirlineArray.get<Object>(i).get<String>("起飞机场"); airline->mArrivalAirport=AirlineArray.get<Object>(i).get<String>("到达机场"); airline->mDepartureTime=AirlineArray.get<Object>(i).get<String>("起飞时间"); airline->mArrivalTime=AirlineArray.get<Object>(i).get<String>("到达时间"); airline->mAirplaneModel=AirlineArray.get<Object>(i).get<String>("机型"); airline->mDepartureCity=AirlineArray.get<Object>(i).get<String>("起始城市"); airline->mArrivalCity=AirlineArray.get<Object>(i).get<String>("到达城市"); airline->mPrice=AirlineArray.get<Object>(i).get<Number>("价格"); airline->mIntDiscount=AirlineArray.get<Object>(i).get<Number>("最大折扣"); airline->mCapacity=AirlineArray.get<Object>(i).get<Number>("满载"); airline->mCurrentNumber=AirlineArray.get<Object>(i).get<Number>("当前人数"); mAirlineVector->push_back(airline); Airport* dAirport=GetAirportByName(airline->mDepartureAirport); Airport* aAirport=GetAirportByName(airline->mArrivalAirport); if(dAirport!=NULL&&aAirport!=NULL) //判断机场是否存在 { airline->mAirportNo=aAirport->No; InsertAirlineGraph(dAirport,airline); //插入到图 } } infile.close(); //cout<<AirlineArray.json(); } //通过航班号查询航班 Airport* AirlineGraph::GetAirportByName(string name) { for(int i=0;i<mAirportNumber;i++) { if(mAirportHeadArray[i]->mAirportName==name) { // cout<<mAirportHeadArray[i]->mAirportName; return mAirportHeadArray[i]; } } return NULL; } //插入航班 创建时调用 void AirlineGraph::InsertAirlineGraph(Airport* airport,Airline* airline) { Airline* line=airport->mAdjAirline; if(line==NULL) { airport->mAdjAirline=airline; }else { //cout<<line->mAirlineName; while(line->mNextAirline!=NULL) { line=line->mNextAirline; } line->mNextAirline=airline; } } void AirlineGraph::RemoveAirlineGraph(Airline* airline) { for(int i=0;i<mAirportNumber;i++) { Airline* line=mAirportHeadArray[i]->mAdjAirline; if(line==airline) { mAirportHeadArray[i]->mAdjAirline=line->mNextAirline; delete line; return; }else { Airline* pline=line; line=line->mNextAirline; while(line!=NULL) { if(line==airline) { pline->mNextAirline=line->mNextAirline; delete line; return; } pline=line; line=line->mNextAirline; } } } } //展示航班 void AirlineGraph::ShowAirlineGraph() { cout.setf(ios::left); cout<<endl; for(int i=0;i<mAirportNumber;i++) { cout<<endl; cout<<"======================================================================================================================"; Airport* airport=mAirportHeadArray[i]; Airline* airline=airport->mAdjAirline; cout<<endl<<"【"<<airport->mLocation<<" - "<<airport->mAirportName<<"】"<<"\t"<<endl<<endl; while(airline!=NULL) { cout<<airline->mAirlineName<<"\t"; airline=airline->mNextAirline; } } cout<<endl<<"======================================================================================================================"<<endl; } //生成json Array AirlineGraph::GenerateAirlineJson() { Array jsonArray; for(int i=0;i<mAirportNumber;i++) { Airport* airport=mAirportHeadArray[i]; Airline* airline=airport->mAdjAirline; while(airline!=NULL) { Object jsonObj; jsonObj<<"公司"<<airline->mCompany; jsonObj<<"航班号"<<airline->mAirlineName; jsonObj<<"起始城市"<<airline->mDepartureCity; jsonObj<<"起飞机场"<<airline->mDepartureAirport; jsonObj<<"到达城市"<<airline->mArrivalCity; jsonObj<<"到达机场"<<airline->mArrivalAirport; jsonObj<<"起飞时间"<<airline->mDepartureTime; jsonObj<<"到达时间"<<airline->mArrivalTime; jsonObj<<"机型"<<airline->mAirplaneModel; jsonObj<<"价格"<<airline->mPrice; jsonObj<<"最大折扣"<<airline->mIntDiscount; jsonObj<<"满载"<<airline->mCapacity; jsonObj<<"当前人数"<<airline->mCurrentNumber; jsonArray<<jsonObj; airline=airline->mNextAirline; } } return jsonArray; } void AirlineGraph::WriteAirlineJson() { ofstream outfile; outfile.open("data/Airline.json"); Array jsonArray=GenerateAirlineJson(); //cout<<jsonArray.json(); outfile<<jsonArray.json(); outfile.close(); } int AirlineGraph::GetAirlineNumber() { return mAirlineVector->size(); } void AirlineGraph::InsertAirline(Airline* airline) { Airport* dAirport=GetAirportByName(airline->mDepartureAirport); Airport* aAirport=GetAirportByName(airline->mArrivalAirport); if(dAirport==NULL||aAirport==NULL) { cout<<endl<<"机场不存在!"<<endl; return; }else { airline->mDepartureCity=dAirport->mLocation; airline->mArrivalCity=aAirport->mLocation; mAirlineVector->push_back(airline); InsertAirlineGraph(dAirport,airline); //插入到图 WriteAirlineJson(); //写出,更新航线数据文件 cout<<endl<<"航班"<<airline->mAirlineName<<"录入成功!"<<endl; } } void AirlineGraph::RemoveAirline(Airline* airline) { for(vector<Airline*>::iterator it=mAirlineVector->begin();it!=mAirlineVector->end();it++) { if((*it)==airline) { mAirlineVector->erase(it); break; } } RemoveAirlineGraph(airline); WriteAirlineJson(); } string AirlineGraph::GetAirportLocation(string airportName) { return GetAirportByName(airportName)->mLocation; } //输入航班号获取所有可能的航线 vector<Airline*>* AirlineGraph::FindAirlineByName(string name) { vector<Airline*>* vec=new vector<Airline*>(); for(int i=0;i<mAirportNumber;i++) { Airport* airport=mAirportHeadArray[i]; Airline* airline=airport->mAdjAirline; while(airline!=NULL) { if(airline->mAirlineName==name) { vec->push_back(airline); } airline=airline->mNextAirline; } } return vec; } void AirlineGraph::ShowAllAirlineToUser() { cout.setf(ios::left); cout<<endl; for(int i=0;i<mAirportNumber;i++) { ShowAirlineByAirport(i); } cout<<endl<<"========================================================================================================================================================================"<<endl; } void AirlineGraph::ShowAirlineByAirport(int no) { vector<Airline*> vec; Airport* airport=mAirportHeadArray[no]; Airline* airline=airport->mAdjAirline; while(airline!=NULL) { vec.push_back(airline); airline=airline->mNextAirline; } for(int i=1;i<vec.size();i++) //插入排序 { Airline* airline=vec[i]; int j; for(j=i-1;j>=0&&(airline->GetAirlineDepartureTimeStamp())<vec[j]->GetAirlineDepartureTimeStamp();j--) { vec[j+1]=vec[j]; } vec[j+1]=airline; } cout.setf(ios::left); cout<<endl; cout<<"========================================================================================================================================================================"<<endl; /*Airport* airport=mAirportHeadArray[no]; Airline* airline=airport->mAdjAirline;*/ cout<<endl<<"【"<<airport->mLocation<<" - "<<airport->mAirportName<<"】"<<"\t"<<endl<<endl; cout<<setw(10)<<"航班号"; cout<<setw(25)<<"航空公司"; cout<<setw(10)<<"出发地"; cout<<setw(20)<<"起飞机场"; cout<<setw(10)<<"目的地"; cout<<setw(20)<<"着陆机场"; cout<<setw(10)<<"起飞时间"; cout<<setw(10)<<"抵达时间"; cout<<setw(8)<<"机型"; cout<<setw(8)<<"票价"; cout<<setw(8)<<"折扣"; cout<<setw(9)<<"折后票价"; cout<<setw(8)<<"载客量"; cout<<setw(8)<<"已售"; cout<<setw(8)<<"余票"; cout<<endl<<endl; for(vector<Airline*>::iterator it=vec.begin();it!=vec.end();it++) { Airline* airline=*it; cout<<setw(10)<<airline->mAirlineName; cout<<setw(25)<<airline->mCompany; cout<<setw(10)<<airline->mDepartureCity; cout<<setw(20)<<airline->mDepartureAirport; cout<<setw(10)<<airline->mArrivalCity; cout<<setw(20)<<airline->mArrivalAirport; cout<<setw(10)<<airline->mDepartureTime; cout<<setw(10)<<airline->mArrivalTime; cout<<setw(8)<<airline->mAirplaneModel; cout<<setw(8)<<airline->mPrice; cout<<setw(8)<<airline->mIntDiscount/1000.0; cout<<setw(9)<<airline->mPrice*(1-airline->mIntDiscount/1000.0); cout<<setw(8)<<airline->mCapacity; cout<<setw(8)<<airline->mCurrentNumber; cout<<setw(8)<<airline->mCapacity-airline->mCurrentNumber; cout<<endl; } } vector<int>* AirlineGraph::GetAirportIdByLocation(string loc) { vector<int>* vec=new vector<int>(); for(int i=0;i<mAirportNumber;i++) { if(mAirportHeadArray[i]->mLocation==loc) { vec->push_back(i); } } return vec; } vector<Airline*>* AirlineGraph::GetAirlineByDACity(string departure,string arrival) { vector<Airline*>* vec=new vector<Airline*>(); vector<int>* dAirportVec=new vector<int>(); dAirportVec=GetAirportIdByLocation(departure); for(vector<int>::iterator dit=dAirportVec->begin();dit!=dAirportVec->end();dit++) { Airline* airline=mAirportHeadArray[*dit]->mAdjAirline; while(airline!=NULL) { if(airline->mArrivalCity==arrival) { vec->push_back(airline); } airline=airline->mNextAirline; } } return vec; } void AirlineGraph::ShowDACityAirlineByDiscountPrice(string departure,string arrival) { vector<Airline*>* vec=GetAirlineByDACity(departure,arrival); for(int i=1;i<vec->size();i++) //插入排序 { Airline* airline=(*vec)[i]; int j; for(j=i-1;j>=0&&(airline->GetPriceAfterDiscount())<(*vec)[j]->GetPriceAfterDiscount();j--) { (*vec)[j+1]=(*vec)[j]; } (*vec)[j+1]=airline; } cout.setf(ios::left); cout<<endl<<"========================================================================================================================================================================"<<endl; cout<<setw(10)<<"航班号"; cout<<setw(25)<<"航空公司"; cout<<setw(10)<<"出发地"; cout<<setw(20)<<"起飞机场"; cout<<setw(10)<<"目的地"; cout<<setw(20)<<"着陆机场"; cout<<setw(10)<<"起飞时间"; cout<<setw(10)<<"抵达时间"; cout<<setw(8)<<"机型"; cout<<setw(8)<<"票价"; cout<<setw(8)<<"折扣"; cout<<setw(9)<<"折后票价"; cout<<setw(8)<<"载客量"; cout<<setw(8)<<"已售"; cout<<setw(8)<<"余票"; cout<<endl<<endl; for(vector<Airline*>::iterator it=vec->begin();it!=vec->end();it++) { Airline* airline=*it; cout<<setw(10)<<airline->mAirlineName; cout<<setw(25)<<airline->mCompany; cout<<setw(10)<<airline->mDepartureCity; cout<<setw(20)<<airline->mDepartureAirport; cout<<setw(10)<<airline->mArrivalCity; cout<<setw(20)<<airline->mArrivalAirport; cout<<setw(10)<<airline->mDepartureTime; cout<<setw(10)<<airline->mArrivalTime; cout<<setw(8)<<airline->mAirplaneModel; cout<<setw(8)<<airline->mPrice; cout<<setw(8)<<airline->mIntDiscount/1000.0; cout<<setw(9)<<airline->mPrice*(1-airline->mIntDiscount/1000.0); cout<<setw(8)<<airline->mCapacity; cout<<setw(8)<<airline->mCurrentNumber; cout<<setw(8)<<airline->mCapacity-airline->mCurrentNumber; cout<<endl; } cout<<endl<<"========================================================================================================================================================================"<<endl; } void AirlineGraph::ShowDACityAirlineByDepartureTime(string departure,string arrival) { vector<Airline*>* vec=GetAirlineByDACity(departure,arrival); for(int i=1;i<vec->size();i++) { Airline* airline=(*vec)[i]; int j; for(j=i-1;j>=0&&(airline->GetAirlineDepartureTimeStamp())<(*vec)[j]->GetAirlineDepartureTimeStamp();j--) { (*vec)[j+1]=(*vec)[j]; } (*vec)[j+1]=airline; } cout.setf(ios::left); cout<<endl<<"========================================================================================================================================================================"<<endl; cout<<setw(10)<<"航班号"; cout<<setw(25)<<"航空公司"; cout<<setw(10)<<"出发地"; cout<<setw(20)<<"起飞机场"; cout<<setw(10)<<"目的地"; cout<<setw(20)<<"着陆机场"; cout<<setw(10)<<"起飞时间"; cout<<setw(10)<<"抵达时间"; cout<<setw(8)<<"机型"; cout<<setw(8)<<"票价"; cout<<setw(8)<<"折扣"; cout<<setw(9)<<"折后票价"; cout<<setw(8)<<"载客量"; cout<<setw(8)<<"已售"; cout<<setw(8)<<"余票"; cout<<endl<<endl; for(vector<Airline*>::iterator it=vec->begin();it!=vec->end();it++) { Airline* airline=*it; cout<<setw(10)<<airline->mAirlineName; cout<<setw(25)<<airline->mCompany; cout<<setw(10)<<airline->mDepartureCity; cout<<setw(20)<<airline->mDepartureAirport; cout<<setw(10)<<airline->mArrivalCity; cout<<setw(20)<<airline->mArrivalAirport; cout<<setw(10)<<airline->mDepartureTime; cout<<setw(10)<<airline->mArrivalTime; cout<<setw(8)<<airline->mAirplaneModel; cout<<setw(8)<<airline->mPrice; cout<<setw(8)<<airline->mIntDiscount/1000.0; cout<<setw(9)<<airline->mPrice*(1-airline->mIntDiscount/1000.0); cout<<setw(8)<<airline->mCapacity; cout<<setw(8)<<airline->mCurrentNumber; cout<<setw(8)<<airline->mCapacity-airline->mCurrentNumber; cout<<endl; } cout<<endl<<"========================================================================================================================================================================"<<endl; } void AirlineGraph::ShowAirlineByCity(string city) { vector<int>* vec=GetAirportIdByLocation(city); for(int i=0;i<vec->size();i++) { ShowAirlineByAirport((*vec)[i]); } if(vec->size()>0) { cout<<endl<<"========================================================================================================================================================================"<<endl; }else { cout<<endl<<"无航班信息!"<<endl; } } void AirlineGraph::Book(Airline* airline) { airline->mCurrentNumber=airline->mCurrentNumber+1; //已订人数+1 WriteAirlineJson(); //写出,更新本地数据 } void AirlineGraph::Unsubscribe(BookOrder* bookOrder) { vector<Airline*>* vec=FindAirlineByName(bookOrder->mAirlineName); for(vector<Airline*>::iterator it=vec->begin();it!=vec->end();it++) { if((*it)->mDepartureAirport==bookOrder->mDepartureAirport&&(*it)->mArrivalAirport==bookOrder->mArrivalAirport) { (*it)->mCurrentNumber=(*it)->mCurrentNumber-1; //已订人数-1 WriteAirlineJson(); //写出,更新本地数据 break; } } cout<<"==========================================="<<endl; cout<<endl; cout<<"================ 退票成功 ================="<<endl; cout<<endl; cout<<setw(12)<<"姓名:"<<bookOrder->mName<<endl; cout<<setw(12)<<"证件号:"<<bookOrder->mIdNumber<<endl; cout<<setw(12)<<"航班号:"<<bookOrder->mAirlineName<<endl; cout<<setw(12)<<"航空公司:"<<bookOrder->mCompany<<endl; cout<<setw(12)<<"出发地:"<<bookOrder->mDepartureCity<<endl; cout<<setw(12)<<"目的地:"<<bookOrder->mArrivalCity<<endl; cout<<setw(12)<<"购买价格:"<<bookOrder->mPrice<<endl; cout<<endl; cout<<"==========================================="<<endl; } vector<Route*>* AirlineGraph::GetAdvisableRouteWithBFS(string departure,string arrival,int departureTime,int arrivalTime) { int InD[mAirportNumber]={0}; int visit[mAirportNumber]={0}; for(int i=0;i<mAirportNumber;i++) { Airline* airline=mAirportHeadArray[i]->mAdjAirline; while(airline!=NULL) { InD[GetAirportByName(airline->mArrivalAirport)->No]+=1; //统计机场入度 airline=airline->mNextAirline; } } vector<int>* dAirportId=GetAirportIdByLocation(departure); vector<int>* aAirportId=GetAirportIdByLocation(arrival); vector<Route>* mainVec=new vector<Route>(); vector<Route*>* retVec=new vector<Route*>(); for(int i=0;i<dAirportId->size();i++) { for(int j=0;j<aAirportId->size();j++) { BFS((*dAirportId)[i],(*aAirportId)[j],InD,visit,mainVec); for(int k=0;k<mAirportNumber;k++) { visit[k]=0; } } } for(vector<Route>::iterator it=mainVec->begin();it!=mainVec->end();it++) { if((*it).mAirlineVec[(*it).mAirlineVec.size()-1]->GetAirlineDepartureTimeStamp()<arrivalTime &&(*it).mAirlineVec[(*it).mAirlineVec.size()-1]->GetAirlineArrivalTimeStamp()<arrivalTime &&(*it).mAirlineVec[0]->GetAirlineDepartureTimeStamp()>departureTime &&(*it).mAirlineVec[0]->GetAirlineArrivalTimeStamp()>departureTime) //起降时间满足给定条件,并且不出现隔夜的情况 { (*it).SumToatalCost(); retVec->push_back(&(*it)); //筛选符合条件的结果,直接erase删除会出现 std::bad_alloc,原因未知 }else { //mainVec->erase(it); } } for(int i=1;i<retVec->size();i++) //插入排序 { Route* r=(*retVec)[i]; int j; for(j=i-1;j>=0&&(r->mTotalCost)<(*retVec)[j]->mTotalCost;j--) { (*retVec)[j+1]=(*retVec)[j]; } (*retVec)[j+1]=r; } return retVec; } void AirlineGraph::BFS(int f,int a,int* InD,int* visit,vector<Route>* mainVec) { int k=1; //参数k queue<Route> q; Route r; r.mPrevNo=f; q.push(r); while(!q.empty()) { Route r0=q.front(); q.pop(); Airline* airline=mAirportHeadArray[r0.mPrevNo]->mAdjAirline; while(airline!=NULL) { if(!r0.CheckPass(airline->mArrivalAirport)) { if(((r0.mAirlineVec.size()>0&&r0.mAirlineVec[r0.mAirlineVec.size()-1]->GetAirlineArrivalTimeStamp()<airline->GetAirlineDepartureTimeStamp()) ||r0.mAirlineVec.size()==0) //若不是始发航线,则需要判断前后航班时间是否赶得上 &&airline->GetAirlineDepartureTimeStamp()<airline->GetAirlineArrivalTimeStamp()) //不隔夜 { int no=GetAirportByName(airline->mArrivalAirport)->No; if(visit[no]<k*InD[no]) //入度的k倍,经过一个点是入度的10倍。决定BFS精密程度,但是运行时间会增大 { Route rNew=r0; rNew.mAirlineVec.push_back(airline); rNew.mPrevNo=no; visit[no]+=1; if(no!=a) { q.push(rNew); } else { mainVec->push_back(rNew); } } } } airline=airline->mNextAirline; } } } void AirlineGraph::DFS(int v,int a,int* InD,int* visit,vector< vector<Airline*> >* mainVec,vector<Airline*> routeVec) { if(v!=a) //未到达目的地 { visit[v]+=1; Airline* airline=mAirportHeadArray[v]->mAdjAirline; while(airline!=NULL) { int no=airline->mAirportNo; bool tag=0; for(int i=0;i<routeVec.size();i++) { if(routeVec[i]->mArrivalAirport==airline->mArrivalAirport) { tag=1; break; } } if(routeVec.size()==0) { if(visit[no]<InD[no]&&!tag) //比较访问次数,检测是否小于入度 { vector<Airline*> newRoute; for(vector<Airline*>::iterator it=routeVec.begin(); it!=routeVec.end(); it++) { newRoute.push_back(*it); } newRoute.push_back(airline); DFS(no,a,InD,visit,mainVec,newRoute); } } else if(routeVec[routeVec.size()-1]->GetAirlineArrivalTimeStamp()<airline->GetAirlineDepartureTimeStamp()/*&&airline->GetAirlineDepartureTimeStamp()<airline->GetAirlineArrivalTimeStamp()*/) { if(visit[no]<InD[no]&&!tag) //比较访问次数,检测是否小于入度 { vector<Airline*> newRoute; for(vector<Airline*>::iterator it=routeVec.begin(); it!=routeVec.end(); it++) { newRoute.push_back(*it); } newRoute.push_back(airline); DFS(no,a,InD,visit,mainVec,newRoute); } } airline=airline->mNextAirline; } }else //到达目的地,终止DFS { visit[v]+=1; mainVec->push_back(routeVec); //将路径保存至 mainVec } } Airline* AirlineGraph::GetMinCostAirline(int f,int t) { //cout<<"f\t"<<f<<"\tt\t"<<t<<"\t"; Airline* airline=mAirportHeadArray[f]->mAdjAirline; Airline* ret=NULL; int cost=INT_MAX; while(airline!=NULL) { if(airline->mAirportNo==t&&airline->GetPriceAfterDiscount()<cost) { cost=airline->GetPriceAfterDiscount(); ret=airline; } airline=airline->mNextAirline; } return ret; } Route** AirlineGraph::Dijkstra(int v) { int TotalCost[mAirportNumber]; int path[mAirportNumber]; bool visit[mAirportNumber]; for(int i=0; i<mAirportNumber; i++) { TotalCost[i]=INT_MAX; path[i]=-1; visit[i]=0; } TotalCost[v]=0; visit[v]=1; Airline* airline=mAirportHeadArray[v]->mAdjAirline; int u=v; for(int i=0; i<mAirportNumber-1; i++) { while(airline!=NULL) //更新长度、路径信息 { int k=airline->mAirportNo; if(visit[k]!=1&&TotalCost[k]+airline->GetPriceAfterDiscount()<TotalCost[k]) { TotalCost[k]=TotalCost[k]+airline->GetPriceAfterDiscount(); path[k]=u; } airline=airline->mNextAirline; } int tmpMin=INT_MAX; for(int j=0; j<mAirportNumber; j++) //决定下一被访问结点 { if(TotalCost[j]<tmpMin&&visit[j]==0) { tmpMin=TotalCost[j]; u=j; } } visit[u]=1; airline=mAirportHeadArray[u]->mAdjAirline; } Route** routeArray=new Route*[mAirportNumber]; /*for(int i=0;i<mAirportNumber;i++) cout<<"i\t"<<i<<"\t"<<path[i]<<endl;*/ for(int i=0;i<mAirportNumber;i++) { if(path[i]!=-1) //是v本身或没有可及路径 { stack<int> s; int j=i; while(j!=v) //回溯路径,压栈 { s.push(j); j=path[j]; } int prev=v; Route* r=new Route(); while(!s.empty()) //弹栈,生成路径 { int f=s.top(); Airline* airline=GetMinCostAirline(prev,f); r->mAirlineVec.push_back(airline); s.pop(); prev=f; } routeArray[i]=r; }else { routeArray[i]=NULL; } } return routeArray; }
[ "1005031096@qq.com" ]
1005031096@qq.com
109a7ad9529b68a7a50654fe95d36031b2438d9c
74b3058ff7aead32d7691d3fda836acae9cddc95
/algorithm/0053/res.cpp
d25d7cdae11a81c2ce1d99e2d5678726bfc8f295
[]
no_license
onehumanbeing/leetcode
647f6d09a4b6c8075e2e254de2e99a5664864bba
7fc0a7a87b082d5e8c63a35ee5f282b2d3f43bcb
refs/heads/master
2020-03-22T10:03:04.967533
2018-09-09T09:01:53
2018-09-09T09:01:53
139,877,549
2
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxSubArray(vector<int>& nums) { // sum[i]表示从i开始的最大子串和, // 则有递推公式:sum[i] = max{nums[i], nums[i] + sum[i+1]} int n = nums.size(); int sum = nums[n - 1]; int res = sum; for (int i = n - 2; i >= 0; i--) { sum = max(nums[i], sum + nums[i]); res = max(res, sum); } return res; } }; int main(){ int temp[9] = {-2,1,-3,4,-1,2,1,-5,4}; vector<int> n(0); for(int i=0;i<9;i++){ n.push_back(temp[i]); } Solution s = Solution(); cout << s.maxSubArray(n) << endl; return 0; }
[ "henryhenryhenry111@126.com" ]
henryhenryhenry111@126.com
b8e9d031fd1fb86866a3329717aacd1369957d2b
ad06994cda92d0c5463e5854317c30274ad22fc8
/src/burn/misc/post90s/d_aerofgt.cpp
05c95773e1c34046e8cf05ea11bbaebbc3a7fd6a
[]
no_license
retrofw/fba-a320
72c97e8647c098655f7a747ec5454eef33ba3f85
ddb1a973aa787f0d1697737bfb243f6cbe8b7161
refs/heads/master
2022-08-31T15:40:25.739153
2020-01-26T04:15:38
2020-05-16T05:04:33
163,225,249
4
6
null
null
null
null
UTF-8
C++
false
false
144,848
cpp
/* * Aero Fighters driver for FB Alpha 0.2.96.71 * Port by OopsWare. 2007 * http://oopsware.googlepages.com * http://oopsware.ys168.com * * 6.13.2007 * Add driver Spinal Breakers (spinlbrk) * * 6.12.2007 * Add driver Karate Blazers (karatblz) * * 6.11.2007 * Add driver Turbo Force (turbofrc) * * 6.10.2007 * Add BurnHighCol support, and add BDF_16BIT_ONLY into driver. thanks to KEV * */ #include "burnint.h" #include "burn_ym2610.h" #define USE_BURN_HIGHCOL 1 static unsigned char DrvButton[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvJoy1[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvJoy2[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvJoy3[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvJoy4[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvInput[10] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvReset = 0; static unsigned char *Mem = NULL, *MemEnd = NULL; static unsigned char *RamStart, *RamEnd; static unsigned char *Rom01; static unsigned char *RomZ80; static unsigned char *RomBg; static unsigned char *RomSpr1; static unsigned char *RomSpr2; static unsigned char *RomSnd1; static unsigned char *RomSnd2; static unsigned char *RamPal; static unsigned short *RamRaster; static unsigned short *RamBg1V, *RamBg2V; static unsigned short *RamSpr1; static unsigned short *RamSpr2; static unsigned short *RamSpr3; static unsigned char *Ram01; static unsigned char *RamZ80; //static int nCyclesDone[2]; static int nCyclesTotal[2]; //static int nCyclesSegment; static unsigned char RamGfxBank[8]; static unsigned short *RamCurPal; static unsigned char *DeRomBg; static unsigned char *DeRomSpr1; static unsigned char *DeRomSpr2; static unsigned int RamSpr1SizeMask; static unsigned int RamSpr2SizeMask; static unsigned int RomSpr1SizeMask; static unsigned int RomSpr2SizeMask; static int pending_command = 0; static int RomSndSize1, RomSndSize2; static unsigned short bg1scrollx, bg2scrollx; static unsigned short bg1scrolly, bg2scrolly; static int nAerofgtZ80Bank; static unsigned char nSoundlatch; #if USE_BURN_HIGHCOL inline static unsigned int CalcCol(unsigned short nColour) { int r, g, b; r = (nColour & 0x001F) << 3; // Red r |= r >> 5; g = (nColour & 0x03E0) >> 2; // Green g |= g >> 5; b = (nColour & 0x7C00) >> 7; // Blue b |= b >> 5; return BurnHighCol(b, g, r, 0); } #else inline static unsigned int CalcCol(unsigned short nColour) { return (nColour & 0x001F) | ((nColour & 0x7FE0) << 1); } #endif static struct BurnInputInfo aerofgtInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvButton + 0, "p1 coin"}, {"P1 Start", BIT_DIGITAL, DrvButton + 2, "p1 start"}, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up"}, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down"}, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left"}, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right"}, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1"}, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2"}, {"P2 Coin", BIT_DIGITAL, DrvButton + 1, "p2 coin"}, {"P2 Start", BIT_DIGITAL, DrvButton + 3, "p2 start"}, {"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up"}, {"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down"}, {"P2 Left", BIT_DIGITAL, DrvJoy2 + 2, "p2 left"}, {"P2 Right", BIT_DIGITAL, DrvJoy2 + 3, "p2 right"}, {"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1"}, {"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2"}, {"P3 Coin", BIT_DIGITAL, DrvButton + 6, "p3 coin"}, {"Reset", BIT_DIGITAL, &DrvReset, "reset"}, {"Dip A", BIT_DIPSWITCH, DrvInput + 3, "dip"}, {"Dip B", BIT_DIPSWITCH, DrvInput + 4, "dip"}, {"Dip C", BIT_DIPSWITCH, DrvInput + 5, "dip"}, }; STDINPUTINFO(aerofgt); static struct BurnDIPInfo aerofgtDIPList[] = { // Defaults {0x12, 0xFF, 0xFF, 0x00, NULL}, {0x13, 0xFF, 0xFF, 0x00, NULL}, // DIP 1 {0, 0xFE, 0, 2, "Coin Slot"}, {0x12, 0x01, 0x01, 0x00, "Same"}, {0x12, 0x01, 0x01, 0x01, "Individual"}, {0, 0xFE, 0, 8, "Coin 1"}, {0x12, 0x01, 0x0E, 0x00, "1 coin 1 credits"}, {0x12, 0x01, 0x0E, 0x02, "2 coin 1 credits"}, {0x12, 0x01, 0x0E, 0x04, "3 coin 1 credit"}, {0x12, 0x01, 0x0E, 0x06, "1 coin 2 credits"}, {0x12, 0x01, 0x0E, 0x08, "1 coins 3 credit"}, {0x12, 0x01, 0x0E, 0x0A, "1 coins 4 credit"}, {0x12, 0x01, 0x0E, 0x0C, "1 coins 5 credit"}, {0x12, 0x01, 0x0E, 0x0E, "1 coins 6 credit"}, {0, 0xFE, 0, 8, "Coin 2"}, {0x12, 0x01, 0x70, 0x00, "1 coin 1 credits"}, {0x12, 0x01, 0x70, 0x10, "2 coin 1 credits"}, {0x12, 0x01, 0x70, 0x20, "3 coin 1 credit"}, {0x12, 0x01, 0x70, 0x30, "1 coin 2 credits"}, {0x12, 0x01, 0x70, 0x40, "1 coins 3 credit"}, {0x12, 0x01, 0x70, 0x50, "1 coins 4 credit"}, {0x12, 0x01, 0x70, 0x60, "1 coins 5 credit"}, {0x12, 0x01, 0x70, 0x70, "1 coins 6 credit"}, {0, 0xFE, 0, 2, "2 Coins to Start, 1 to Continue"}, {0x12, 0x01, 0x80, 0x00, "Off"}, {0x12, 0x01, 0x80, 0x80, "On"}, // DIP 2 {0, 0xFE, 0, 2, "Screen flip"}, {0x13, 0x01, 0x01, 0x00, "Off"}, {0x13, 0x01, 0x01, 0x01, "On"}, {0, 0xFE, 0, 2, "Demo sound"}, {0x13, 0x01, 0x02, 0x00, "Off"}, {0x13, 0x01, 0x02, 0x02, "On"}, {0, 0xFE, 0, 4, "Difficulty"}, {0x13, 0x01, 0x0C, 0x00, "Normal"}, {0x13, 0x01, 0x0C, 0x04, "Easy"}, {0x13, 0x01, 0x0C, 0x08, "Hard"}, {0x13, 0x01, 0x0C, 0x0C, "Hardest"}, {0, 0xFE, 0, 4, "Lives"}, {0x13, 0x01, 0x30, 0x00, "3"}, {0x13, 0x01, 0x30, 0x10, "1"}, {0x13, 0x01, 0x30, 0x20, "2"}, {0x13, 0x01, 0x30, 0x30, "4"}, {0, 0xFE, 0, 2, "Bonus Life"}, {0x13, 0x01, 0x40, 0x00, "200000"}, {0x13, 0x01, 0x40, 0x40, "300000"}, {0, 0xFE, 0, 2, "Service"}, {0x13, 0x01, 0x80, 0x00, "Off"}, {0x13, 0x01, 0x80, 0x80, "On"}, }; static struct BurnDIPInfo aerofgt_DIPList[] = { {0x14, 0xFF, 0xFF, 0x0F, NULL}, // DIP 3 {0, 0xFE, 0, 5, "Region"}, {0x14, 0x01, 0x0F, 0x00, "USA"}, {0x14, 0x01, 0x0F, 0x01, "Korea"}, {0x14, 0x01, 0x0F, 0x02, "Hong Kong"}, {0x14, 0x01, 0x0F, 0x04, "Taiwan"}, {0x14, 0x01, 0x0F, 0x0F, "Any"}, }; STDDIPINFOEXT(aerofgt, aerofgt, aerofgt_); // Rom information static struct BurnRomInfo aerofgtRomDesc[] = { { "1.u4", 0x080000, 0x6fdff0a2, BRF_ESS | BRF_PRG }, // 68000 code swapped { "538a54.124", 0x080000, 0x4d2c4df2, BRF_GRA }, // graphics { "1538a54.124", 0x080000, 0x286d109e, BRF_GRA }, { "538a53.u9", 0x100000, 0x630d8e0b, BRF_GRA }, // { "534g8f.u18", 0x080000, 0x76ce0926, BRF_GRA }, { "2.153", 0x020000, 0xa1ef64ec, BRF_ESS | BRF_PRG }, // Sound CPU { "it-19-01", 0x040000, 0x6d42723d, BRF_SND }, // samples { "it-19-06", 0x100000, 0xcdbbdb1d, BRF_SND }, }; STD_ROM_PICK(aerofgt); STD_ROM_FN(aerofgt); static int MemIndex() { unsigned char *Next; Next = Mem; Rom01 = Next; Next += 0x080000; // 68000 ROM RomZ80 = Next; Next += 0x030000; // Z80 ROM RomBg = Next; Next += 0x200040; // Background, 1M 8x8x4bit decode to 2M + 64Byte safe DeRomBg = RomBg + 0x000040; RomSpr1 = Next; Next += 0x200000; // Sprite 1 , 1M 16x16x4bit decode to 2M + 256Byte safe RomSpr2 = Next; Next += 0x100100; // Sprite 2 DeRomSpr1 = RomSpr1 + 0x000100; DeRomSpr2 = RomSpr2 += 0x000100; RomSnd1 = Next; Next += 0x040000; // ADPCM data RomSndSize1 = 0x040000; RomSnd2 = Next; Next += 0x100000; // ADPCM data RomSndSize2 = 0x100000; RamStart = Next; RamPal = Next; Next += 0x000800; // 1024 of X1R5G5B5 Palette RamRaster = (unsigned short *)Next; Next += 0x001000; // 0x1b0000~0x1b07ff, Raster // 0x1b0800~0x1b0801, NOP // 0x1b0ff0~0x1b0fff, stack area during boot RamBg1V = (unsigned short *)Next; Next += 0x002000; // BG1 Video Ram RamBg2V = (unsigned short *)Next; Next += 0x002000; // BG2 Video Ram RamSpr1 = (unsigned short *)Next; Next += 0x008000; // Sprite 1 Ram RamSpr2 = (unsigned short *)Next; Next += 0x002000; // Sprite 2 Ram Ram01 = Next; Next += 0x010000; // Work Ram RamZ80 = Next; Next += 0x000800; // Z80 Ram 2K RamEnd = Next; RamCurPal = (unsigned short *)Next; Next += 0x000800; // 1024 colors MemEnd = Next; return 0; } static void DecodeBg() { for (int c=0x8000-1; c>=0; c--) { for (int y=7; y>=0; y--) { DeRomBg[(c * 64) + (y * 8) + 7] = RomBg[0x00002 + (y * 4) + (c * 32)] & 0x0f; DeRomBg[(c * 64) + (y * 8) + 6] = RomBg[0x00002 + (y * 4) + (c * 32)] >> 4; DeRomBg[(c * 64) + (y * 8) + 5] = RomBg[0x00003 + (y * 4) + (c * 32)] & 0x0f; DeRomBg[(c * 64) + (y * 8) + 4] = RomBg[0x00003 + (y * 4) + (c * 32)] >> 4; DeRomBg[(c * 64) + (y * 8) + 3] = RomBg[0x00000 + (y * 4) + (c * 32)] & 0x0f; DeRomBg[(c * 64) + (y * 8) + 2] = RomBg[0x00000 + (y * 4) + (c * 32)] >> 4; DeRomBg[(c * 64) + (y * 8) + 1] = RomBg[0x00001 + (y * 4) + (c * 32)] & 0x0f; DeRomBg[(c * 64) + (y * 8) + 0] = RomBg[0x00001 + (y * 4) + (c * 32)] >> 4; } } } static void DecodeSpr(unsigned char *d, unsigned char *s, int cnt) { for (int c=cnt-1; c>=0; c--) for (int y=15; y>=0; y--) { d[(c * 256) + (y * 16) + 15] = s[0x00006 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 14] = s[0x00006 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 13] = s[0x00007 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 12] = s[0x00007 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 11] = s[0x00004 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 10] = s[0x00004 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 9] = s[0x00005 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 8] = s[0x00005 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 7] = s[0x00002 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 6] = s[0x00002 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 5] = s[0x00003 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 4] = s[0x00003 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 3] = s[0x00000 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 2] = s[0x00000 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 1] = s[0x00001 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 0] = s[0x00001 + (y * 8) + (c * 128)] >> 4; } } static int LoadRoms() { // Load 68000 ROM if (BurnLoadRom(Rom01, 0, 1)) { return 1; } // Load Graphic BurnLoadRom(RomBg, 1, 1); BurnLoadRom(RomBg+0x80000, 2, 1); DecodeBg(); BurnLoadRom(RomSpr1+0x000000, 3, 1); BurnLoadRom(RomSpr1+0x100000, 4, 1); DecodeSpr(DeRomSpr1, RomSpr1, 8192+4096); // Load Z80 ROM if (BurnLoadRom(RomZ80+0x10000, 5, 1)) return 1; memcpy(RomZ80, RomZ80+0x10000, 0x10000); BurnLoadRom(RomSnd1, 6, 1); BurnLoadRom(RomSnd2, 7, 1); return 0; } unsigned char __fastcall aerofgtReadByte(unsigned int sekAddress) { switch (sekAddress) { case 0xFFFFA1: return ~DrvInput[0]; case 0xFFFFA3: return ~DrvInput[1]; case 0xFFFFA5: return ~DrvInput[2]; case 0xFFFFA7: return ~DrvInput[3]; case 0xFFFFA9: return ~DrvInput[4]; case 0xFFFFAD: //printf("read pending_command %d addr %08x\n", pending_command, sekAddress); return pending_command; case 0xFFFFAF: return ~DrvInput[5]; // default: // printf("Attempt to read byte value of location %x\n", sekAddress); } return 0; } /* unsigned short __fastcall aerofgtReadWord(unsigned int sekAddress) { switch (sekAddress) { default: printf("Attempt to read word value of location %x\n", sekAddress); } return 0; } */ static void SoundCommand(unsigned char nCommand) { // bprintf(PRINT_NORMAL, _T(" - Sound command sent (0x%02X).\n"), nCommand); int nCycles = ((long long)SekTotalCycles() * nCyclesTotal[1] / nCyclesTotal[0]); if (nCycles <= ZetTotalCycles()) return; BurnTimerUpdate(nCycles); nSoundlatch = nCommand; ZetNmi(); } void __fastcall aerofgtWriteByte(unsigned int sekAddress, unsigned char byteValue) { if (( sekAddress & 0xFF0000 ) == 0x1A0000) { sekAddress &= 0xFFFF; if (sekAddress < 0x800) { RamPal[sekAddress^1] = byteValue; // palette byte write at boot self-test only ?! // if (sekAddress & 1) // RamCurPal[sekAddress>>1] = CalcCol( *((unsigned short *)&RamPal[sekAddress]) ); } return; } switch (sekAddress) { case 0xFFFFC1: pending_command = 1; SoundCommand(byteValue); break; /* case 0xFFFFB9: case 0xFFFFBB: case 0xFFFFBD: case 0xFFFFBF: break; case 0xFFFFAD: // NOP break; default: printf("Attempt to write byte value %x to location %x\n", byteValue, sekAddress); */ } } void __fastcall aerofgtWriteWord(unsigned int sekAddress, unsigned short wordValue) { if (( sekAddress & 0xFF0000 ) == 0x1A0000) { sekAddress &= 0xFFFF; if (sekAddress < 0x800) *((unsigned short *)&RamPal[sekAddress]) = wordValue; RamCurPal[sekAddress>>1] = CalcCol( wordValue ); return; } switch (sekAddress) { case 0xFFFF80: RamGfxBank[0] = wordValue >> 0x08; RamGfxBank[1] = wordValue & 0xFF; break; case 0xFFFF82: RamGfxBank[2] = wordValue >> 0x08; RamGfxBank[3] = wordValue & 0xFF; break; case 0xFFFF84: RamGfxBank[4] = wordValue >> 0x08; RamGfxBank[5] = wordValue & 0xFF; break; case 0xFFFF86: RamGfxBank[6] = wordValue >> 0x08; RamGfxBank[7] = wordValue & 0xFF; break; case 0xFFFF88: bg1scrolly = wordValue; break; case 0xFFFF90: bg2scrolly = wordValue; break; /* case 0xFFFF40: case 0xFFFF42: case 0xFFFF44: case 0xFFFF48: case 0xFFFF4A: case 0xFFFF4C: case 0xFFFF50: case 0xFFFF52: case 0xFFFF60: break; default: printf("Attempt to write word value %x to location %x\n", wordValue, sekAddress); */ } } static void aerofgtFMIRQHandler(int, int nStatus) { // bprintf(PRINT_NORMAL, _T(" - IRQ -> %i.\n"), nStatus); if (nStatus) { ZetSetIRQLine(0xFF, ZET_IRQSTATUS_ACK); } else { ZetSetIRQLine(0, ZET_IRQSTATUS_NONE); } } static int aerofgtSynchroniseStream(int nSoundRate) { return (long long)ZetTotalCycles() * nSoundRate / 4000000; } static double aerofgtGetTime() { return (double)ZetTotalCycles() / 4000000.0; } /* static unsigned char __fastcall aerofgtZ80Read(unsigned short a) { switch (a) { default: printf("Z80 Attempt to read word value of location %04x\n", a); } return 0; } static void __fastcall aerofgtZ80Write(unsigned short a,unsigned char v) { switch (a) { default: printf("Attempt to write word value %x to location %x\n", v, a); } } */ static void aerofgtSndBankSwitch(unsigned char v) { /* UINT8 *rom = memory_region(REGION_CPU2) + 0x10000; memory_set_bankptr(1,rom + (data & 0x03) * 0x8000); */ v &= 0x03; if (v != nAerofgtZ80Bank) { unsigned char* nStartAddress = RomZ80 + 0x10000 + (v << 15); ZetMapArea(0x8000, 0xFFFF, 0, nStartAddress); ZetMapArea(0x8000, 0xFFFF, 2, nStartAddress); nAerofgtZ80Bank = v; } } unsigned char __fastcall aerofgtZ80PortRead(unsigned short p) { switch (p & 0xFF) { case 0x00: return BurnYM2610Read(0); case 0x02: return BurnYM2610Read(2); case 0x0C: return nSoundlatch; // default: // printf("Z80 Attempt to read port %04x\n", p); } return 0; } void __fastcall aerofgtZ80PortWrite(unsigned short p, unsigned char v) { switch (p & 0x0FF) { case 0x00: case 0x01: case 0x02: case 0x03: BurnYM2610Write(p & 3, v); break; case 0x04: aerofgtSndBankSwitch(v); break; case 0x08: pending_command = 0; break; // default: // printf("Z80 Attempt to write %02x to port %04x\n", v, p); } } static int DrvDoReset() { nAerofgtZ80Bank = -1; aerofgtSndBankSwitch(0); SekOpen(0); //nIRQPending = 0; SekSetIRQLine(0, SEK_IRQSTATUS_NONE); SekReset(); SekClose(); ZetReset(); BurnYM2610Reset(); memset(RamGfxBank, 0 , sizeof(RamGfxBank)); return 0; } static int aerofgtInit() { Mem = NULL; MemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) { return 1; } memset(Mem, 0, nLen); // blank all memory MemIndex(); // Load the roms into memory if (LoadRoms()) { return 1; } { SekInit(0, 0x68000); // Allocate 68000 SekOpen(0); // Map 68000 memory: SekMapMemory(Rom01, 0x000000, 0x07FFFF, SM_ROM); // CPU 0 ROM SekMapMemory(RamPal, 0x1A0000, 0x1A07FF, SM_ROM); // Palette SekMapMemory((unsigned char *)RamRaster, 0x1B0000, 0x1B0FFF, SM_RAM); // Raster / MRA_NOP / MRA_BANK7 SekMapMemory((unsigned char *)RamBg1V, 0x1B2000, 0x1B3FFF, SM_RAM); SekMapMemory((unsigned char *)RamBg2V, 0x1B4000, 0x1B5FFF, SM_RAM); SekMapMemory((unsigned char *)RamSpr1, 0x1C0000, 0x1C7FFF, SM_RAM); SekMapMemory((unsigned char *)RamSpr2, 0x1D0000, 0x1D1FFF, SM_RAM); SekMapMemory(Ram01, 0xFEF000, 0xFFEFFF, SM_RAM); // 64K Work RAM // SekSetReadWordHandler(0, aerofgtReadWord); SekSetReadByteHandler(0, aerofgtReadByte); SekSetWriteWordHandler(0, aerofgtWriteWord); SekSetWriteByteHandler(0, aerofgtWriteByte); SekClose(); } { ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x77FF, 0, RomZ80); ZetMapArea(0x0000, 0x77FF, 2, RomZ80); ZetMapArea(0x7800, 0x7FFF, 0, RamZ80); ZetMapArea(0x7800, 0x7FFF, 1, RamZ80); ZetMapArea(0x7800, 0x7FFF, 2, RamZ80); ZetMemEnd(); //ZetSetReadHandler(aerofgtZ80Read); //ZetSetWriteHandler(aerofgtZ80Write); ZetSetInHandler(aerofgtZ80PortRead); ZetSetOutHandler(aerofgtZ80PortWrite); ZetClose(); } BurnYM2610Init(8000000, RomSnd2, &RomSndSize2, RomSnd1, &RomSndSize1, &aerofgtFMIRQHandler, aerofgtSynchroniseStream, aerofgtGetTime, 0); BurnTimerAttachZet(4000000); DrvDoReset(); // Reset machine return 0; } static int DrvExit() { BurnYM2610Exit(); ZetExit(); SekExit(); free(Mem); Mem = NULL; return 0; } static void drawgfxzoom(int bank,unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,int scalex,int scaley) { if (!scalex || !scaley) return; unsigned short * p = (unsigned short *) pBurnDraw; unsigned char * q; unsigned short * pal; if (bank) { q = DeRomSpr2 + (code) * 256; pal = RamCurPal + 768; } else { q = DeRomSpr1 + (code) * 256; pal = RamCurPal + 512; } p += sy * 320 + sx; if (sx < 0 || sx >= 304 || sy < 0 || sy >= 208 ) { if ((sx <= -16) || (sx >= 320) || (sy <= -16) || (sy >= 224)) return; if (flipy) { p += 320 * 15; if (flipx) { for (int i=15;i>=0;i--) { if (((sy+i)>=0) && ((sy+i)<224)) { if (q[ 0] != 15 && ((sx + 15) >= 0) && ((sx + 15)<320)) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 14) >= 0) && ((sx + 14)<320)) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 13) >= 0) && ((sx + 13)<320)) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 12) >= 0) && ((sx + 12)<320)) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 11) >= 0) && ((sx + 11)<320)) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 10) >= 0) && ((sx + 10)<320)) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 9) >= 0) && ((sx + 9)<320)) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 8) >= 0) && ((sx + 8)<320)) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 7) >= 0) && ((sx + 7)<320)) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 6) >= 0) && ((sx + 6)<320)) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 5) >= 0) && ((sx + 5)<320)) p[ 5] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 4) >= 0) && ((sx + 4)<320)) p[ 4] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 3) >= 0) && ((sx + 3)<320)) p[ 3] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 2) >= 0) && ((sx + 2)<320)) p[ 2] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 1) >= 0) && ((sx + 1)<320)) p[ 1] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 0) >= 0) && ((sx + 0)<320)) p[ 0] = pal[ q[15] | color]; } p -= 320; q += 16; } } else { for (int i=15;i>=0;i--) { if (((sy+i)>=0) && ((sy+i)<224)) { if (q[ 0] != 15 && ((sx + 0) >= 0) && ((sx + 0)<320)) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 1) >= 0) && ((sx + 1)<320)) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 2) >= 0) && ((sx + 2)<320)) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 3) >= 0) && ((sx + 3)<320)) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 4) >= 0) && ((sx + 4)<320)) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 5) >= 0) && ((sx + 5)<320)) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 6) >= 0) && ((sx + 6)<320)) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 7) >= 0) && ((sx + 7)<320)) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 8) >= 0) && ((sx + 8)<320)) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 9) >= 0) && ((sx + 9)<320)) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 10) >= 0) && ((sx + 10)<320)) p[10] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 11) >= 0) && ((sx + 11)<320)) p[11] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 12) >= 0) && ((sx + 12)<320)) p[12] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 13) >= 0) && ((sx + 13)<320)) p[13] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 14) >= 0) && ((sx + 14)<320)) p[14] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 15) >= 0) && ((sx + 15)<320)) p[15] = pal[ q[15] | color]; } p -= 320; q += 16; } } } else { if (flipx) { for (int i=0;i<16;i++) { if (((sy+i)>=0) && ((sy+i)<224)) { if (q[ 0] != 15 && ((sx + 15) >= 0) && ((sx + 15)<320)) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 14) >= 0) && ((sx + 14)<320)) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 13) >= 0) && ((sx + 13)<320)) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 12) >= 0) && ((sx + 12)<320)) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 11) >= 0) && ((sx + 11)<320)) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 10) >= 0) && ((sx + 10)<320)) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 9) >= 0) && ((sx + 9)<320)) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 8) >= 0) && ((sx + 8)<320)) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 7) >= 0) && ((sx + 7)<320)) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 6) >= 0) && ((sx + 6)<320)) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 5) >= 0) && ((sx + 5)<320)) p[ 5] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 4) >= 0) && ((sx + 4)<320)) p[ 4] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 3) >= 0) && ((sx + 3)<320)) p[ 3] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 2) >= 0) && ((sx + 2)<320)) p[ 2] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 1) >= 0) && ((sx + 1)<320)) p[ 1] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 0) >= 0) && ((sx + 0)<320)) p[ 0] = pal[ q[15] | color]; } p += 320; q += 16; } } else { for (int i=0;i<16;i++) { if (((sy+i)>=0) && ((sy+i)<224)) { if (q[ 0] != 15 && ((sx + 0) >= 0) && ((sx + 0)<320)) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 1) >= 0) && ((sx + 1)<320)) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 2) >= 0) && ((sx + 2)<320)) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 3) >= 0) && ((sx + 3)<320)) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 4) >= 0) && ((sx + 4)<320)) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 5) >= 0) && ((sx + 5)<320)) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 6) >= 0) && ((sx + 6)<320)) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 7) >= 0) && ((sx + 7)<320)) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 8) >= 0) && ((sx + 8)<320)) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 9) >= 0) && ((sx + 9)<320)) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 10) >= 0) && ((sx + 10)<320)) p[10] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 11) >= 0) && ((sx + 11)<320)) p[11] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 12) >= 0) && ((sx + 12)<320)) p[12] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 13) >= 0) && ((sx + 13)<320)) p[13] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 14) >= 0) && ((sx + 14)<320)) p[14] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 15) >= 0) && ((sx + 15)<320)) p[15] = pal[ q[15] | color]; } p += 320; q += 16; } } } return; } if (flipy) { p += 320 * 15; if (flipx) { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15) p[ 5] = pal[ q[10] | color]; if (q[11] != 15) p[ 4] = pal[ q[11] | color]; if (q[12] != 15) p[ 3] = pal[ q[12] | color]; if (q[13] != 15) p[ 2] = pal[ q[13] | color]; if (q[14] != 15) p[ 1] = pal[ q[14] | color]; if (q[15] != 15) p[ 0] = pal[ q[15] | color]; p -= 320; q += 16; } } else { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15) p[10] = pal[ q[10] | color]; if (q[11] != 15) p[11] = pal[ q[11] | color]; if (q[12] != 15) p[12] = pal[ q[12] | color]; if (q[13] != 15) p[13] = pal[ q[13] | color]; if (q[14] != 15) p[14] = pal[ q[14] | color]; if (q[15] != 15) p[15] = pal[ q[15] | color]; p -= 320; q += 16; } } } else { if (flipx) { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15) p[ 5] = pal[ q[10] | color]; if (q[11] != 15) p[ 4] = pal[ q[11] | color]; if (q[12] != 15) p[ 3] = pal[ q[12] | color]; if (q[13] != 15) p[ 2] = pal[ q[13] | color]; if (q[14] != 15) p[ 1] = pal[ q[14] | color]; if (q[15] != 15) p[ 0] = pal[ q[15] | color]; p += 320; q += 16; } } else { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15) p[10] = pal[ q[10] | color]; if (q[11] != 15) p[11] = pal[ q[11] | color]; if (q[12] != 15) p[12] = pal[ q[12] | color]; if (q[13] != 15) p[13] = pal[ q[13] | color]; if (q[14] != 15) p[14] = pal[ q[14] | color]; if (q[15] != 15) p[15] = pal[ q[15] | color]; p += 320; q += 16; } } } } static void aerofgt_drawsprites(int priority) { priority <<= 12; int offs = 0; while (offs < 0x0400 && (RamSpr2[offs] & 0x8000) == 0) { int attr_start = (RamSpr2[offs] & 0x03ff) * 4; /* is the way I handle priority correct? Or should I just check bit 13? */ if ((RamSpr2[attr_start + 2] & 0x3000) == priority) { int map_start; int ox,oy,x,y,xsize,ysize,zoomx,zoomy,flipx,flipy,color; ox = RamSpr2[attr_start + 1] & 0x01ff; xsize = (RamSpr2[attr_start + 1] & 0x0e00) >> 9; zoomx = (RamSpr2[attr_start + 1] & 0xf000) >> 12; oy = RamSpr2[attr_start + 0] & 0x01ff; ysize = (RamSpr2[attr_start + 0] & 0x0e00) >> 9; zoomy = (RamSpr2[attr_start + 0] & 0xf000) >> 12; flipx = RamSpr2[attr_start + 2] & 0x4000; flipy = RamSpr2[attr_start + 2] & 0x8000; color = (RamSpr2[attr_start + 2] & 0x0f00) >> 4; map_start = RamSpr2[attr_start + 3] & 0x3fff; ox += (xsize*zoomx+2)/4; oy += (ysize*zoomy+2)/4; zoomx = 32 - zoomx; zoomy = 32 - zoomy; for (y = 0;y <= ysize;y++) { int sx,sy; if (flipy) sy = ((oy + zoomy * (ysize - y)/2 + 16) & 0x1ff) - 16; else sy = ((oy + zoomy * y / 2 + 16) & 0x1ff) - 16; for (x = 0;x <= xsize;x++) { if (flipx) sx = ((ox + zoomx * (xsize - x) / 2 + 16) & 0x1ff) - 16; else sx = ((ox + zoomx * x / 2 + 16) & 0x1ff) - 16; //if (map_start < 0x2000) int code = RamSpr1[map_start] & 0x1fff; drawgfxzoom(map_start&0x2000,code,color,flipx,flipy,sx,sy,zoomx<<11, zoomy<<11); map_start++; } } } offs++; } } /* * aerofgt Background Tile * 16-bit tile code in RamBg1V and RamBg2V * 0xE000 shr 13 is Color * 0x1800 shr 11 is Gfx Bank * 0x07FF shr 0 or Tile element index (low part) * */ static void TileBackground_1(unsigned short *bg, unsigned short *pal) { int offs, mx, my, x, y; mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - RamRaster[0x0000] + 18; if (x <= -192) x += 512; y = my * 8 - (bg1scrolly & 0x1FF); if (y <= (224-512)) y += 512; if ( x<=-8 || x>=320 || y<=-8 || y>= 224 ) continue; else if ( x >=0 && x < 312 && y >= 0 && y < 216) { unsigned char *d = DeRomBg + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11)] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; for (int k=0;k<8;k++) { p[0] = pal[ d[0] | c ]; p[1] = pal[ d[1] | c ]; p[2] = pal[ d[2] | c ]; p[3] = pal[ d[3] | c ]; p[4] = pal[ d[4] | c ]; p[5] = pal[ d[5] | c ]; p[6] = pal[ d[6] | c ]; p[7] = pal[ d[7] | c ]; d += 8; p += 320; } } else { unsigned char *d = DeRomBg + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11)] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<224 ) { if ((x + 0) >= 0 && (x + 0)<320) p[0] = pal[ d[0] | c ]; if ((x + 1) >= 0 && (x + 1)<320) p[1] = pal[ d[1] | c ]; if ((x + 2) >= 0 && (x + 2)<320) p[2] = pal[ d[2] | c ]; if ((x + 3) >= 0 && (x + 3)<320) p[3] = pal[ d[3] | c ]; if ((x + 4) >= 0 && (x + 4)<320) p[4] = pal[ d[4] | c ]; if ((x + 5) >= 0 && (x + 5)<320) p[5] = pal[ d[5] | c ]; if ((x + 6) >= 0 && (x + 6)<320) p[6] = pal[ d[6] | c ]; if ((x + 7) >= 0 && (x + 7)<320) p[7] = pal[ d[7] | c ]; } d += 8; p += 320; } } } } static void TileBackground_2(unsigned short *bg, unsigned short *pal) { int offs, mx, my, x, y; mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - RamRaster[0x0200] + 20; if (x <= -192) x += 512; y = my * 8 - (bg2scrolly & 0x1FF); if (y <= (224-512)) y += 512; if ( x<=-8 || x>=320 || y<=-8 || y>= 224 ) continue; else if ( x >=0 && x < 312 && y >= 0 && y < 216) { unsigned char *d = DeRomBg + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11) + 4] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; for (int k=0;k<8;k++) { if (d[0] != 15) p[0] = pal[ d[0] | c ]; if (d[1] != 15) p[1] = pal[ d[1] | c ]; if (d[2] != 15) p[2] = pal[ d[2] | c ]; if (d[3] != 15) p[3] = pal[ d[3] | c ]; if (d[4] != 15) p[4] = pal[ d[4] | c ]; if (d[5] != 15) p[5] = pal[ d[5] | c ]; if (d[6] != 15) p[6] = pal[ d[6] | c ]; if (d[7] != 15) p[7] = pal[ d[7] | c ]; d += 8; p += 320; } } else { unsigned char *d = DeRomBg + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11) + 4] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<224 ) { if (d[0] != 15 && (x + 0) >= 0 && (x + 0)<320) p[0] = pal[ d[0] | c ]; if (d[1] != 15 && (x + 1) >= 0 && (x + 1)<320) p[1] = pal[ d[1] | c ]; if (d[2] != 15 && (x + 2) >= 0 && (x + 2)<320) p[2] = pal[ d[2] | c ]; if (d[3] != 15 && (x + 3) >= 0 && (x + 3)<320) p[3] = pal[ d[3] | c ]; if (d[4] != 15 && (x + 4) >= 0 && (x + 4)<320) p[4] = pal[ d[4] | c ]; if (d[5] != 15 && (x + 5) >= 0 && (x + 5)<320) p[5] = pal[ d[5] | c ]; if (d[6] != 15 && (x + 6) >= 0 && (x + 6)<320) p[6] = pal[ d[6] | c ]; if (d[7] != 15 && (x + 7) >= 0 && (x + 7)<320) p[7] = pal[ d[7] | c ]; } d += 8; p += 320; } } } } static int DrvDraw() { // background 1 TileBackground_1(RamBg1V, RamCurPal); aerofgt_drawsprites(0); aerofgt_drawsprites(1); // background 2 TileBackground_2(RamBg2V, RamCurPal + 256); aerofgt_drawsprites(2); aerofgt_drawsprites(3); return 0; } static int DrvFrame() { if (DrvReset) { // Reset machine DrvDoReset(); } // Compile digital inputs DrvInput[0] = 0x00; // Joy1 DrvInput[1] = 0x00; // Joy2 DrvInput[2] = 0x00; // Buttons for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvJoy1[i] & 1) << i; DrvInput[1] |= (DrvJoy2[i] & 1) << i; DrvInput[2] |= (DrvButton[i] & 1) << i; } SekNewFrame(); ZetNewFrame(); nCyclesTotal[0] = 10000000 / 60; nCyclesTotal[1] = 4000000 / 60; // SekSetCyclesScanline(nCyclesTotal[0] / 262); SekOpen(0); ZetOpen(0); SekRun(nCyclesTotal[0]); SekSetIRQLine(1, SEK_IRQSTATUS_AUTO); BurnTimerEndFrame(nCyclesTotal[1]); BurnYM2610Update(pBurnSoundOut, nBurnSoundLen); ZetClose(); SekClose(); if (pBurnDraw) DrvDraw(); return 0; } static int DrvScan(int nAction,int *pnMin) { struct BurnArea ba; if (pnMin) { // Return minimum compatible version *pnMin = 0x029671; } if (nAction & ACB_MEMORY_ROM) { // Scan all memory, devices & variables // } if (nAction & ACB_MEMORY_RAM) { // Scan all memory, devices & variables memset(&ba, 0, sizeof(ba)); ba.Data = RamStart; ba.nLen = RamEnd-RamStart; ba.szName = "All Ram"; BurnAcb(&ba); if (nAction & ACB_WRITE) { // update palette while loaded unsigned short* ps = (unsigned short*) RamPal; unsigned short* pd = RamCurPal; for (int i=0; i<1024; i++, ps++, pd++) *pd = CalcCol(*ps); } } if (nAction & ACB_DRIVER_DATA) { SekScan(nAction); // Scan 68000 state ZetOpen(0); ZetScan(nAction); // Scan Z80 state ZetClose(); SCAN_VAR(RamGfxBank); SCAN_VAR(DrvInput); BurnYM2610Scan(nAction, pnMin); SCAN_VAR(nSoundlatch); SCAN_VAR(nAerofgtZ80Bank); if (nAction & ACB_WRITE) { int nBank = nAerofgtZ80Bank; nAerofgtZ80Bank = -1; aerofgtSndBankSwitch(nBank); } } return 0; } struct BurnDriver BurnDrvAerofgt = { "aerofgt", NULL, NULL, "1992", "Aero Fighters\0", NULL, "Video System Co.", "Video System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL | BDF_16BIT_ONLY, 2, HARDWARE_MISC_POST90S, NULL, aerofgtRomInfo, aerofgtRomName, aerofgtInputInfo, aerofgtDIPInfo, aerofgtInit,DrvExit,DrvFrame,DrvDraw,DrvScan, 0, NULL, NULL, NULL, NULL, 224,320,3,4 }; // ------------------------------------------------------ static struct BurnInputInfo turbofrcInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvButton + 0, "p1 coin"}, {"P1 Start", BIT_DIGITAL, DrvButton + 2, "p1 start"}, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up"}, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down"}, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left"}, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right"}, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1"}, {"P2 Coin", BIT_DIGITAL, DrvButton + 1, "p2 coin"}, {"P2 Start", BIT_DIGITAL, DrvButton + 3, "p2 start"}, {"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up"}, {"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down"}, {"P2 Left", BIT_DIGITAL, DrvJoy2 + 2, "p2 left"}, {"P2 Right", BIT_DIGITAL, DrvJoy2 + 3, "p2 right"}, {"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1"}, {"P3 Coin", BIT_DIGITAL, DrvButton + 7, "p3 start"}, {"P3 Start", BIT_DIGITAL, DrvJoy3 + 7, "p3 start"}, {"P3 Up", BIT_DIGITAL, DrvJoy3 + 0, "p3 up"}, {"P3 Down", BIT_DIGITAL, DrvJoy3 + 1, "p3 down"}, {"P3 Left", BIT_DIGITAL, DrvJoy3 + 2, "p3 left"}, {"P3 Right", BIT_DIGITAL, DrvJoy3 + 3, "p3 right"}, {"P3 Button 1", BIT_DIGITAL, DrvJoy3 + 4, "p3 fire 1"}, {"Reset", BIT_DIGITAL, &DrvReset, "reset"}, {"Dip A", BIT_DIPSWITCH, DrvInput + 4, "dip"}, {"Dip B", BIT_DIPSWITCH, DrvInput + 5, "dip"}, }; STDINPUTINFO(turbofrc); static struct BurnDIPInfo turbofrcDIPList[] = { // Defaults {0x16, 0xFF, 0xFF, 0x00, NULL}, {0x17, 0xFF, 0xFF, 0x06, NULL}, // DIP 1 {0, 0xFE, 0, 8, "Coin 1"}, {0x16, 0x01, 0x07, 0x00, "1 coins 1 credit"}, {0x16, 0x01, 0x07, 0x01, "2 coins 1 credit"}, {0x16, 0x01, 0x07, 0x02, "3 coins 1 credit"}, {0x16, 0x01, 0x07, 0x03, "4 coins 1 credit"}, {0x16, 0x01, 0x07, 0x04, "1 coin 2 credits"}, {0x16, 0x01, 0x07, 0x05, "1 coin 3 credits"}, {0x16, 0x01, 0x07, 0x06, "1 coin 5 credits"}, {0x16, 0x01, 0x07, 0x07, "1 coin 6 credits"}, {0, 0xFE, 0, 2, "2 Coins to Start, 1 to Continue"}, {0x16, 0x01, 0x08, 0x00, "Off"}, {0x16, 0x01, 0x08, 0x08, "On"}, {0, 0xFE, 0, 2, "Coin Slot"}, {0x16, 0x01, 0x10, 0x00, "Same"}, {0x16, 0x01, 0x10, 0x10, "Individual"}, {0, 0xFE, 0, 2, "Play Mode"}, {0x16, 0x01, 0x20, 0x00, "2 Players"}, {0x16, 0x01, 0x20, 0x20, "3 Players"}, {0, 0xFE, 0, 2, "Demo_Sounds"}, {0x16, 0x01, 0x40, 0x00, "Off"}, {0x16, 0x01, 0x40, 0x40, "On"}, {0, 0xFE, 0, 2, "Service"}, {0x16, 0x01, 0x80, 0x00, "Off"}, {0x16, 0x01, 0x80, 0x80, "On"}, // DIP 2 {0, 0xFE, 0, 2, "Screen flip"}, {0x17, 0x01, 0x01, 0x00, "Off"}, {0x17, 0x01, 0x01, 0x01, "On"}, {0, 0xFE, 0, 8, "Difficulty"}, {0x17, 0x01, 0x0E, 0x00, "1 (Easiest)"}, {0x17, 0x01, 0x0E, 0x02, "2"}, {0x17, 0x01, 0x0E, 0x04, "3"}, {0x17, 0x01, 0x0E, 0x06, "4 (Normal)"}, {0x17, 0x01, 0x0E, 0x08, "5"}, {0x17, 0x01, 0x0E, 0x0A, "6"}, {0x17, 0x01, 0x0E, 0x0C, "7"}, {0x17, 0x01, 0x0E, 0x0E, "8 (Hardest)"}, {0, 0xFE, 0, 2, "Lives"}, {0x17, 0x01, 0x10, 0x00, "3"}, {0x17, 0x01, 0x10, 0x10, "2"}, {0, 0xFE, 0, 2, "Bonus Life"}, {0x17, 0x01, 0x20, 0x00, "300000"}, {0x17, 0x01, 0x20, 0x20, "200000"}, }; STDDIPINFO(turbofrc); static struct BurnRomInfo turbofrcRomDesc[] = { { "tfrc2.bin", 0x040000, 0x721300ee, BRF_ESS | BRF_PRG }, // 68000 code swapped { "tfrc1.bin", 0x040000, 0x6cd5312b, BRF_ESS | BRF_PRG }, { "tfrc3.bin", 0x040000, 0x63f50557, BRF_ESS | BRF_PRG }, { "tfrcu94.bin", 0x080000, 0xbaa53978, BRF_GRA }, // gfx1 { "tfrcu95.bin", 0x020000, 0x71a6c573, BRF_GRA }, { "tfrcu105.bin", 0x080000, 0x4de4e59e, BRF_GRA }, // gfx2 { "tfrcu106.bin", 0x020000, 0xc6479eb5, BRF_GRA }, { "tfrcu116.bin", 0x080000, 0xdf210f3b, BRF_GRA }, // gfx3 { "tfrcu118.bin", 0x040000, 0xf61d1d79, BRF_GRA }, { "tfrcu117.bin", 0x080000, 0xf70812fd, BRF_GRA }, { "tfrcu119.bin", 0x040000, 0x474ea716, BRF_GRA }, { "tfrcu134.bin", 0x080000, 0x487330a2, BRF_GRA }, // gfx4 { "tfrcu135.bin", 0x080000, 0x3a7e5b6d, BRF_GRA }, { "tfrcu166.bin", 0x020000, 0x2ca14a65, BRF_ESS | BRF_PRG }, // Sound CPU { "tfrcu180.bin", 0x020000, 0x39c7c7d5, BRF_SND }, // samples { "tfrcu179.bin", 0x100000, 0x60ca0333, BRF_SND }, }; STD_ROM_PICK(turbofrc); STD_ROM_FN(turbofrc); unsigned char __fastcall turbofrcReadByte(unsigned int sekAddress) { sekAddress &= 0x0FFFFF; switch (sekAddress) { case 0x0FF000: return ~DrvInput[3]; case 0x0FF001: return ~DrvInput[0]; case 0x0FF002: return 0xFF; case 0x0FF003: return ~DrvInput[1]; case 0x0FF004: return ~DrvInput[5]; case 0x0FF005: return ~DrvInput[4]; case 0x0FF007: return pending_command; case 0x0FF009: return ~DrvInput[2]; // default: // printf("Attempt to read byte value of location %x\n", sekAddress); } return 0; } /* unsigned short __fastcall turbofrcReadWord(unsigned int sekAddress) { // sekAddress &= 0x0FFFFF; // switch (sekAddress) { // default: // printf("Attempt to read word value of location %x\n", sekAddress); // } return 0; } */ void __fastcall turbofrcWriteByte(unsigned int sekAddress, unsigned char byteValue) { if (( sekAddress & 0x0FF000 ) == 0x0FE000) { sekAddress &= 0x07FF; RamPal[sekAddress^1] = byteValue; // palette byte write at boot self-test only ?! //if (sekAddress & 1) // RamCurPal[sekAddress>>1] = CalcCol( *((unsigned short *)&RamPal[sekAddress & 0xFFE]) ); return; } sekAddress &= 0x0FFFFF; switch (sekAddress) { case 0x0FF00E: pending_command = 1; SoundCommand(byteValue); break; // default: // printf("Attempt to write byte value %x to location %x\n", byteValue, sekAddress); } } void __fastcall turbofrcWriteWord(unsigned int sekAddress, unsigned short wordValue) { if (( sekAddress & 0x0FF000 ) == 0x0FE000) { sekAddress &= 0x07FE; *((unsigned short *)&RamPal[sekAddress]) = wordValue; RamCurPal[sekAddress>>1] = CalcCol( wordValue ); return; } sekAddress &= 0x0FFFFF; switch (sekAddress) { case 0x0FF002: bg1scrolly = wordValue; break; case 0x0FF004: bg2scrollx = wordValue; break; case 0x0FF006: bg2scrolly = wordValue; break; case 0x0FF008: RamGfxBank[0] = (wordValue >> 0) & 0x0f; RamGfxBank[1] = (wordValue >> 4) & 0x0f; RamGfxBank[2] = (wordValue >> 8) & 0x0f; RamGfxBank[3] = (wordValue >> 12) & 0x0f; break; case 0x0FF00A: RamGfxBank[4] = (wordValue >> 0) & 0x0f; RamGfxBank[5] = (wordValue >> 4) & 0x0f; RamGfxBank[6] = (wordValue >> 8) & 0x0f; RamGfxBank[7] = (wordValue >> 12) & 0x0f; break; case 0x0FF00C: // NOP break; // default: // printf("Attempt to write word value %x to location %x\n", wordValue, sekAddress); } } unsigned char __fastcall turbofrcZ80PortRead(unsigned short p) { switch (p & 0xFF) { case 0x14: return nSoundlatch; case 0x18: return BurnYM2610Read(0); case 0x1A: return BurnYM2610Read(2); // default: // printf("Z80 Attempt to read port %04x\n", p); } return 0; } void __fastcall turbofrcZ80PortWrite(unsigned short p, unsigned char v) { switch (p & 0x0FF) { case 0x18: case 0x19: case 0x1A: case 0x1B: BurnYM2610Write((p - 0x18) & 3, v); break; case 0x00: aerofgtSndBankSwitch(v); break; case 0x14: pending_command = 0; break; // default: // printf("Z80 Attempt to write %02x to port %04x\n", v, p); } } static int turbofrcMemIndex() { unsigned char *Next; Next = Mem; Rom01 = Next; Next += 0x0C0000; // 68000 ROM RomZ80 = Next; Next += 0x030000; // Z80 ROM RomBg = Next; Next += 0x280040; // DeRomBg = RomBg + 0x000040; RomSpr1 = Next; Next += 0x400000; // Sprite 1 RomSpr2 = Next; Next += 0x200100; // Sprite 2 DeRomSpr1 = RomSpr1 + 0x000100; DeRomSpr2 = RomSpr2 += 0x000100; RomSnd1 = Next; Next += 0x020000; // ADPCM data RomSndSize1 = 0x020000; RomSnd2 = Next; Next += 0x100000; // ADPCM data RomSndSize2 = 0x100000; RamStart = Next; RamBg1V = (unsigned short *)Next; Next += 0x002000; // BG1 Video Ram RamBg2V = (unsigned short *)Next; Next += 0x002000; // BG2 Video Ram RamSpr1 = (unsigned short *)Next; Next += 0x004000; // Sprite 1 Ram RamSpr2 = (unsigned short *)Next; Next += 0x004000; // Sprite 2 Ram RamSpr3 = (unsigned short *)Next; Next += 0x000800; // Sprite 3 Ram RamRaster = (unsigned short *)Next; Next += 0x001000; // Raster Ram RamSpr1SizeMask = 0x1FFF; RamSpr2SizeMask = 0x1FFF; RomSpr1SizeMask = 0x3FFF; RomSpr2SizeMask = 0x1FFF; Ram01 = Next; Next += 0x014000; // Work Ram RamPal = Next; Next += 0x000800; // 1024 of X1R5G5B5 Palette RamZ80 = Next; Next += 0x000800; // Z80 Ram 2K RamEnd = Next; RamCurPal = (unsigned short *)Next; Next += 0x000800; MemEnd = Next; return 0; } static void pspikesDecodeBg(int cnt) { for (int c=cnt-1; c>=0; c--) { for (int y=7; y>=0; y--) { DeRomBg[(c * 64) + (y * 8) + 7] = RomBg[0x00003 + (y * 4) + (c * 32)] >> 4; DeRomBg[(c * 64) + (y * 8) + 6] = RomBg[0x00003 + (y * 4) + (c * 32)] & 0x0f; DeRomBg[(c * 64) + (y * 8) + 5] = RomBg[0x00002 + (y * 4) + (c * 32)] >> 4; DeRomBg[(c * 64) + (y * 8) + 4] = RomBg[0x00002 + (y * 4) + (c * 32)] & 0x0f; DeRomBg[(c * 64) + (y * 8) + 3] = RomBg[0x00001 + (y * 4) + (c * 32)] >> 4; DeRomBg[(c * 64) + (y * 8) + 2] = RomBg[0x00001 + (y * 4) + (c * 32)] & 0x0f; DeRomBg[(c * 64) + (y * 8) + 1] = RomBg[0x00000 + (y * 4) + (c * 32)] >> 4; DeRomBg[(c * 64) + (y * 8) + 0] = RomBg[0x00000 + (y * 4) + (c * 32)] & 0x0f; } } } static void pspikesDecodeSpr(unsigned char *d, unsigned char *s, int cnt) { for (int c=cnt-1; c>=0; c--) for (int y=15; y>=0; y--) { d[(c * 256) + (y * 16) + 15] = s[0x00007 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 14] = s[0x00007 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 13] = s[0x00005 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 12] = s[0x00005 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 11] = s[0x00006 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 10] = s[0x00006 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 9] = s[0x00004 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 8] = s[0x00004 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 7] = s[0x00003 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 6] = s[0x00003 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 5] = s[0x00001 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 4] = s[0x00001 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 3] = s[0x00002 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 2] = s[0x00002 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 1] = s[0x00000 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 0] = s[0x00000 + (y * 8) + (c * 128)] & 0x0f; } } static int turbofrcInit() { Mem = NULL; turbofrcMemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); turbofrcMemIndex(); // Load 68000 ROM if (BurnLoadRom(Rom01+0x00000, 0, 1)) return 1; if (BurnLoadRom(Rom01+0x40000, 1, 1)) return 1; if (BurnLoadRom(Rom01+0x80000, 2, 1)) return 1; // Load Graphic BurnLoadRom(RomBg+0x000000, 3, 1); BurnLoadRom(RomBg+0x080000, 4, 1); BurnLoadRom(RomBg+0x0A0000, 5, 1); BurnLoadRom(RomBg+0x120000, 6, 1); pspikesDecodeBg(0x14000); BurnLoadRom(RomSpr1+0x000000, 7, 2); BurnLoadRom(RomSpr1+0x000001, 9, 2); BurnLoadRom(RomSpr1+0x100000, 8, 2); BurnLoadRom(RomSpr1+0x100001, 10, 2); BurnLoadRom(RomSpr1+0x200000, 11, 2); BurnLoadRom(RomSpr1+0x200001, 12, 2); pspikesDecodeSpr(DeRomSpr1, RomSpr1, 0x6000); // Load Z80 ROM if (BurnLoadRom(RomZ80+0x10000, 13, 1)) return 1; memcpy(RomZ80, RomZ80+0x10000, 0x10000); BurnLoadRom(RomSnd1, 14, 1); BurnLoadRom(RomSnd2, 15, 1); { SekInit(0, 0x68000); // Allocate 68000 SekOpen(0); // Map 68000 memory: SekMapMemory(Rom01, 0x000000, 0x0BFFFF, SM_ROM); // CPU 0 ROM SekMapMemory(Ram01, 0x0C0000, 0x0CFFFF, SM_RAM); // 64K Work RAM SekMapMemory((unsigned char *)RamBg1V, 0x0D0000, 0x0D1FFF, SM_RAM); SekMapMemory((unsigned char *)RamBg2V, 0x0D2000, 0x0D3FFF, SM_RAM); SekMapMemory((unsigned char *)RamSpr1, 0x0E0000, 0x0E3FFF, SM_RAM); SekMapMemory((unsigned char *)RamSpr2, 0x0E4000, 0x0E7FFF, SM_RAM); SekMapMemory(Ram01+0x10000, 0x0F8000, 0x0FBFFF, SM_RAM); // Work RAM SekMapMemory(Ram01+0x10000, 0xFF8000, 0xFFBFFF, SM_RAM); // Work RAM SekMapMemory((unsigned char *)RamSpr3, 0x0FC000, 0x0FC7FF, SM_RAM); SekMapMemory((unsigned char *)RamSpr3, 0xFFC000, 0xFFC7FF, SM_RAM); SekMapMemory((unsigned char *)RamRaster, 0x0FD000, 0x0FDFFF, SM_RAM); SekMapMemory((unsigned char *)RamRaster, 0xFFD000, 0xFFDFFF, SM_RAM); SekMapMemory(RamPal, 0x0FE000, 0x0FE7FF, SM_ROM); // Palette // SekSetReadWordHandler(0, turbofrcReadWord); SekSetReadByteHandler(0, turbofrcReadByte); SekSetWriteWordHandler(0, turbofrcWriteWord); SekSetWriteByteHandler(0, turbofrcWriteByte); SekClose(); } { ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x77FF, 0, RomZ80); ZetMapArea(0x0000, 0x77FF, 2, RomZ80); ZetMapArea(0x7800, 0x7FFF, 0, RamZ80); ZetMapArea(0x7800, 0x7FFF, 1, RamZ80); ZetMapArea(0x7800, 0x7FFF, 2, RamZ80); ZetMemEnd(); ZetSetInHandler(turbofrcZ80PortRead); ZetSetOutHandler(turbofrcZ80PortWrite); ZetClose(); } BurnYM2610Init(8000000, RomSnd2, &RomSndSize2, RomSnd1, &RomSndSize1, &aerofgtFMIRQHandler, aerofgtSynchroniseStream, aerofgtGetTime, 0); BurnTimerAttachZet(4000000); DrvDoReset(); return 0; } static void turbofrcTileBackground_1(unsigned short *bg, unsigned char *BgGfx, unsigned short *pal) { int offs, mx, my, x, y; mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - (RamRaster[7] & 0x1FF) - 11; if (x <= (352-512)) x += 512; y = my * 8 - (bg1scrolly & 0x1FF) - 2; if (y <= (240-512)) y += 512; if ( x<=-8 || x>=352 || y<=-8 || y>= 240 ) continue; else if ( x >=0 && x < (352-8) && y >= 0 && y < (240-8)) { unsigned char *d = BgGfx + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11)] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { p[0] = pal[ d[0] | c ]; p[1] = pal[ d[1] | c ]; p[2] = pal[ d[2] | c ]; p[3] = pal[ d[3] | c ]; p[4] = pal[ d[4] | c ]; p[5] = pal[ d[5] | c ]; p[6] = pal[ d[6] | c ]; p[7] = pal[ d[7] | c ]; d += 8; p += 352; } } else { unsigned char *d = BgGfx + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11)] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<240 ) { if ((x + 0) >= 0 && (x + 0)<352) p[0] = pal[ d[0] | c ]; if ((x + 1) >= 0 && (x + 1)<352) p[1] = pal[ d[1] | c ]; if ((x + 2) >= 0 && (x + 2)<352) p[2] = pal[ d[2] | c ]; if ((x + 3) >= 0 && (x + 3)<352) p[3] = pal[ d[3] | c ]; if ((x + 4) >= 0 && (x + 4)<352) p[4] = pal[ d[4] | c ]; if ((x + 5) >= 0 && (x + 5)<352) p[5] = pal[ d[5] | c ]; if ((x + 6) >= 0 && (x + 6)<352) p[6] = pal[ d[6] | c ]; if ((x + 7) >= 0 && (x + 7)<352) p[7] = pal[ d[7] | c ]; } d += 8; p += 352; } } } } static void turbofrcTileBackground_2(unsigned short *bg, unsigned char *BgGfx, unsigned short *pal) { int offs, mx, my, x, y; mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - (bg2scrollx & 0x1FF) + 7; if (x <= (352-512)) x += 512; y = my * 8 - (bg2scrolly & 0x1FF) - 2; if (y <= (240-512)) y += 512; if ( x<=-8 || x>=352 || y<=-8 || y>= 240 ) continue; else if ( x >=0 && x < (352-8) && y >= 0 && y < (240-8)) { unsigned char *d = BgGfx + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11) + 4] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { if (d[0] != 15) p[0] = pal[ d[0] | c ]; if (d[1] != 15) p[1] = pal[ d[1] | c ]; if (d[2] != 15) p[2] = pal[ d[2] | c ]; if (d[3] != 15) p[3] = pal[ d[3] | c ]; if (d[4] != 15) p[4] = pal[ d[4] | c ]; if (d[5] != 15) p[5] = pal[ d[5] | c ]; if (d[6] != 15) p[6] = pal[ d[6] | c ]; if (d[7] != 15) p[7] = pal[ d[7] | c ]; d += 8; p += 352; } } else { unsigned char *d = BgGfx + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11) + 4] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<240 ) { if (d[0] != 15 && (x + 0) >= 0 && (x + 0)<352) p[0] = pal[ d[0] | c ]; if (d[1] != 15 && (x + 1) >= 0 && (x + 1)<352) p[1] = pal[ d[1] | c ]; if (d[2] != 15 && (x + 2) >= 0 && (x + 2)<352) p[2] = pal[ d[2] | c ]; if (d[3] != 15 && (x + 3) >= 0 && (x + 3)<352) p[3] = pal[ d[3] | c ]; if (d[4] != 15 && (x + 4) >= 0 && (x + 4)<352) p[4] = pal[ d[4] | c ]; if (d[5] != 15 && (x + 5) >= 0 && (x + 5)<352) p[5] = pal[ d[5] | c ]; if (d[6] != 15 && (x + 6) >= 0 && (x + 6)<352) p[6] = pal[ d[6] | c ]; if (d[7] != 15 && (x + 7) >= 0 && (x + 7)<352) p[7] = pal[ d[7] | c ]; } d += 8; p += 352; } } } } static void pdrawgfxzoom(int bank,unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,int scalex,int scaley) { if (!scalex || !scaley) return; unsigned short * p = (unsigned short *) pBurnDraw; unsigned char * q; unsigned short * pal; if (bank) { //if (code > RomSpr2SizeMask) code &= RomSpr2SizeMask; q = DeRomSpr2 + (code) * 256; pal = RamCurPal + 768; } else { //if (code > RomSpr1SizeMask) code &= RomSpr1SizeMask; q = DeRomSpr1 + (code) * 256; pal = RamCurPal + 512; } p += sy * 352 + sx; if (sx < 0 || sx >= (352-16) || sy < 0 || sy >= (240-16) ) { if ((sx <= -16) || (sx >= 352) || (sy <= -16) || (sy >= 240)) return; if (flipy) { p += 352 * 15; if (flipx) { for (int i=15;i>=0;i--) { if (((sy+i)>=0) && ((sy+i)<240)) { if (q[ 0] != 15 && ((sx + 15) >= 0) && ((sx + 15)<352)) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 14) >= 0) && ((sx + 14)<352)) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 13) >= 0) && ((sx + 13)<352)) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 12) >= 0) && ((sx + 12)<352)) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 11) >= 0) && ((sx + 11)<352)) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 10) >= 0) && ((sx + 10)<352)) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 9) >= 0) && ((sx + 9)<352)) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 8) >= 0) && ((sx + 8)<352)) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 7) >= 0) && ((sx + 7)<352)) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 6) >= 0) && ((sx + 6)<352)) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 5) >= 0) && ((sx + 5)<352)) p[ 5] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 4) >= 0) && ((sx + 4)<352)) p[ 4] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 3) >= 0) && ((sx + 3)<352)) p[ 3] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 2) >= 0) && ((sx + 2)<352)) p[ 2] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 1) >= 0) && ((sx + 1)<352)) p[ 1] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 0) >= 0) && ((sx + 0)<352)) p[ 0] = pal[ q[15] | color]; } p -= 352; q += 16; } } else { for (int i=15;i>=0;i--) { if (((sy+i)>=0) && ((sy+i)<240)) { if (q[ 0] != 15 && ((sx + 0) >= 0) && ((sx + 0)<352)) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 1) >= 0) && ((sx + 1)<352)) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 2) >= 0) && ((sx + 2)<352)) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 3) >= 0) && ((sx + 3)<352)) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 4) >= 0) && ((sx + 4)<352)) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 5) >= 0) && ((sx + 5)<352)) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 6) >= 0) && ((sx + 6)<352)) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 7) >= 0) && ((sx + 7)<352)) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 8) >= 0) && ((sx + 8)<352)) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 9) >= 0) && ((sx + 9)<352)) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 10) >= 0) && ((sx + 10)<352)) p[10] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 11) >= 0) && ((sx + 11)<352)) p[11] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 12) >= 0) && ((sx + 12)<352)) p[12] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 13) >= 0) && ((sx + 13)<352)) p[13] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 14) >= 0) && ((sx + 14)<352)) p[14] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 15) >= 0) && ((sx + 15)<352)) p[15] = pal[ q[15] | color]; } p -= 352; q += 16; } } } else { if (flipx) { for (int i=0;i<16;i++) { if (((sy+i)>=0) && ((sy+i)<240)) { if (q[ 0] != 15 && ((sx + 15) >= 0) && ((sx + 15)<352)) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 14) >= 0) && ((sx + 14)<352)) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 13) >= 0) && ((sx + 13)<352)) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 12) >= 0) && ((sx + 12)<352)) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 11) >= 0) && ((sx + 11)<352)) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 10) >= 0) && ((sx + 10)<352)) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 9) >= 0) && ((sx + 9)<352)) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 8) >= 0) && ((sx + 8)<352)) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 7) >= 0) && ((sx + 7)<352)) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 6) >= 0) && ((sx + 6)<352)) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 5) >= 0) && ((sx + 5)<352)) p[ 5] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 4) >= 0) && ((sx + 4)<352)) p[ 4] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 3) >= 0) && ((sx + 3)<352)) p[ 3] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 2) >= 0) && ((sx + 2)<352)) p[ 2] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 1) >= 0) && ((sx + 1)<352)) p[ 1] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 0) >= 0) && ((sx + 0)<352)) p[ 0] = pal[ q[15] | color]; } p += 352; q += 16; } } else { for (int i=0;i<16;i++) { if (((sy+i)>=0) && ((sy+i)<240)) { if (q[ 0] != 15 && ((sx + 0) >= 0) && ((sx + 0)<352)) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 1) >= 0) && ((sx + 1)<352)) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 2) >= 0) && ((sx + 2)<352)) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 3) >= 0) && ((sx + 3)<352)) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 4) >= 0) && ((sx + 4)<352)) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 5) >= 0) && ((sx + 5)<352)) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 6) >= 0) && ((sx + 6)<352)) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 7) >= 0) && ((sx + 7)<352)) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 8) >= 0) && ((sx + 8)<352)) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 9) >= 0) && ((sx + 9)<352)) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 10) >= 0) && ((sx + 10)<352)) p[10] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 11) >= 0) && ((sx + 11)<352)) p[11] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 12) >= 0) && ((sx + 12)<352)) p[12] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 13) >= 0) && ((sx + 13)<352)) p[13] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 14) >= 0) && ((sx + 14)<352)) p[14] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 15) >= 0) && ((sx + 15)<352)) p[15] = pal[ q[15] | color]; } p += 352; q += 16; } } } return; } if (flipy) { p += 352 * 15; if (flipx) { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15) p[ 5] = pal[ q[10] | color]; if (q[11] != 15) p[ 4] = pal[ q[11] | color]; if (q[12] != 15) p[ 3] = pal[ q[12] | color]; if (q[13] != 15) p[ 2] = pal[ q[13] | color]; if (q[14] != 15) p[ 1] = pal[ q[14] | color]; if (q[15] != 15) p[ 0] = pal[ q[15] | color]; p -= 352; q += 16; } } else { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15) p[10] = pal[ q[10] | color]; if (q[11] != 15) p[11] = pal[ q[11] | color]; if (q[12] != 15) p[12] = pal[ q[12] | color]; if (q[13] != 15) p[13] = pal[ q[13] | color]; if (q[14] != 15) p[14] = pal[ q[14] | color]; if (q[15] != 15) p[15] = pal[ q[15] | color]; p -= 352; q += 16; } } } else { if (flipx) { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15) p[ 5] = pal[ q[10] | color]; if (q[11] != 15) p[ 4] = pal[ q[11] | color]; if (q[12] != 15) p[ 3] = pal[ q[12] | color]; if (q[13] != 15) p[ 2] = pal[ q[13] | color]; if (q[14] != 15) p[ 1] = pal[ q[14] | color]; if (q[15] != 15) p[ 0] = pal[ q[15] | color]; p += 352; q += 16; } } else { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15) p[10] = pal[ q[10] | color]; if (q[11] != 15) p[11] = pal[ q[11] | color]; if (q[12] != 15) p[12] = pal[ q[12] | color]; if (q[13] != 15) p[13] = pal[ q[13] | color]; if (q[14] != 15) p[14] = pal[ q[14] | color]; if (q[15] != 15) p[15] = pal[ q[15] | color]; p += 352; q += 16; } } } } static void turbofrc_drawsprites(int chip,int chip_disabled_pri) { int attr_start,base,first; base = chip * 0x0200; first = 4 * RamSpr3[0x1fe + base]; //for (attr_start = base + 0x0200-8;attr_start >= first + base;attr_start -= 4) { for (attr_start = first + base; attr_start <= base + 0x0200-8; attr_start += 4) { int map_start; int ox,oy,x,y,xsize,ysize,zoomx,zoomy,flipx,flipy,color,pri; // some other drivers still use this wrong table, they have to be upgraded // int zoomtable[16] = { 0,7,14,20,25,30,34,38,42,46,49,52,54,57,59,61 }; if (!(RamSpr3[attr_start + 2] & 0x0080)) continue; pri = RamSpr3[attr_start + 2] & 0x0010; if ( chip_disabled_pri & !pri) continue; if (!chip_disabled_pri & (pri>>4)) continue; ox = RamSpr3[attr_start + 1] & 0x01ff; xsize = (RamSpr3[attr_start + 2] & 0x0700) >> 8; zoomx = (RamSpr3[attr_start + 1] & 0xf000) >> 12; oy = RamSpr3[attr_start + 0] & 0x01ff; ysize = (RamSpr3[attr_start + 2] & 0x7000) >> 12; zoomy = (RamSpr3[attr_start + 0] & 0xf000) >> 12; flipx = RamSpr3[attr_start + 2] & 0x0800; flipy = RamSpr3[attr_start + 2] & 0x8000; color = (RamSpr3[attr_start + 2] & 0x000f) << 4; // + 16 * spritepalettebank; map_start = RamSpr3[attr_start + 3]; // aerofgt has this adjustment, but doing it here would break turbo force title screen // ox += (xsize*zoomx+2)/4; // oy += (ysize*zoomy+2)/4; zoomx = 32 - zoomx; zoomy = 32 - zoomy; for (y = 0;y <= ysize;y++) { int sx,sy; if (flipy) sy = ((oy + zoomy * (ysize - y)/2 + 16) & 0x1ff) - 16; else sy = ((oy + zoomy * y / 2 + 16) & 0x1ff) - 16; for (x = 0;x <= xsize;x++) { int code; if (flipx) sx = ((ox + zoomx * (xsize - x) / 2 + 16) & 0x1ff) - 16 - 8; else sx = ((ox + zoomx * x / 2 + 16) & 0x1ff) - 16 - 8; if (chip == 0) code = RamSpr1[map_start & RamSpr1SizeMask]; else code = RamSpr2[map_start & RamSpr2SizeMask]; pdrawgfxzoom(chip,code,color,flipx,flipy,sx,sy,zoomx << 11, zoomy << 11); map_start++; } if (xsize == 2) map_start += 1; if (xsize == 4) map_start += 3; if (xsize == 5) map_start += 2; if (xsize == 6) map_start += 1; } } } static int turbofrcDraw() { turbofrcTileBackground_1(RamBg1V, DeRomBg, RamCurPal); turbofrcTileBackground_2(RamBg2V, DeRomBg + 0x140000, RamCurPal + 256); /* // we use the priority buffer so sprites are drawn front to back turbofrc_drawsprites(0,-1); //enemy turbofrc_drawsprites(0, 0); //enemy turbofrc_drawsprites(1,-1); //ship turbofrc_drawsprites(1, 0); //intro */ // in MAME it use a pri-buf control render to draw sprites from front to back // i'm not use it, is right ??? turbofrc_drawsprites(0, 0); turbofrc_drawsprites(0,-1); turbofrc_drawsprites(1, 0); turbofrc_drawsprites(1,-1); return 0; } static int turbofrcFrame() { if (DrvReset) DrvDoReset(); // Compile digital inputs // Compile digital inputs DrvInput[0] = 0x00; // Joy1 DrvInput[1] = 0x00; // Joy2 DrvInput[2] = 0x00; // Joy3 DrvInput[3] = 0x00; // Buttons for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvJoy1[i] & 1) << i; DrvInput[1] |= (DrvJoy2[i] & 1) << i; DrvInput[2] |= (DrvJoy3[i] & 1) << i; DrvInput[3] |= (DrvButton[i] & 1) << i; } SekNewFrame(); ZetNewFrame(); nCyclesTotal[0] = 10000000 / 60; nCyclesTotal[1] = 4000000 / 60; SekOpen(0); ZetOpen(0); SekRun(nCyclesTotal[0]); SekSetIRQLine(1, SEK_IRQSTATUS_AUTO); BurnTimerEndFrame(nCyclesTotal[1]); BurnYM2610Update(pBurnSoundOut, nBurnSoundLen); ZetClose(); SekClose(); if (pBurnDraw) turbofrcDraw(); return 0; } struct BurnDriver BurnDrvTurbofrc = { "turbofrc", NULL, NULL, "1991", "Turbo Force\0", NULL, "Video System Co.", "Video System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL | BDF_16BIT_ONLY, 3, HARDWARE_MISC_POST90S, NULL, turbofrcRomInfo, turbofrcRomName, turbofrcInputInfo, turbofrcDIPInfo, turbofrcInit,DrvExit,turbofrcFrame,turbofrcDraw,DrvScan, 0, NULL, NULL, NULL, NULL,240,352,3,4 }; // ------------------------------------------------------------ static struct BurnInputInfo karatblzInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvButton + 0, "p1 coin"}, {"P1 Start", BIT_DIGITAL, DrvButton + 2, "p1 start"}, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up"}, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down"}, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left"}, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right"}, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1"}, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2"}, {"P1 Button 3", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3"}, {"P1 Button 4", BIT_DIGITAL, DrvJoy1 + 7, "p1 fire 4"}, {"P2 Coin", BIT_DIGITAL, DrvButton + 1, "p2 coin"}, {"P2 Start", BIT_DIGITAL, DrvButton + 3, "p2 start"}, {"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up"}, {"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down"}, {"P2 Left", BIT_DIGITAL, DrvJoy2 + 2, "p2 left"}, {"P2 Right", BIT_DIGITAL, DrvJoy2 + 3, "p2 right"}, {"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1"}, {"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2"}, {"P2 Button 3", BIT_DIGITAL, DrvJoy2 + 6, "p2 fire 3"}, {"P2 Button 4", BIT_DIGITAL, DrvJoy2 + 7, "p2 fire 4"}, {"P3 Coin", BIT_DIGITAL, DrvButton + 4, "p3 coin"}, {"P3 Start", BIT_DIGITAL, DrvButton + 6, "p3 start"}, {"P3 Up", BIT_DIGITAL, DrvJoy3 + 0, "p3 up"}, {"P3 Down", BIT_DIGITAL, DrvJoy3 + 1, "p3 down"}, {"P3 Left", BIT_DIGITAL, DrvJoy3 + 2, "p3 left"}, {"P3 Right", BIT_DIGITAL, DrvJoy3 + 3, "p3 right"}, {"P3 Button 1", BIT_DIGITAL, DrvJoy3 + 4, "p3 fire 1"}, {"P3 Button 2", BIT_DIGITAL, DrvJoy3 + 5, "p3 fire 2"}, {"P3 Button 3", BIT_DIGITAL, DrvJoy3 + 6, "p3 fire 3"}, {"P3 Button 4", BIT_DIGITAL, DrvJoy3 + 7, "p3 fire 4"}, {"P4 Coin", BIT_DIGITAL, DrvButton + 5, "p4 coin"}, {"P4 Start", BIT_DIGITAL, DrvButton + 7, "p4 start"}, {"P4 Up", BIT_DIGITAL, DrvJoy4 + 0, "p4 up"}, {"P4 Down", BIT_DIGITAL, DrvJoy4 + 1, "p4 down"}, {"P4 Left", BIT_DIGITAL, DrvJoy4 + 2, "p4 left"}, {"P4 Right", BIT_DIGITAL, DrvJoy4 + 3, "p4 right"}, {"P4 Button 1", BIT_DIGITAL, DrvJoy4 + 4, "p4 fire 1"}, {"P4 Button 2", BIT_DIGITAL, DrvJoy4 + 5, "p4 fire 2"}, {"P4 Button 3", BIT_DIGITAL, DrvJoy4 + 6, "p4 fire 3"}, {"P4 Button 4", BIT_DIGITAL, DrvJoy4 + 7, "p4 fire 4"}, {"Reset", BIT_DIGITAL, &DrvReset, "reset"}, {"Dip A", BIT_DIPSWITCH, DrvInput + 6, "dip"}, {"Dip B", BIT_DIPSWITCH, DrvInput + 7, "dip"}, }; STDINPUTINFO(karatblz); static struct BurnDIPInfo karatblzDIPList[] = { // Defaults {0x29, 0xFF, 0xFF, 0x00, NULL}, {0x2A, 0xFF, 0xFF, 0x00, NULL}, // DIP 1 {0, 0xFE, 0, 8, "Coinage"}, {0x29, 0x01, 0x07, 0x00, "1 coin 1 credit"}, {0x29, 0x01, 0x07, 0x01, "2 coins 1 credit"}, {0x29, 0x01, 0x07, 0x02, "3 coins 1 credit"}, {0x29, 0x01, 0x07, 0x03, "4 coins 1 credit"}, {0x29, 0x01, 0x07, 0x04, "1 coin 2 credit"}, {0x29, 0x01, 0x07, 0x05, "1 coin 3 credit"}, {0x29, 0x01, 0x07, 0x06, "1 coin 5 credit"}, {0x29, 0x01, 0x07, 0x07, "1 coin 6 credit"}, {0, 0xFE, 0, 2, "2 Coins to Start, 1 to Continue"}, {0x29, 0x01, 0x08, 0x00, "Off"}, {0x29, 0x01, 0x08, 0x08, "On"}, {0, 0xFE, 0, 2, "Lives"}, {0x29, 0x01, 0x10, 0x00, "2"}, {0x29, 0x01, 0x10, 0x10, "1"}, {0, 0xFE, 0, 4, "Cabinet"}, {0x29, 0x01, 0x60, 0x00, "2 Players"}, {0x29, 0x01, 0x60, 0x20, "3 Players"}, {0x29, 0x01, 0x60, 0x40, "4 Players"}, {0x29, 0x01, 0x60, 0x60, "4 Players (Team)"}, {0, 0xFE, 0, 2, "Coin Slot"}, {0x29, 0x01, 0x80, 0x00, "Same"}, {0x29, 0x01, 0x80, 0x80, "Individual"}, // DIP 2 {0, 0xFE, 0, 2, "Unknown"}, {0x2A, 0x01, 0x01, 0x00, "Off"}, {0x2A, 0x01, 0x01, 0x01, "On"}, {0, 0xFE, 0, 4, "Number of Enemies"}, {0x2A, 0x01, 0x06, 0x00, "Normal"}, {0x2A, 0x01, 0x06, 0x02, "Easy"}, {0x2A, 0x01, 0x06, 0x04, "Hard"}, {0x2A, 0x01, 0x06, 0x06, "Hardest"}, {0, 0xFE, 0, 4, "Strength of Enemies"}, {0x2A, 0x01, 0x18, 0x00, "Normal"}, {0x2A, 0x01, 0x18, 0x08, "Easy"}, {0x2A, 0x01, 0x18, 0x10, "Hard"}, {0x2A, 0x01, 0x18, 0x18, "Hardest"}, {0, 0xFE, 0, 2, "Freeze"}, {0x2A, 0x01, 0x20, 0x00, "Off"}, {0x2A, 0x01, 0x20, 0x20, "On"}, {0, 0xFE, 0, 2, "Demo sound"}, {0x2A, 0x01, 0x40, 0x00, "Off"}, {0x2A, 0x01, 0x40, 0x40, "On"}, {0, 0xFE, 0, 2, "Flip Screen"}, {0x2A, 0x01, 0x80, 0x00, "Off"}, {0x2A, 0x01, 0x80, 0x80, "On"}, }; STDDIPINFO(karatblz); static struct BurnRomInfo karatblzRomDesc[] = { { "rom2v3", 0x040000, 0x01f772e1, BRF_ESS | BRF_PRG }, // 68000 code swapped { "1.u15", 0x040000, 0xd16ee21b, BRF_ESS | BRF_PRG }, { "gha.u55", 0x080000, 0x3e0cea91, BRF_GRA }, // gfx1 { "gh9.u61", 0x080000, 0x5d1676bd, BRF_GRA }, // gfx2 { "u42", 0x100000, 0x65f0da84, BRF_GRA }, // gfx3 { "3.u44", 0x020000, 0x34bdead2, BRF_GRA }, { "u43", 0x100000, 0x7b349e5d, BRF_GRA }, { "4.u45", 0x020000, 0xbe4d487d, BRF_GRA }, { "u59.ghb", 0x080000, 0x158c9cde, BRF_GRA }, // gfx4 { "ghd.u60", 0x080000, 0x73180ae3, BRF_GRA }, { "5.u92", 0x020000, 0x97d67510, BRF_ESS | BRF_PRG }, // Sound CPU { "u105.gh8", 0x080000, 0x7a68cb1b, BRF_SND }, // samples { "u104", 0x100000, 0x5795e884, BRF_SND }, }; STD_ROM_PICK(karatblz); STD_ROM_FN(karatblz); static struct BurnRomInfo karatbluRomDesc[] = { { "2.u14", 0x040000, 0x202e6220, BRF_ESS | BRF_PRG }, // 68000 code swapped { "1.u15", 0x040000, 0xd16ee21b, BRF_ESS | BRF_PRG }, { "gha.u55", 0x080000, 0x3e0cea91, BRF_GRA }, // gfx1 { "gh9.u61", 0x080000, 0x5d1676bd, BRF_GRA }, // gfx2 { "u42", 0x100000, 0x65f0da84, BRF_GRA }, // gfx3 { "3.u44", 0x020000, 0x34bdead2, BRF_GRA }, { "u43", 0x100000, 0x7b349e5d, BRF_GRA }, { "4.u45", 0x020000, 0xbe4d487d, BRF_GRA }, { "u59.ghb", 0x080000, 0x158c9cde, BRF_GRA }, // gfx4 { "ghd.u60", 0x080000, 0x73180ae3, BRF_GRA }, { "5.u92", 0x020000, 0x97d67510, BRF_ESS | BRF_PRG }, // Sound CPU { "u105.gh8", 0x080000, 0x7a68cb1b, BRF_SND }, // samples { "u104", 0x100000, 0x5795e884, BRF_SND }, }; STD_ROM_PICK(karatblu); STD_ROM_FN(karatblu); static struct BurnRomInfo karatbljRomDesc[] = { { "2tecmo.u14", 0x040000, 0x57e52654, BRF_ESS | BRF_PRG }, // 68000 code swapped { "1.u15", 0x040000, 0xd16ee21b, BRF_ESS | BRF_PRG }, { "gha.u55", 0x080000, 0x3e0cea91, BRF_GRA }, // gfx1 { "gh9.u61", 0x080000, 0x5d1676bd, BRF_GRA }, // gfx2 { "u42", 0x100000, 0x65f0da84, BRF_GRA }, // gfx3 { "3.u44", 0x020000, 0x34bdead2, BRF_GRA }, { "u43", 0x100000, 0x7b349e5d, BRF_GRA }, { "4.u45", 0x020000, 0xbe4d487d, BRF_GRA }, { "u59.ghb", 0x080000, 0x158c9cde, BRF_GRA }, // gfx4 { "ghd.u60", 0x080000, 0x73180ae3, BRF_GRA }, { "5.u92", 0x020000, 0x97d67510, BRF_ESS | BRF_PRG }, // Sound CPU { "u105.gh8", 0x080000, 0x7a68cb1b, BRF_SND }, // samples { "u104", 0x100000, 0x5795e884, BRF_SND }, }; STD_ROM_PICK(karatblj); STD_ROM_FN(karatblj); unsigned char __fastcall karatblzReadByte(unsigned int sekAddress) { sekAddress &= 0x0FFFFF; switch (sekAddress) { case 0x0FF000: return ~DrvInput[4]; case 0x0FF001: return ~DrvInput[0]; case 0x0FF002: return 0xFF; case 0x0FF003: return ~DrvInput[1]; case 0x0FF004: return ~DrvInput[5]; case 0x0FF005: return ~DrvInput[2]; case 0x0FF006: return 0xFF; case 0x0FF007: return ~DrvInput[3]; case 0x0FF008: return ~DrvInput[7]; case 0x0FF009: return ~DrvInput[6]; case 0x0FF00B: return pending_command; // default: // printf("Attempt to read byte value of location %x\n", sekAddress); } return 0; } /* unsigned short __fastcall karatblzReadWord(unsigned int sekAddress) { sekAddress &= 0x0FFFFF; switch (sekAddress) { default: printf("Attempt to read word value of location %x\n", sekAddress); } return 0; } */ void __fastcall karatblzWriteByte(unsigned int sekAddress, unsigned char byteValue) { sekAddress &= 0x0FFFFF; switch (sekAddress) { case 0x0FF000: case 0x0FF401: case 0x0FF403: break; case 0x0FF002: //if (ACCESSING_MSB) { // setbank(bg1_tilemap,0,(data & 0x0100) >> 8); // setbank(bg2_tilemap,1,(data & 0x0800) >> 11); //} RamGfxBank[0] = (byteValue & 0x1); RamGfxBank[1] = (byteValue & 0x8) >> 3; break; case 0x0FF007: pending_command = 1; SoundCommand(byteValue); break; // default: // printf("Attempt to write byte value %x to location %x\n", byteValue, sekAddress); } } void __fastcall karatblzWriteWord(unsigned int sekAddress, unsigned short wordValue) { if (( sekAddress & 0x0FF000 ) == 0x0FE000) { sekAddress &= 0x07FF; *((unsigned short *)&RamPal[sekAddress]) = wordValue; RamCurPal[sekAddress>>1] = CalcCol( wordValue ); return; } sekAddress &= 0x0FFFFF; switch (sekAddress) { case 0x0ff008: bg1scrollx = wordValue; break; case 0x0ff00A: bg1scrolly = wordValue; break; case 0x0ff00C: bg2scrollx = wordValue; break; case 0x0ff00E: bg2scrolly = wordValue; break; // default: // printf("Attempt to write word value %x to location %x\n", wordValue, sekAddress); } } static int karatblzMemIndex() { unsigned char *Next; Next = Mem; Rom01 = Next; Next += 0x080000; // 68000 ROM RomZ80 = Next; Next += 0x030000; // Z80 ROM RomBg = Next; Next += 0x200040; // Background, 1M 8x8x4bit decode to 2M + 64Byte safe DeRomBg = RomBg + 0x000040; RomSpr1 = Next; Next += 0x800000; // Sprite 1 , 1M 16x16x4bit decode to 2M + 256Byte safe RomSpr2 = Next; Next += 0x200100; // Sprite 2 DeRomSpr1 = RomSpr1 + 0x000100; DeRomSpr2 = RomSpr2 += 0x000100; RomSnd1 = Next; Next += 0x080000; // ADPCM data RomSndSize1 = 0x080000; RomSnd2 = Next; Next += 0x100000; // ADPCM data RomSndSize2 = 0x100000; RamStart = Next; RamBg1V = (unsigned short *)Next; Next += 0x002000; // BG1 Video Ram RamBg2V = (unsigned short *)Next; Next += 0x002000; // BG2 Video Ram RamSpr1 = (unsigned short *)Next; Next += 0x010000; // Sprite 1 Ram RamSpr2 = (unsigned short *)Next; Next += 0x010000; // Sprite 2 Ram RamSpr3 = (unsigned short *)Next; Next += 0x000800; // Sprite 3 Ram Ram01 = Next; Next += 0x014000; // Work Ram 1 + Work Ram 1 RamPal = Next; Next += 0x000800; // 1024 of X1R5G5B5 Palette RamZ80 = Next; Next += 0x000800; // Z80 Ram 2K RamSpr1SizeMask = 0x7FFF; RamSpr2SizeMask = 0x7FFF; RomSpr1SizeMask = 0x7FFF; RomSpr2SizeMask = 0x1FFF; RamEnd = Next; RamCurPal = (unsigned short *)Next; Next += 0x000800; MemEnd = Next; return 0; } static int karatblzInit() { Mem = NULL; karatblzMemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); karatblzMemIndex(); // Load 68000 ROM if (BurnLoadRom(Rom01+0x00000, 0, 1)) return 1; if (BurnLoadRom(Rom01+0x40000, 1, 1)) return 1; // Load Graphic BurnLoadRom(RomBg+0x00000, 2, 1); BurnLoadRom(RomBg+0x80000, 3, 1); pspikesDecodeBg(0x10000); BurnLoadRom(RomSpr1+0x000000, 4, 2); BurnLoadRom(RomSpr1+0x000001, 6, 2); BurnLoadRom(RomSpr1+0x200000, 5, 2); BurnLoadRom(RomSpr1+0x200001, 7, 2); BurnLoadRom(RomSpr1+0x400000, 8, 2); BurnLoadRom(RomSpr1+0x400001, 9, 2); pspikesDecodeSpr(DeRomSpr1, RomSpr1, 0xA000); // Load Z80 ROM if (BurnLoadRom(RomZ80+0x10000, 10, 1)) return 1; memcpy(RomZ80, RomZ80+0x10000, 0x10000); BurnLoadRom(RomSnd1, 11, 1); BurnLoadRom(RomSnd2, 12, 1); { SekInit(0, 0x68000); // Allocate 68000 SekOpen(0); // Map 68000 memory: SekMapMemory(Rom01, 0x000000, 0x07FFFF, SM_ROM); // CPU 0 ROM SekMapMemory((unsigned char *)RamBg1V, 0x080000, 0x081FFF, SM_RAM); SekMapMemory((unsigned char *)RamBg2V, 0x082000, 0x083FFF, SM_RAM); SekMapMemory((unsigned char *)RamSpr1, 0x0A0000, 0x0AFFFF, SM_RAM); SekMapMemory((unsigned char *)RamSpr2, 0x0B0000, 0x0BFFFF, SM_RAM); SekMapMemory(Ram01, 0x0C0000, 0x0CFFFF, SM_RAM); // 64K Work RAM SekMapMemory(Ram01+0x10000, 0x0F8000, 0x0FBFFF, SM_RAM); // Work RAM SekMapMemory(Ram01+0x10000, 0xFF8000, 0xFFBFFF, SM_RAM); // Work RAM SekMapMemory((unsigned char *)RamSpr3, 0x0FC000, 0x0FC7FF, SM_RAM); SekMapMemory(RamPal, 0x0FE000, 0x0FE7FF, SM_ROM); // Palette // SekSetReadWordHandler(0, karatblzReadWord); SekSetReadByteHandler(0, karatblzReadByte); SekSetWriteWordHandler(0, karatblzWriteWord); SekSetWriteByteHandler(0, karatblzWriteByte); SekClose(); } { ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x77FF, 0, RomZ80); ZetMapArea(0x0000, 0x77FF, 2, RomZ80); ZetMapArea(0x7800, 0x7FFF, 0, RamZ80); ZetMapArea(0x7800, 0x7FFF, 1, RamZ80); ZetMapArea(0x7800, 0x7FFF, 2, RamZ80); ZetMemEnd(); ZetSetInHandler(turbofrcZ80PortRead); ZetSetOutHandler(turbofrcZ80PortWrite); ZetClose(); } BurnYM2610Init(8000000, RomSnd2, &RomSndSize2, RomSnd1, &RomSndSize1, &aerofgtFMIRQHandler, aerofgtSynchroniseStream, aerofgtGetTime, 0); BurnTimerAttachZet(4000000); DrvDoReset(); return 0; } static void karatblzTileBackground_1(unsigned short *bg, unsigned char *BgGfx, unsigned short *pal) { int offs, mx, my, x, y; mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - (((signed short)bg1scrollx + 8)& 0x1FF); if (x <= (352-512)) x += 512; y = my * 8 - (bg1scrolly & 0x1FF); if (y <= (240-512)) y += 512; if ( x<=-8 || x>=352 || y<=-8 || y>= 240 ) continue; else if ( x >=0 && x < (352-8) && y >= 0 && y < (240-8)) { unsigned char *d = BgGfx + ( (bg[offs] & 0x1FFF) + ( RamGfxBank[0] << 13 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { p[0] = pal[ d[0] | c ]; p[1] = pal[ d[1] | c ]; p[2] = pal[ d[2] | c ]; p[3] = pal[ d[3] | c ]; p[4] = pal[ d[4] | c ]; p[5] = pal[ d[5] | c ]; p[6] = pal[ d[6] | c ]; p[7] = pal[ d[7] | c ]; d += 8; p += 352; } } else { unsigned char *d = BgGfx + ( (bg[offs] & 0x1FFF) + ( RamGfxBank[0] << 13 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<240 ) { if ((x + 0) >= 0 && (x + 0)<352) p[0] = pal[ d[0] | c ]; if ((x + 1) >= 0 && (x + 1)<352) p[1] = pal[ d[1] | c ]; if ((x + 2) >= 0 && (x + 2)<352) p[2] = pal[ d[2] | c ]; if ((x + 3) >= 0 && (x + 3)<352) p[3] = pal[ d[3] | c ]; if ((x + 4) >= 0 && (x + 4)<352) p[4] = pal[ d[4] | c ]; if ((x + 5) >= 0 && (x + 5)<352) p[5] = pal[ d[5] | c ]; if ((x + 6) >= 0 && (x + 6)<352) p[6] = pal[ d[6] | c ]; if ((x + 7) >= 0 && (x + 7)<352) p[7] = pal[ d[7] | c ]; } d += 8; p += 352; } } } } static void karatblzTileBackground_2(unsigned short *bg, unsigned char *BgGfx, unsigned short *pal) { int offs, mx, my, x, y; mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - ( ((signed short)bg2scrollx + 4) & 0x1FF); if (x <= (352-512)) x += 512; y = my * 8 - (bg2scrolly & 0x1FF); if (y <= (240-512)) y += 512; if ( x<=-8 || x>=352 || y<=-8 || y>= 240 ) continue; else if ( x >=0 && x < (352-8) && y >= 0 && y < (240-8)) { unsigned char *d = BgGfx + ( (bg[offs] & 0x1FFF) + ( RamGfxBank[1] << 13 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { if (d[0] != 15) p[0] = pal[ d[0] | c ]; if (d[1] != 15) p[1] = pal[ d[1] | c ]; if (d[2] != 15) p[2] = pal[ d[2] | c ]; if (d[3] != 15) p[3] = pal[ d[3] | c ]; if (d[4] != 15) p[4] = pal[ d[4] | c ]; if (d[5] != 15) p[5] = pal[ d[5] | c ]; if (d[6] != 15) p[6] = pal[ d[6] | c ]; if (d[7] != 15) p[7] = pal[ d[7] | c ]; d += 8; p += 352; } } else { unsigned char *d = BgGfx + ( (bg[offs] & 0x1FFF) + ( RamGfxBank[1] << 13 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<240 ) { if (d[0] != 15 && (x + 0) >= 0 && (x + 0)<352) p[0] = pal[ d[0] | c ]; if (d[1] != 15 && (x + 1) >= 0 && (x + 1)<352) p[1] = pal[ d[1] | c ]; if (d[2] != 15 && (x + 2) >= 0 && (x + 2)<352) p[2] = pal[ d[2] | c ]; if (d[3] != 15 && (x + 3) >= 0 && (x + 3)<352) p[3] = pal[ d[3] | c ]; if (d[4] != 15 && (x + 4) >= 0 && (x + 4)<352) p[4] = pal[ d[4] | c ]; if (d[5] != 15 && (x + 5) >= 0 && (x + 5)<352) p[5] = pal[ d[5] | c ]; if (d[6] != 15 && (x + 6) >= 0 && (x + 6)<352) p[6] = pal[ d[6] | c ]; if (d[7] != 15 && (x + 7) >= 0 && (x + 7)<352) p[7] = pal[ d[7] | c ]; } d += 8; p += 352; } } } } static int karatblzDraw() { karatblzTileBackground_1(RamBg1V, DeRomBg, RamCurPal); karatblzTileBackground_2(RamBg2V, DeRomBg + 0x100000, RamCurPal + 256); /* turbofrc_drawsprites(1,-1); turbofrc_drawsprites(1, 0); turbofrc_drawsprites(0,-1); turbofrc_drawsprites(0, 0); */ turbofrc_drawsprites(0, 0); turbofrc_drawsprites(0,-1); turbofrc_drawsprites(1, 0); turbofrc_drawsprites(1,-1); return 0; } static int karatblzFrame() { if (DrvReset) DrvDoReset(); // Compile digital inputs DrvInput[0] = 0x00; // Joy1 DrvInput[1] = 0x00; // Joy2 DrvInput[2] = 0x00; // Joy3 DrvInput[3] = 0x00; // Joy4 DrvInput[4] = 0x00; // Buttons1 DrvInput[5] = 0x00; // Buttons2 for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvJoy1[i] & 1) << i; DrvInput[1] |= (DrvJoy2[i] & 1) << i; DrvInput[2] |= (DrvJoy3[i] & 1) << i; DrvInput[3] |= (DrvJoy4[i] & 1) << i; } for (int i = 0; i < 4; i++) { DrvInput[4] |= (DrvButton[i] & 1) << i; DrvInput[5] |= (DrvButton[i+4] & 1) << i; } SekNewFrame(); ZetNewFrame(); nCyclesTotal[0] = 10000000 / 60; nCyclesTotal[1] = 4000000 / 60; SekOpen(0); ZetOpen(0); SekRun(nCyclesTotal[0]); SekSetIRQLine(1, SEK_IRQSTATUS_AUTO); BurnTimerEndFrame(nCyclesTotal[1]); BurnYM2610Update(pBurnSoundOut, nBurnSoundLen); ZetClose(); SekClose(); if (pBurnDraw) karatblzDraw(); return 0; } struct BurnDriver BurnDrvKaratblz = { "karatblz", NULL, NULL, "1991", "Karate Blazers (World?)\0", NULL, "Video System Co.", "Video System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_16BIT_ONLY, 4, HARDWARE_MISC_POST90S, NULL, karatblzRomInfo, karatblzRomName, karatblzInputInfo, karatblzDIPInfo, karatblzInit,DrvExit,karatblzFrame,karatblzDraw,DrvScan, 0, NULL, NULL, NULL, NULL,352,240,4,3 }; struct BurnDriver BurnDrvKaratblu = { "karatblu", "karatblz", NULL, "1991", "Karate Blazers (US)\0", NULL, "Video System Co.", "Video System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_16BIT_ONLY, 4, HARDWARE_MISC_POST90S, NULL, karatbluRomInfo, karatbluRomName, karatblzInputInfo, karatblzDIPInfo, karatblzInit,DrvExit,karatblzFrame,karatblzDraw,DrvScan, 0, NULL, NULL, NULL, NULL,352,240,4,3 }; struct BurnDriver BurnDrvKaratblj = { "karatblj", "karatblz", NULL, "1991", "Karate Blazers (Japan)\0", NULL, "Video System Co.", "Video System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_16BIT_ONLY, 4, HARDWARE_MISC_POST90S, NULL, karatbljRomInfo, karatbljRomName, karatblzInputInfo, karatblzDIPInfo, karatblzInit,DrvExit,karatblzFrame,karatblzDraw,DrvScan, 0, NULL, NULL, NULL, NULL,352,240,4,3 }; // ----------------------------------------------------------- static struct BurnInputInfo spinlbrkInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvButton + 0, "p1 coin"}, {"P1 Start", BIT_DIGITAL, DrvButton + 2, "p1 start"}, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up"}, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down"}, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left"}, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right"}, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1"}, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2"}, {"P1 Button 3", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3"}, {"P2 Coin", BIT_DIGITAL, DrvButton + 1, "p2 coin"}, {"P2 Start", BIT_DIGITAL, DrvButton + 3, "p2 start"}, {"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up"}, {"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down"}, {"P2 Left", BIT_DIGITAL, DrvJoy2 + 2, "p2 left"}, {"P2 Right", BIT_DIGITAL, DrvJoy2 + 3, "p2 right"}, {"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1"}, {"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2"}, {"P2 Button 3", BIT_DIGITAL, DrvJoy2 + 6, "p2 fire 3"}, {"Reset", BIT_DIGITAL, &DrvReset, "reset"}, {"Dip A", BIT_DIPSWITCH, DrvInput + 3, "dip"}, {"Dip B", BIT_DIPSWITCH, DrvInput + 4, "dip"}, }; STDINPUTINFO(spinlbrk); static struct BurnDIPInfo spinlbrkDIPList[] = { // Defaults {0x13, 0xFF, 0xFF, 0x00, NULL}, {0x14, 0xFF, 0xFF, 0x00, NULL}, // DIP 1 {0, 0xFE, 0, 16, "Coin A"}, {0x13, 0x01, 0x0F, 0x00, "1-1C 1-2 HPs"}, {0x13, 0x01, 0x0F, 0x01, "1-1-1-1C 1-1-1-2 HPs"}, {0x13, 0x01, 0x0F, 0x02, "1-1-1-1-1C 1-1-1-1-2 HPs"}, {0x13, 0x01, 0x0F, 0x03, "2-2C 1-2 HPs"}, {0x13, 0x01, 0x0F, 0x04, "2-1-1C 1-1-1 HPs"}, {0x13, 0x01, 0x0F, 0x05, "2 Credits 2 Health Packs"}, {0x13, 0x01, 0x0F, 0x06, "5 Credits 1 Health Pack"}, {0x13, 0x01, 0x0F, 0x07, "4 Credits 1 Health Pack"}, {0x13, 0x01, 0x0F, 0x08, "3 Credits 1 Health Pack"}, {0x13, 0x01, 0x0F, 0x09, "2 Credits 1 Health Pack"}, {0x13, 0x01, 0x0F, 0x0A, "1 Credit 6 Health Packs"}, {0x13, 0x01, 0x0F, 0x0B, "1 Credit 5 Health Packs"}, {0x13, 0x01, 0x0F, 0x0C, "1 Credit 4 Health Packs"}, {0x13, 0x01, 0x0F, 0x0D, "1 Credit 3 Health Packs"}, {0x13, 0x01, 0x0F, 0x0E, "1 Credit 2 Health Packs"}, {0x13, 0x01, 0x0F, 0x0F, "1 Credit 1 Health Pack"}, {0, 0xFE, 0, 16, "Coin A"}, {0x13, 0x01, 0xF0, 0x00, "1-1C 1-2 HPs"}, {0x13, 0x01, 0xF0, 0x10, "1-1-1-1C 1-1-1-2 HPs"}, {0x13, 0x01, 0xF0, 0x20, "1-1-1-1-1C 1-1-1-1-2 HPs"}, {0x13, 0x01, 0xF0, 0x30, "2-2C 1-2 HPs"}, {0x13, 0x01, 0xF0, 0x40, "2-1-1C 1-1-1 HPs"}, {0x13, 0x01, 0xF0, 0x50, "2 Credits 2 Health Packs"}, {0x13, 0x01, 0xF0, 0x60, "5 Credits 1 Health Pack"}, {0x13, 0x01, 0xF0, 0x70, "4 Credits 1 Health Pack"}, {0x13, 0x01, 0xF0, 0x80, "3 Credits 1 Health Pack"}, {0x13, 0x01, 0xF0, 0x90, "2 Credits 1 Health Pack"}, {0x13, 0x01, 0xF0, 0xA0, "1 Credit 6 Health Packs"}, {0x13, 0x01, 0xF0, 0xB0, "1 Credit 5 Health Packs"}, {0x13, 0x01, 0xF0, 0xC0, "1 Credit 4 Health Packs"}, {0x13, 0x01, 0xF0, 0xD0, "1 Credit 3 Health Packs"}, {0x13, 0x01, 0xF0, 0xE0, "1 Credit 2 Health Packs"}, {0x13, 0x01, 0xF0, 0xF0, "1 Credit 1 Health Pack"}, // DIP 2 {0, 0xFE, 0, 4, "Difficulty"}, {0x14, 0x01, 0x03, 0x00, "Normal"}, {0x14, 0x01, 0x03, 0x01, "Easy"}, {0x14, 0x01, 0x03, 0x02, "Hard"}, {0x14, 0x01, 0x03, 0x03, "Hardest"}, }; static struct BurnDIPInfo spinlbrk_DIPList[] = { {0, 0xFE, 0, 2, "Coin Slot"}, {0x14, 0x01, 0x04, 0x00, "Individuala"}, {0x14, 0x01, 0x04, 0x04, "Same"}, {0, 0xFE, 0, 2, "Flip Screen"}, {0x14, 0x01, 0x08, 0x00, "Off"}, {0x14, 0x01, 0x08, 0x08, "On"}, {0, 0xFE, 0, 2, "Lever Type"}, {0x14, 0x01, 0x10, 0x00, "Digital"}, {0x14, 0x01, 0x10, 0x10, "Analog"}, {0, 0xFE, 0, 2, "Service"}, {0x14, 0x01, 0x20, 0x00, "Off"}, {0x14, 0x01, 0x20, 0x20, "On"}, {0, 0xFE, 0, 2, "Health Pack"}, {0x14, 0x01, 0x40, 0x00, "32 Hitpoints"}, {0x14, 0x01, 0x40, 0x40, "40 Hitpoints"}, {0, 0xFE, 0, 2, "Life Restoration"}, {0x14, 0x01, 0x80, 0x00, "10 Points"}, {0x14, 0x01, 0x80, 0x80, "5 Points"}, }; STDDIPINFOEXT(spinlbrk, spinlbrk, spinlbrk_); static struct BurnDIPInfo spinlbru_DIPList[] = { {0, 0xFE, 0, 2, "Coin Slot"}, {0x14, 0x01, 0x04, 0x00, "Individuala"}, {0x14, 0x01, 0x04, 0x04, "Same"}, {0, 0xFE, 0, 2, "Flip Screen"}, {0x14, 0x01, 0x08, 0x00, "Off"}, {0x14, 0x01, 0x08, 0x08, "On"}, {0, 0xFE, 0, 2, "Lever Type"}, {0x14, 0x01, 0x10, 0x00, "Digital"}, {0x14, 0x01, 0x10, 0x10, "Analog"}, {0, 0xFE, 0, 2, "Service"}, {0x14, 0x01, 0x20, 0x00, "Off"}, {0x14, 0x01, 0x20, 0x20, "On"}, {0, 0xFE, 0, 2, "Health Pack"}, {0x14, 0x01, 0x40, 0x00, "20 Hitpoints"}, {0x14, 0x01, 0x40, 0x40, "32 Hitpoints"}, {0, 0xFE, 0, 2, "Life Restoration"}, {0x14, 0x01, 0x80, 0x00, "10 Points"}, {0x14, 0x01, 0x80, 0x80, "5 Points"}, }; STDDIPINFOEXT(spinlbru, spinlbrk, spinlbru_); static struct BurnDIPInfo spinlbrj_DIPList[] = { {0, 0xFE, 0, 2, "Continue"}, {0x14, 0x01, 0x04, 0x00, "Unlimited"}, {0x14, 0x01, 0x04, 0x04, "6 Times"}, {0, 0xFE, 0, 2, "Flip Screen"}, {0x14, 0x01, 0x08, 0x00, "Off"}, {0x14, 0x01, 0x08, 0x08, "On"}, {0, 0xFE, 0, 2, "Lever Type"}, {0x14, 0x01, 0x10, 0x00, "Digital"}, {0x14, 0x01, 0x10, 0x10, "Analog"}, {0, 0xFE, 0, 2, "Service"}, {0x14, 0x01, 0x20, 0x00, "Off"}, {0x14, 0x01, 0x20, 0x20, "On"}, {0, 0xFE, 0, 2, "Health Pack"}, {0x14, 0x01, 0x40, 0x00, "32 Hitpoints"}, {0x14, 0x01, 0x40, 0x40, "40 Hitpoints"}, {0, 0xFE, 0, 2, "Life Restoration"}, {0x14, 0x01, 0x80, 0x00, "10 Points"}, {0x14, 0x01, 0x80, 0x80, "5 Points"}, }; STDDIPINFOEXT(spinlbrj, spinlbrk, spinlbrj_); static struct BurnRomInfo spinlbrkRomDesc[] = { { "ic98", 0x010000, 0x36c2bf70, BRF_ESS | BRF_PRG }, // 68000 code swapped { "ic104", 0x010000, 0x34a7e158, BRF_ESS | BRF_PRG }, { "ic93", 0x010000, 0x726f4683, BRF_ESS | BRF_PRG }, { "ic94", 0x010000, 0xc4385e03, BRF_ESS | BRF_PRG }, { "ic15", 0x080000, 0xe318cf3a, BRF_GRA }, // gfx 1 { "ic9", 0x080000, 0xe071f674, BRF_GRA }, { "ic17", 0x080000, 0xa63d5a55, BRF_GRA }, // gfx 2 { "ic11", 0x080000, 0x7dcc913d, BRF_GRA }, { "ic16", 0x080000, 0x0d84af7f, BRF_GRA }, { "ic12", 0x080000, 0xd63fac4e, BRF_GRA }, // gfx 3 { "ic18", 0x080000, 0x5a60444b, BRF_GRA }, { "ic14", 0x080000, 0x1befd0f3, BRF_GRA }, // gfx 4 { "ic20", 0x080000, 0xc2f84a61, BRF_GRA }, { "ic35", 0x080000, 0xeba8e1a3, BRF_GRA }, { "ic40", 0x080000, 0x5ef5aa7e, BRF_GRA }, { "ic19", 0x010000, 0xdb24eeaa, BRF_GRA }, // gfx 5, hardcoded sprite maps { "ic13", 0x010000, 0x97025bf4, BRF_GRA }, { "ic117", 0x008000, 0x625ada41, BRF_ESS | BRF_PRG }, // Sound CPU { "ic118", 0x010000, 0x1025f024, BRF_ESS | BRF_PRG }, { "ic166", 0x080000, 0x6e0d063a, BRF_SND }, // samples { "ic163", 0x080000, 0xe6621dfb, BRF_SND }, { "epl16p8bp.ic100", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic127", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic133", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic99", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "gal16v8a.ic114", 279, 0x00000000, BRF_OPT | BRF_NODUMP }, { "gal16v8a.ic95", 279, 0x00000000, BRF_OPT | BRF_NODUMP }, }; STD_ROM_PICK(spinlbrk); STD_ROM_FN(spinlbrk); static struct BurnRomInfo spinlbruRomDesc[] = { { "ic98.u5", 0x010000, 0x3a0f7667, BRF_ESS | BRF_PRG }, // 68000 code swapped { "ic104.u6", 0x010000, 0xa0e0af31, BRF_ESS | BRF_PRG }, { "ic93.u4", 0x010000, 0x0cf73029, BRF_ESS | BRF_PRG }, { "ic94.u3", 0x010000, 0x5cf7c426, BRF_ESS | BRF_PRG }, { "ic15", 0x080000, 0xe318cf3a, BRF_GRA }, // gfx 1 { "ic9", 0x080000, 0xe071f674, BRF_GRA }, { "ic17", 0x080000, 0xa63d5a55, BRF_GRA }, // gfx 2 { "ic11", 0x080000, 0x7dcc913d, BRF_GRA }, { "ic16", 0x080000, 0x0d84af7f, BRF_GRA }, { "ic12", 0x080000, 0xd63fac4e, BRF_GRA }, // gfx 3 { "ic18", 0x080000, 0x5a60444b, BRF_GRA }, { "ic14", 0x080000, 0x1befd0f3, BRF_GRA }, // gfx 4 { "ic20", 0x080000, 0xc2f84a61, BRF_GRA }, { "ic35", 0x080000, 0xeba8e1a3, BRF_GRA }, { "ic40", 0x080000, 0x5ef5aa7e, BRF_GRA }, { "ic19", 0x010000, 0xdb24eeaa, BRF_GRA }, // gfx 5, hardcoded sprite maps { "ic13", 0x010000, 0x97025bf4, BRF_GRA }, { "ic117", 0x008000, 0x625ada41, BRF_ESS | BRF_PRG }, // Sound CPU { "ic118", 0x010000, 0x1025f024, BRF_ESS | BRF_PRG }, { "ic166", 0x080000, 0x6e0d063a, BRF_SND }, // samples { "ic163", 0x080000, 0xe6621dfb, BRF_SND }, { "epl16p8bp.ic100", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic127", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic133", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic99", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "gal16v8a.ic114", 279, 0x00000000, BRF_OPT | BRF_NODUMP }, { "gal16v8a.ic95", 279, 0x00000000, BRF_OPT | BRF_NODUMP }, }; STD_ROM_PICK(spinlbru); STD_ROM_FN(spinlbru); static struct BurnRomInfo spinlbrjRomDesc[] = { { "j5", 0x010000, 0x6a3d690e, BRF_ESS | BRF_PRG }, // 68000 code swapped { "j6", 0x010000, 0x869593fa, BRF_ESS | BRF_PRG }, { "j4", 0x010000, 0x33e33912, BRF_ESS | BRF_PRG }, { "j3", 0x010000, 0x16ca61d0, BRF_ESS | BRF_PRG }, { "ic15", 0x080000, 0xe318cf3a, BRF_GRA }, // gfx 1 { "ic9", 0x080000, 0xe071f674, BRF_GRA }, { "ic17", 0x080000, 0xa63d5a55, BRF_GRA }, // gfx 2 { "ic11", 0x080000, 0x7dcc913d, BRF_GRA }, { "ic16", 0x080000, 0x0d84af7f, BRF_GRA }, { "ic12", 0x080000, 0xd63fac4e, BRF_GRA }, // gfx 3 { "ic18", 0x080000, 0x5a60444b, BRF_GRA }, { "ic14", 0x080000, 0x1befd0f3, BRF_GRA }, // gfx 4 { "ic20", 0x080000, 0xc2f84a61, BRF_GRA }, { "ic35", 0x080000, 0xeba8e1a3, BRF_GRA }, { "ic40", 0x080000, 0x5ef5aa7e, BRF_GRA }, { "ic19", 0x010000, 0xdb24eeaa, BRF_GRA }, // gfx 5, hardcoded sprite maps { "ic13", 0x010000, 0x97025bf4, BRF_GRA }, { "ic117", 0x008000, 0x625ada41, BRF_ESS | BRF_PRG }, // Sound CPU { "ic118", 0x010000, 0x1025f024, BRF_ESS | BRF_PRG }, { "ic166", 0x080000, 0x6e0d063a, BRF_SND }, // samples { "ic163", 0x080000, 0xe6621dfb, BRF_SND }, { "epl16p8bp.ic100", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic127", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic133", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "epl16p8bp.ic99", 263, 0x00000000, BRF_OPT | BRF_NODUMP }, { "gal16v8a.ic114", 279, 0x00000000, BRF_OPT | BRF_NODUMP }, { "gal16v8a.ic95", 279, 0x00000000, BRF_OPT | BRF_NODUMP }, }; STD_ROM_PICK(spinlbrj); STD_ROM_FN(spinlbrj); /* unsigned char __fastcall spinlbrkReadByte(unsigned int sekAddress) { switch (sekAddress) { default: printf("Attempt to read byte value of location %x\n", sekAddress); } return 0; } */ unsigned short __fastcall spinlbrkReadWord(unsigned int sekAddress) { switch (sekAddress) { case 0xFFF000: return ~(DrvInput[0] | (DrvInput[2] << 8)); case 0xFFF002: return ~(DrvInput[1]); case 0xFFF004: return ~(DrvInput[3] | (DrvInput[4] << 8)); // default: // printf("Attempt to read word value of location %x\n", sekAddress); } return 0; } void __fastcall spinlbrkWriteByte(unsigned int sekAddress, unsigned char byteValue) { switch (sekAddress) { case 0xFFF401: case 0xFFF403: // NOP break; case 0xFFF007: pending_command = 1; SoundCommand(byteValue); break; // default: // printf("Attempt to write byte value %x to location %x\n", byteValue, sekAddress); } } void __fastcall spinlbrkWriteWord(unsigned int sekAddress, unsigned short wordValue) { if (( sekAddress & 0xFFF000 ) == 0xFFE000) { sekAddress &= 0x07FF; *((unsigned short *)&RamPal[sekAddress]) = wordValue; RamCurPal[sekAddress>>1] = CalcCol( wordValue ); return; } switch (sekAddress) { case 0xFFF000: RamGfxBank[0] = (wordValue & 0x07); RamGfxBank[1] = (wordValue & 0x38) >> 3; break; case 0xFFF002: bg2scrollx = wordValue; break; case 0xFFF008: // NOP break; // default: // printf("Attempt to write word value %x to location %x\n", wordValue, sekAddress); } } static int spinlbrkMemIndex() { unsigned char *Next; Next = Mem; Rom01 = Next; Next += 0x040000; // 68000 ROM RomZ80 = Next; Next += 0x030000; // Z80 ROM RomBg = Next; Next += 0x500040; // Background, 2.5M 8x8x4bit DeRomBg = RomBg + 0x000040; RomSpr1 = Next; Next += 0x200000; // Sprite 1 RomSpr2 = Next; Next += 0x400100; // Sprite 2 DeRomSpr1 = RomSpr1 + 0x000100; DeRomSpr2 = RomSpr2 += 0x000100; RomSnd2 = Next; Next += 0x100000; // ADPCM data RomSnd1 = RomSnd2; RomSndSize1 = 0x100000; RomSndSize2 = 0x100000; RamSpr2 = (unsigned short *)Next; Next += 0x020000; // Sprite 2 Ram RamSpr1 = (unsigned short *)Next; Next += 0x004000; // Sprite 1 Ram RamStart = Next; RamBg1V = (unsigned short *)Next; Next += 0x001000; // BG1 Video Ram RamBg2V = (unsigned short *)Next; Next += 0x002000; // BG2 Video Ram Ram01 = Next; Next += 0x004000; // Work Ram RamSpr3 = (unsigned short *)Next; Next += 0x000800; // Sprite 3 Ram RamRaster = (unsigned short *)Next; Next += 0x000200; // Raster RamPal = Next; Next += 0x000800; // 1024 of X1R5G5B5 Palette RamZ80 = Next; Next += 0x000800; // Z80 Ram 2K RamSpr1SizeMask = 0x1FFF; RamSpr2SizeMask = 0xFFFF; RomSpr1SizeMask = 0x1FFF; RomSpr2SizeMask = 0x3FFF; RamEnd = Next; RamCurPal = (unsigned short *)Next; Next += 0x000800; MemEnd = Next; return 0; } static int spinlbrkInit() { Mem = NULL; spinlbrkMemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); spinlbrkMemIndex(); // Load 68000 ROM if (BurnLoadRom(Rom01+0x00001, 0, 2)) return 1; if (BurnLoadRom(Rom01+0x00000, 1, 2)) return 1; if (BurnLoadRom(Rom01+0x20001, 2, 2)) return 1; if (BurnLoadRom(Rom01+0x20000, 3, 2)) return 1; // Load Graphic BurnLoadRom(RomBg+0x000000, 4, 1); BurnLoadRom(RomBg+0x080000, 5, 1); BurnLoadRom(RomBg+0x100000, 6, 1); BurnLoadRom(RomBg+0x180000, 7, 1); BurnLoadRom(RomBg+0x200000, 8, 1); pspikesDecodeBg(0x14000); BurnLoadRom(RomSpr1+0x000000, 9, 2); BurnLoadRom(RomSpr1+0x000001, 10, 2); BurnLoadRom(RomSpr1+0x100000, 11, 2); BurnLoadRom(RomSpr1+0x100001, 13, 2); BurnLoadRom(RomSpr1+0x200000, 12, 2); BurnLoadRom(RomSpr1+0x200001, 14, 2); pspikesDecodeSpr(DeRomSpr1, RomSpr1, 0x6000); BurnLoadRom((unsigned char *)RamSpr2+0x000001, 15, 2); BurnLoadRom((unsigned char *)RamSpr2+0x000000, 16, 2); // Load Z80 ROM if (BurnLoadRom(RomZ80+0x00000, 17, 1)) return 1; if (BurnLoadRom(RomZ80+0x08000, 18, 1)) return 1; BurnLoadRom(RomSnd2+0x00000, 19, 1); BurnLoadRom(RomSnd2+0x80000, 20, 1); { SekInit(0, 0x68000); // Allocate 68000 SekOpen(0); // Map 68000 memory: SekMapMemory(Rom01, 0x000000, 0x04FFFF, SM_ROM); // CPU 0 ROM SekMapMemory((unsigned char *)RamBg1V, 0x080000, 0x080FFF, SM_RAM); SekMapMemory((unsigned char *)RamBg2V, 0x082000, 0x083FFF, SM_RAM); SekMapMemory(Ram01, 0xFF8000, 0xFFBFFF, SM_RAM); // Work RAM SekMapMemory((unsigned char *)RamSpr3, 0xFFC000, 0xFFC7FF, SM_RAM); SekMapMemory((unsigned char *)RamRaster, 0xFFD000, 0xFFD1FF, SM_RAM); SekMapMemory(RamPal, 0xFFE000, 0xFFE7FF, SM_ROM); // Palette SekSetReadWordHandler(0, spinlbrkReadWord); // SekSetReadByteHandler(0, spinlbrkReadByte); SekSetWriteWordHandler(0, spinlbrkWriteWord); SekSetWriteByteHandler(0, spinlbrkWriteByte); SekClose(); } { ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x77FF, 0, RomZ80); ZetMapArea(0x0000, 0x77FF, 2, RomZ80); ZetMapArea(0x7800, 0x7FFF, 0, RamZ80); ZetMapArea(0x7800, 0x7FFF, 1, RamZ80); ZetMapArea(0x7800, 0x7FFF, 2, RamZ80); ZetMemEnd(); ZetSetInHandler(turbofrcZ80PortRead); ZetSetOutHandler(turbofrcZ80PortWrite); ZetClose(); } BurnYM2610Init(8000000, RomSnd2, &RomSndSize2, RomSnd1, &RomSndSize1, &aerofgtFMIRQHandler, aerofgtSynchroniseStream, aerofgtGetTime, 0); BurnTimerAttachZet(4000000); bg2scrollx = 0; // for (unsigned short i=0; i<0x2000;i++) RamSpr1[i] = i; DrvDoReset(); return 0; } static void spinlbrkTileBackground_1(unsigned short *bg, unsigned char *BgGfx, unsigned short *pal) { int offs, mx, my, x, y; mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - (RamRaster[my*8] & 0x1FF); // + 8 if (x <= (352-512)) x += 512; y = my * 8; if ( x<=-8 || x>=352 || y<=-8 || y>= 240 ) continue; else if ( x >=0 && x < (352-8) && y >= 0 && y < (240-8)) { unsigned char *d = BgGfx + ( (bg[offs] & 0x0FFF) + ( RamGfxBank[0] << 12 ) ) * 64; unsigned short c = (bg[offs] & 0xF000) >> 8; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { p[0] = pal[ d[0] | c ]; p[1] = pal[ d[1] | c ]; p[2] = pal[ d[2] | c ]; p[3] = pal[ d[3] | c ]; p[4] = pal[ d[4] | c ]; p[5] = pal[ d[5] | c ]; p[6] = pal[ d[6] | c ]; p[7] = pal[ d[7] | c ]; d += 8; p += 352; } } else { unsigned char *d = BgGfx + ( (bg[offs] & 0x0FFF) + ( RamGfxBank[0] << 12 ) ) * 64; unsigned short c = (bg[offs] & 0xF000) >> 8; unsigned short * p = (unsigned short *) pBurnDraw + y * 352 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<240 ) { if ((x + 0) >= 0 && (x + 0)<352) p[0] = pal[ d[0] | c ]; if ((x + 1) >= 0 && (x + 1)<352) p[1] = pal[ d[1] | c ]; if ((x + 2) >= 0 && (x + 2)<352) p[2] = pal[ d[2] | c ]; if ((x + 3) >= 0 && (x + 3)<352) p[3] = pal[ d[3] | c ]; if ((x + 4) >= 0 && (x + 4)<352) p[4] = pal[ d[4] | c ]; if ((x + 5) >= 0 && (x + 5)<352) p[5] = pal[ d[5] | c ]; if ((x + 6) >= 0 && (x + 6)<352) p[6] = pal[ d[6] | c ]; if ((x + 7) >= 0 && (x + 7)<352) p[7] = pal[ d[7] | c ]; } d += 8; p += 352; } } } } static int spinlbrkDraw() { spinlbrkTileBackground_1(RamBg1V, DeRomBg, RamCurPal); karatblzTileBackground_2(RamBg2V, DeRomBg + 0x200000, RamCurPal + 256); turbofrc_drawsprites(1,-1); // enemy(near far) turbofrc_drawsprites(1, 0); // enemy(near) fense turbofrc_drawsprites(0, 0); // avatar , post , bullet turbofrc_drawsprites(0,-1); /* unsigned short *ps = RamCurPal; unsigned short *pd = (unsigned short *)pBurnDraw; for (int j=0;j<32;j++) { for (int i=0;i<32;i++) { *pd = *ps; pd ++; ps ++; } pd += 352 - 32; } */ return 0; } static int spinlbrkFrame() { if (DrvReset) DrvDoReset(); // Compile digital inputs DrvInput[0] = 0x00; // Joy1 DrvInput[1] = 0x00; // Joy2 DrvInput[2] = 0x00; // Buttons for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvJoy1[i] & 1) << i; DrvInput[1] |= (DrvJoy2[i] & 1) << i; DrvInput[2] |= (DrvButton[i] & 1) << i; } SekNewFrame(); ZetNewFrame(); nCyclesTotal[0] = 10000000 / 60; nCyclesTotal[1] = 4000000 / 60; SekOpen(0); ZetOpen(0); SekRun(nCyclesTotal[0]); SekSetIRQLine(1, SEK_IRQSTATUS_AUTO); BurnTimerEndFrame(nCyclesTotal[1]); BurnYM2610Update(pBurnSoundOut, nBurnSoundLen); ZetClose(); SekClose(); if (pBurnDraw) spinlbrkDraw(); return 0; } struct BurnDriver BurnDrvSpinlbrk = { "spinlbrk", NULL, NULL, "1990", "Spinal Breakers (World)\0", NULL, "V-System Co.", "V-System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_16BIT_ONLY, 2, HARDWARE_MISC_POST90S, NULL, spinlbrkRomInfo, spinlbrkRomName, spinlbrkInputInfo, spinlbrkDIPInfo, spinlbrkInit,DrvExit,spinlbrkFrame,spinlbrkDraw,DrvScan, 0, NULL, NULL, NULL, NULL,352,240,4,3 }; struct BurnDriver BurnDrvSpinlbru = { "spinlbru", "spinlbrk", NULL, "1990", "Spinal Breakers (US)\0", NULL, "V-System Co.", "V-System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_16BIT_ONLY, 2, HARDWARE_MISC_POST90S, NULL, spinlbruRomInfo, spinlbruRomName, spinlbrkInputInfo, spinlbruDIPInfo, spinlbrkInit,DrvExit,spinlbrkFrame,spinlbrkDraw,DrvScan, 0, NULL, NULL, NULL, NULL,352,240,4,3 }; struct BurnDriver BurnDrvSpinlbrj = { "spinlbrj", "spinlbrk", NULL, "1990", "Spinal Breakers (Japan)\0", NULL, "V-System Co.", "V-System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_16BIT_ONLY, 2, HARDWARE_MISC_POST90S, NULL, spinlbrjRomInfo, spinlbrjRomName, spinlbrkInputInfo, spinlbrjDIPInfo, spinlbrkInit,DrvExit,spinlbrkFrame,spinlbrkDraw,DrvScan, 0, NULL, NULL, NULL, NULL,352,240,4,3 }; // ------------------------------------------------------- static struct BurnDIPInfo aerofgtb_DIPList[] = { {0x14, 0xFF, 0xFF, 0x01, NULL}, // DIP 3 {0, 0xFE, 0, 2, "Region"}, {0x14, 0x01, 0x01, 0x00, "Taiwan"}, {0x14, 0x01, 0x01, 0x01, "Japan"}, }; STDDIPINFOEXT(aerofgtb, aerofgt, aerofgtb_); static struct BurnRomInfo aerofgtbRomDesc[] = { { "v2", 0x040000, 0x5c9de9f0, BRF_ESS | BRF_PRG }, // 68000 code swapped { "v1", 0x040000, 0x89c1dcf4, BRF_ESS | BRF_PRG }, // 68000 code swapped { "it-19-03", 0x080000, 0x85eba1a4, BRF_GRA }, // graphics { "it-19-02", 0x080000, 0x4f57f8ba, BRF_GRA }, { "it-19-04", 0x080000, 0x3b329c1f, BRF_GRA }, // { "it-19-05", 0x080000, 0x02b525af, BRF_GRA }, // { "g27", 0x040000, 0x4d89cbc8, BRF_GRA }, { "g26", 0x040000, 0x8072c1d2, BRF_GRA }, { "v3", 0x020000, 0xcbb18cf4, BRF_ESS | BRF_PRG }, // Sound CPU { "it-19-01", 0x040000, 0x6d42723d, BRF_SND }, // samples { "it-19-06", 0x100000, 0xcdbbdb1d, BRF_SND }, }; STD_ROM_PICK(aerofgtb); STD_ROM_FN(aerofgtb); static struct BurnRomInfo aerofgtcRomDesc[] = { { "v2.149", 0x040000, 0xf187aec6, BRF_ESS | BRF_PRG }, // 68000 code swapped { "v1.111", 0x040000, 0x9e684b19, BRF_ESS | BRF_PRG }, // 68000 code swapped { "it-19-03", 0x080000, 0x85eba1a4, BRF_GRA }, // graphics { "it-19-02", 0x080000, 0x4f57f8ba, BRF_GRA }, { "it-19-04", 0x080000, 0x3b329c1f, BRF_GRA }, // { "it-19-05", 0x080000, 0x02b525af, BRF_GRA }, // { "g27", 0x040000, 0x4d89cbc8, BRF_GRA }, { "g26", 0x040000, 0x8072c1d2, BRF_GRA }, { "2.153", 0x020000, 0xa1ef64ec, BRF_ESS | BRF_PRG }, // Sound CPU { "it-19-01", 0x040000, 0x6d42723d, BRF_SND }, // samples { "it-19-06", 0x100000, 0xcdbbdb1d, BRF_SND }, }; STD_ROM_PICK(aerofgtc); STD_ROM_FN(aerofgtc); static struct BurnRomInfo sonicwiRomDesc[] = { { "2.149", 0x040000, 0x3d1b96ba, BRF_ESS | BRF_PRG }, // 68000 code swapped { "1.111", 0x040000, 0xa3d09f94, BRF_ESS | BRF_PRG }, // 68000 code swapped { "it-19-03", 0x080000, 0x85eba1a4, BRF_GRA }, // graphics { "it-19-02", 0x080000, 0x4f57f8ba, BRF_GRA }, { "it-19-04", 0x080000, 0x3b329c1f, BRF_GRA }, // { "it-19-05", 0x080000, 0x02b525af, BRF_GRA }, // { "g27", 0x040000, 0x4d89cbc8, BRF_GRA }, { "g26", 0x040000, 0x8072c1d2, BRF_GRA }, { "2.153", 0x020000, 0xa1ef64ec, BRF_ESS | BRF_PRG }, // Sound CPU { "it-19-01", 0x040000, 0x6d42723d, BRF_SND }, // samples { "it-19-06", 0x100000, 0xcdbbdb1d, BRF_SND }, }; STD_ROM_PICK(sonicwi); STD_ROM_FN(sonicwi); unsigned char __fastcall aerofgtbReadByte(unsigned int sekAddress) { switch (sekAddress) { case 0x0FE000: return ~DrvInput[2]; case 0x0FE001: return ~DrvInput[0]; case 0x0FE002: return 0xFF; case 0x0FE003: return ~DrvInput[1]; case 0x0FE004: return ~DrvInput[4]; case 0x0FE005: return ~DrvInput[3]; case 0x0FE007: return pending_command; case 0x0FE009: return ~DrvInput[5]; default: printf("Attempt to read byte value of location %x\n", sekAddress); } return 0; } unsigned short __fastcall aerofgtbReadWord(unsigned int sekAddress) { switch (sekAddress) { default: printf("Attempt to read word value of location %x\n", sekAddress); } return 0; } void __fastcall aerofgtbWriteByte(unsigned int sekAddress, unsigned char byteValue) { if (( sekAddress & 0x0FF000 ) == 0x0FD000) { sekAddress &= 0x07FF; RamPal[sekAddress^1] = byteValue; // palette byte write at boot self-test only ?! //if (sekAddress & 1) // RamCurPal[sekAddress>>1] = CalcCol( *((unsigned short *)&RamPal[sekAddress & 0xFFE]) ); return; } switch (sekAddress) { case 0x0FE001: case 0x0FE401: case 0x0FE403: // NOP break; case 0x0FE00E: pending_command = 1; SoundCommand(byteValue); break; default: printf("Attempt to write byte value %x to location %x\n", byteValue, sekAddress); } } void __fastcall aerofgtbWriteWord(unsigned int sekAddress, unsigned short wordValue) { if (( sekAddress & 0x0FF000 ) == 0x0FD000) { sekAddress &= 0x07FE; *((unsigned short *)&RamPal[sekAddress]) = wordValue; RamCurPal[sekAddress>>1] = CalcCol( wordValue ); return; } switch (sekAddress) { case 0x0FE002: bg1scrolly = wordValue; break; case 0x0FE004: bg2scrollx = wordValue; break; case 0x0FE006: bg2scrolly = wordValue; break; case 0x0FE008: RamGfxBank[0] = (wordValue >> 0) & 0x0f; RamGfxBank[1] = (wordValue >> 4) & 0x0f; RamGfxBank[2] = (wordValue >> 8) & 0x0f; RamGfxBank[3] = (wordValue >> 12) & 0x0f; break; case 0x0FE00A: RamGfxBank[4] = (wordValue >> 0) & 0x0f; RamGfxBank[5] = (wordValue >> 4) & 0x0f; RamGfxBank[6] = (wordValue >> 8) & 0x0f; RamGfxBank[7] = (wordValue >> 12) & 0x0f; break; case 0x0FE00C: // NOP break; default: printf("Attempt to write word value %x to location %x\n", wordValue, sekAddress); } } static int aerofgtbMemIndex() { unsigned char *Next; Next = Mem; Rom01 = Next; Next += 0x080000; // 68000 ROM RomZ80 = Next; Next += 0x030000; // Z80 ROM RomBg = Next; Next += 0x200040; // Background, 1M 8x8x4bit decode to 2M + 64Byte safe DeRomBg = RomBg + 0x000040; RomSpr1 = Next; Next += 0x200000; // Sprite 1 , 1M 16x16x4bit decode to 2M + 256Byte safe RomSpr2 = Next; Next += 0x100100; // Sprite 2 DeRomSpr1 = RomSpr1 + 0x000100; DeRomSpr2 = RomSpr2 += 0x000100; RomSnd1 = Next; Next += 0x040000; // ADPCM data RomSndSize1 = 0x040000; RomSnd2 = Next; Next += 0x100000; // ADPCM data RomSndSize2 = 0x100000; RamStart = Next; Ram01 = Next; Next += 0x014000; // Work Ram RamBg1V = (unsigned short *)Next; Next += 0x002000; // BG1 Video Ram RamBg2V = (unsigned short *)Next; Next += 0x002000; // BG2 Video Ram RamSpr1 = (unsigned short *)Next; Next += 0x004000; // Sprite 1 Ram RamSpr2 = (unsigned short *)Next; Next += 0x004000; // Sprite 2 Ram RamSpr3 = (unsigned short *)Next; Next += 0x000800; // Sprite 3 Ram RamPal = Next; Next += 0x000800; // 1024 of X1R5G5B5 Palette RamRaster = (unsigned short *)Next; Next += 0x001000; // Raster RamSpr1SizeMask = 0x1FFF; RamSpr2SizeMask = 0x1FFF; RomSpr1SizeMask = 0x1FFF; RomSpr2SizeMask = 0x0FFF; RamZ80 = Next; Next += 0x000800; // Z80 Ram 2K RamEnd = Next; RamCurPal = (unsigned short *)Next; Next += 0x000800; // 1024 colors MemEnd = Next; return 0; } static void aerofgtbDecodeSpr(unsigned char *d, unsigned char *s, int cnt) { for (int c=cnt-1; c>=0; c--) for (int y=15; y>=0; y--) { d[(c * 256) + (y * 16) + 15] = s[0x00005 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 14] = s[0x00005 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 13] = s[0x00007 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 12] = s[0x00007 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 11] = s[0x00004 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 10] = s[0x00004 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 9] = s[0x00006 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 8] = s[0x00006 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 7] = s[0x00001 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 6] = s[0x00001 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 5] = s[0x00003 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 4] = s[0x00003 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 3] = s[0x00000 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 2] = s[0x00000 + (y * 8) + (c * 128)] & 0x0f; d[(c * 256) + (y * 16) + 1] = s[0x00002 + (y * 8) + (c * 128)] >> 4; d[(c * 256) + (y * 16) + 0] = s[0x00002 + (y * 8) + (c * 128)] & 0x0f; } } static int aerofgtbInit() { Mem = NULL; aerofgtbMemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) { return 1; } memset(Mem, 0, nLen); // blank all memory aerofgtbMemIndex(); // Load the roms into memory // Load 68000 ROM if (BurnLoadRom(Rom01 + 0x00001, 0, 2)) return 1; if (BurnLoadRom(Rom01 + 0x00000, 1, 2)) return 1; // Load Graphic BurnLoadRom(RomBg+0x00000, 2, 1); BurnLoadRom(RomBg+0x80000, 3, 1); pspikesDecodeBg(0x8000); BurnLoadRom(RomSpr1+0x000000, 4, 2); BurnLoadRom(RomSpr1+0x000001, 5, 2); BurnLoadRom(RomSpr1+0x100000, 6, 2); BurnLoadRom(RomSpr1+0x100001, 7, 2); aerofgtbDecodeSpr(DeRomSpr1, RomSpr1, 0x3000); // Load Z80 ROM if (BurnLoadRom(RomZ80+0x10000, 8, 1)) return 1; memcpy(RomZ80, RomZ80+0x10000, 0x10000); BurnLoadRom(RomSnd1, 9, 1); BurnLoadRom(RomSnd2, 10, 1); { SekInit(0, 0x68000); // Allocate 68000 SekOpen(0); // Map 68000 memory: SekMapMemory(Rom01, 0x000000, 0x07FFFF, SM_ROM); // CPU 0 ROM SekMapMemory(Ram01, 0x0C0000, 0x0CFFFF, SM_RAM); // 64K Work RAM SekMapMemory((unsigned char *)RamBg1V, 0x0D0000, 0x0D1FFF, SM_RAM); SekMapMemory((unsigned char *)RamBg2V, 0x0D2000, 0x0D3FFF, SM_RAM); SekMapMemory((unsigned char *)RamSpr1, 0x0E0000, 0x0E3FFF, SM_RAM); SekMapMemory((unsigned char *)RamSpr2, 0x0E4000, 0x0E7FFF, SM_RAM); SekMapMemory(Ram01+0x10000, 0x0F8000, 0x0FBFFF, SM_RAM); // Work RAM SekMapMemory((unsigned char *)RamSpr3, 0x0FC000, 0x0FC7FF, SM_RAM); SekMapMemory(RamPal, 0x0FD000, 0x0FD7FF, SM_ROM); // Palette SekMapMemory((unsigned char *)RamRaster, 0x0FF000, 0x0FFFFF, SM_RAM); // Raster SekSetReadWordHandler(0, aerofgtbReadWord); SekSetReadByteHandler(0, aerofgtbReadByte); SekSetWriteWordHandler(0, aerofgtbWriteWord); SekSetWriteByteHandler(0, aerofgtbWriteByte); SekClose(); } { ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x77FF, 0, RomZ80); ZetMapArea(0x0000, 0x77FF, 2, RomZ80); ZetMapArea(0x7800, 0x7FFF, 0, RamZ80); ZetMapArea(0x7800, 0x7FFF, 1, RamZ80); ZetMapArea(0x7800, 0x7FFF, 2, RamZ80); ZetMemEnd(); //ZetSetReadHandler(aerofgtZ80Read); //ZetSetWriteHandler(aerofgtZ80Write); ZetSetInHandler(aerofgtZ80PortRead); ZetSetOutHandler(aerofgtZ80PortWrite); ZetClose(); } BurnYM2610Init(8000000, RomSnd2, &RomSndSize2, RomSnd1, &RomSndSize1, &aerofgtFMIRQHandler, aerofgtSynchroniseStream, aerofgtGetTime, 0); BurnTimerAttachZet(4000000); DrvDoReset(); // Reset machine return 0; } static void aerofgtbTileBackground_1(unsigned short *bg, unsigned char *BgGfx, unsigned short *pal) { int offs, mx, my, x, y; mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - (RamRaster[7] & 0x1FF); if (x <= (320-512)) x += 512; y = my * 8 - (((signed short)bg1scrolly + 2) & 0x1FF); if (y <= (224-512)) y += 512; if ( x<=-8 || x>=320 || y<=-8 || y>= 224 ) continue; else if ( x >=0 && x < (320-8) && y >= 0 && y < (224-8)) { unsigned char *d = BgGfx + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11)] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; for (int k=0;k<8;k++) { p[0] = pal[ d[0] | c ]; p[1] = pal[ d[1] | c ]; p[2] = pal[ d[2] | c ]; p[3] = pal[ d[3] | c ]; p[4] = pal[ d[4] | c ]; p[5] = pal[ d[5] | c ]; p[6] = pal[ d[6] | c ]; p[7] = pal[ d[7] | c ]; d += 8; p += 320; } } else { unsigned char *d = BgGfx + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11)] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<224 ) { if ((x + 0) >= 0 && (x + 0)<320) p[0] = pal[ d[0] | c ]; if ((x + 1) >= 0 && (x + 1)<320) p[1] = pal[ d[1] | c ]; if ((x + 2) >= 0 && (x + 2)<320) p[2] = pal[ d[2] | c ]; if ((x + 3) >= 0 && (x + 3)<320) p[3] = pal[ d[3] | c ]; if ((x + 4) >= 0 && (x + 4)<320) p[4] = pal[ d[4] | c ]; if ((x + 5) >= 0 && (x + 5)<320) p[5] = pal[ d[5] | c ]; if ((x + 6) >= 0 && (x + 6)<320) p[6] = pal[ d[6] | c ]; if ((x + 7) >= 0 && (x + 7)<320) p[7] = pal[ d[7] | c ]; } d += 8; p += 320; } } } } static void aerofgtbTileBackground_2(unsigned short *bg, unsigned char *BgGfx, unsigned short *pal) { int offs, mx, my, x, y; //printf(" %5d%5d%5d%5d\n", (signed short)RamRaster[7],(signed short)bg1scrolly, (signed short)bg2scrollx,(signed short)bg2scrolly); mx = -1; my = 0; for (offs = 0; offs < 64*64; offs++) { mx++; if (mx == 64) { mx = 0; my++; } x = mx * 8 - (((signed short)bg2scrollx + 5) & 0x1FF); if (x <= (320-512)) x += 512; y = my * 8 - (((signed short)bg2scrolly + 2) & 0x1FF); if (y <= (224-512)) y += 512; if ( x<=-8 || x>=320 || y<=-8 || y>= 224 ) continue; else if ( x >=0 && x < (320-8) && y >= 0 && y < (224-8)) { unsigned char *d = BgGfx + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11) + 4] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; for (int k=0;k<8;k++) { if (d[0] != 15) p[0] = pal[ d[0] | c ]; if (d[1] != 15) p[1] = pal[ d[1] | c ]; if (d[2] != 15) p[2] = pal[ d[2] | c ]; if (d[3] != 15) p[3] = pal[ d[3] | c ]; if (d[4] != 15) p[4] = pal[ d[4] | c ]; if (d[5] != 15) p[5] = pal[ d[5] | c ]; if (d[6] != 15) p[6] = pal[ d[6] | c ]; if (d[7] != 15) p[7] = pal[ d[7] | c ]; d += 8; p += 320; } } else { unsigned char *d = BgGfx + ( (bg[offs] & 0x07FF) + ( RamGfxBank[((bg[offs] & 0x1800) >> 11) + 4] << 11 ) ) * 64; unsigned short c = (bg[offs] & 0xE000) >> 9; unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x; for (int k=0;k<8;k++) { if ( (y+k)>=0 && (y+k)<224 ) { if (d[0] != 15 && (x + 0) >= 0 && (x + 0)<352) p[0] = pal[ d[0] | c ]; if (d[1] != 15 && (x + 1) >= 0 && (x + 1)<352) p[1] = pal[ d[1] | c ]; if (d[2] != 15 && (x + 2) >= 0 && (x + 2)<352) p[2] = pal[ d[2] | c ]; if (d[3] != 15 && (x + 3) >= 0 && (x + 3)<352) p[3] = pal[ d[3] | c ]; if (d[4] != 15 && (x + 4) >= 0 && (x + 4)<352) p[4] = pal[ d[4] | c ]; if (d[5] != 15 && (x + 5) >= 0 && (x + 5)<352) p[5] = pal[ d[5] | c ]; if (d[6] != 15 && (x + 6) >= 0 && (x + 6)<352) p[6] = pal[ d[6] | c ]; if (d[7] != 15 && (x + 7) >= 0 && (x + 7)<352) p[7] = pal[ d[7] | c ]; } d += 8; p += 320; } } } } static void aerofgtb_pdrawgfxzoom(int bank,unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,int scalex,int scaley) { if (!scalex || !scaley) return; unsigned short * p = (unsigned short *) pBurnDraw; unsigned char * q; unsigned short * pal; if (bank) { //if (code > RomSpr2SizeMask) code &= RomSpr2SizeMask; q = DeRomSpr2 + (code) * 256; pal = RamCurPal + 768; } else { //if (code > RomSpr1SizeMask) code &= RomSpr1SizeMask; q = DeRomSpr1 + (code) * 256; pal = RamCurPal + 512; } p += sy * 320 + sx; if (sx < 0 || sx >= (320-16) || sy < 0 || sy >= (224-16) ) { if ((sx <= -16) || (sx >= 320) || (sy <= -16) || (sy >= 224)) return; if (flipy) { p += 320 * 15; if (flipx) { for (int i=15;i>=0;i--) { if (((sy+i)>=0) && ((sy+i)<224)) { if (q[ 0] != 15 && ((sx + 15) >= 0) && ((sx + 15)<320)) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 14) >= 0) && ((sx + 14)<320)) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 13) >= 0) && ((sx + 13)<320)) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 12) >= 0) && ((sx + 12)<320)) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 11) >= 0) && ((sx + 11)<320)) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 10) >= 0) && ((sx + 10)<320)) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 9) >= 0) && ((sx + 9)<320)) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 8) >= 0) && ((sx + 8)<320)) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 7) >= 0) && ((sx + 7)<320)) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 6) >= 0) && ((sx + 6)<320)) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 5) >= 0) && ((sx + 5)<320)) p[ 5] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 4) >= 0) && ((sx + 4)<320)) p[ 4] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 3) >= 0) && ((sx + 3)<320)) p[ 3] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 2) >= 0) && ((sx + 2)<320)) p[ 2] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 1) >= 0) && ((sx + 1)<320)) p[ 1] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 0) >= 0) && ((sx + 0)<320)) p[ 0] = pal[ q[15] | color]; } p -= 320; q += 16; } } else { for (int i=15;i>=0;i--) { if (((sy+i)>=0) && ((sy+i)<224)) { if (q[ 0] != 15 && ((sx + 0) >= 0) && ((sx + 0)<320)) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 1) >= 0) && ((sx + 1)<320)) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 2) >= 0) && ((sx + 2)<320)) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 3) >= 0) && ((sx + 3)<320)) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 4) >= 0) && ((sx + 4)<320)) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 5) >= 0) && ((sx + 5)<320)) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 6) >= 0) && ((sx + 6)<320)) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 7) >= 0) && ((sx + 7)<320)) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 8) >= 0) && ((sx + 8)<320)) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 9) >= 0) && ((sx + 9)<320)) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 10) >= 0) && ((sx + 10)<320)) p[10] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 11) >= 0) && ((sx + 11)<320)) p[11] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 12) >= 0) && ((sx + 12)<320)) p[12] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 13) >= 0) && ((sx + 13)<320)) p[13] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 14) >= 0) && ((sx + 14)<320)) p[14] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 15) >= 0) && ((sx + 15)<320)) p[15] = pal[ q[15] | color]; } p -= 320; q += 16; } } } else { if (flipx) { for (int i=0;i<16;i++) { if (((sy+i)>=0) && ((sy+i)<224)) { if (q[ 0] != 15 && ((sx + 15) >= 0) && ((sx + 15)<320)) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 14) >= 0) && ((sx + 14)<320)) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 13) >= 0) && ((sx + 13)<320)) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 12) >= 0) && ((sx + 12)<320)) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 11) >= 0) && ((sx + 11)<320)) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 10) >= 0) && ((sx + 10)<320)) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 9) >= 0) && ((sx + 9)<320)) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 8) >= 0) && ((sx + 8)<320)) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 7) >= 0) && ((sx + 7)<320)) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 6) >= 0) && ((sx + 6)<320)) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 5) >= 0) && ((sx + 5)<320)) p[ 5] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 4) >= 0) && ((sx + 4)<320)) p[ 4] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 3) >= 0) && ((sx + 3)<320)) p[ 3] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 2) >= 0) && ((sx + 2)<320)) p[ 2] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 1) >= 0) && ((sx + 1)<320)) p[ 1] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 0) >= 0) && ((sx + 0)<320)) p[ 0] = pal[ q[15] | color]; } p += 320; q += 16; } } else { for (int i=0;i<16;i++) { if (((sy+i)>=0) && ((sy+i)<224)) { if (q[ 0] != 15 && ((sx + 0) >= 0) && ((sx + 0)<320)) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15 && ((sx + 1) >= 0) && ((sx + 1)<320)) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15 && ((sx + 2) >= 0) && ((sx + 2)<320)) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15 && ((sx + 3) >= 0) && ((sx + 3)<320)) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15 && ((sx + 4) >= 0) && ((sx + 4)<320)) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15 && ((sx + 5) >= 0) && ((sx + 5)<320)) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15 && ((sx + 6) >= 0) && ((sx + 6)<320)) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15 && ((sx + 7) >= 0) && ((sx + 7)<320)) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15 && ((sx + 8) >= 0) && ((sx + 8)<320)) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15 && ((sx + 9) >= 0) && ((sx + 9)<320)) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15 && ((sx + 10) >= 0) && ((sx + 10)<320)) p[10] = pal[ q[10] | color]; if (q[11] != 15 && ((sx + 11) >= 0) && ((sx + 11)<320)) p[11] = pal[ q[11] | color]; if (q[12] != 15 && ((sx + 12) >= 0) && ((sx + 12)<320)) p[12] = pal[ q[12] | color]; if (q[13] != 15 && ((sx + 13) >= 0) && ((sx + 13)<320)) p[13] = pal[ q[13] | color]; if (q[14] != 15 && ((sx + 14) >= 0) && ((sx + 14)<320)) p[14] = pal[ q[14] | color]; if (q[15] != 15 && ((sx + 15) >= 0) && ((sx + 15)<320)) p[15] = pal[ q[15] | color]; } p += 320; q += 16; } } } return; } if (flipy) { p += 320 * 15; if (flipx) { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15) p[ 5] = pal[ q[10] | color]; if (q[11] != 15) p[ 4] = pal[ q[11] | color]; if (q[12] != 15) p[ 3] = pal[ q[12] | color]; if (q[13] != 15) p[ 2] = pal[ q[13] | color]; if (q[14] != 15) p[ 1] = pal[ q[14] | color]; if (q[15] != 15) p[ 0] = pal[ q[15] | color]; p -= 320; q += 16; } } else { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15) p[10] = pal[ q[10] | color]; if (q[11] != 15) p[11] = pal[ q[11] | color]; if (q[12] != 15) p[12] = pal[ q[12] | color]; if (q[13] != 15) p[13] = pal[ q[13] | color]; if (q[14] != 15) p[14] = pal[ q[14] | color]; if (q[15] != 15) p[15] = pal[ q[15] | color]; p -= 320; q += 16; } } } else { if (flipx) { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[15] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[14] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[13] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[12] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[11] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[10] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 9] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 8] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 7] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 6] = pal[ q[ 9] | color]; if (q[10] != 15) p[ 5] = pal[ q[10] | color]; if (q[11] != 15) p[ 4] = pal[ q[11] | color]; if (q[12] != 15) p[ 3] = pal[ q[12] | color]; if (q[13] != 15) p[ 2] = pal[ q[13] | color]; if (q[14] != 15) p[ 1] = pal[ q[14] | color]; if (q[15] != 15) p[ 0] = pal[ q[15] | color]; p += 320; q += 16; } } else { for (int i=0;i<16;i++) { if (q[ 0] != 15) p[ 0] = pal[ q[ 0] | color]; if (q[ 1] != 15) p[ 1] = pal[ q[ 1] | color]; if (q[ 2] != 15) p[ 2] = pal[ q[ 2] | color]; if (q[ 3] != 15) p[ 3] = pal[ q[ 3] | color]; if (q[ 4] != 15) p[ 4] = pal[ q[ 4] | color]; if (q[ 5] != 15) p[ 5] = pal[ q[ 5] | color]; if (q[ 6] != 15) p[ 6] = pal[ q[ 6] | color]; if (q[ 7] != 15) p[ 7] = pal[ q[ 7] | color]; if (q[ 8] != 15) p[ 8] = pal[ q[ 8] | color]; if (q[ 9] != 15) p[ 9] = pal[ q[ 9] | color]; if (q[10] != 15) p[10] = pal[ q[10] | color]; if (q[11] != 15) p[11] = pal[ q[11] | color]; if (q[12] != 15) p[12] = pal[ q[12] | color]; if (q[13] != 15) p[13] = pal[ q[13] | color]; if (q[14] != 15) p[14] = pal[ q[14] | color]; if (q[15] != 15) p[15] = pal[ q[15] | color]; p += 320; q += 16; } } } } static void aerofgtb_drawsprites(int chip,int chip_disabled_pri) { int attr_start,base,first; base = chip * 0x0200; first = 4 * RamSpr3[0x1fe + base]; //for (attr_start = base + 0x0200-8;attr_start >= first + base;attr_start -= 4) { for (attr_start = first + base; attr_start <= base + 0x0200-8; attr_start += 4) { int map_start; int ox,oy,x,y,xsize,ysize,zoomx,zoomy,flipx,flipy,color,pri; // some other drivers still use this wrong table, they have to be upgraded // int zoomtable[16] = { 0,7,14,20,25,30,34,38,42,46,49,52,54,57,59,61 }; if (!(RamSpr3[attr_start + 2] & 0x0080)) continue; pri = RamSpr3[attr_start + 2] & 0x0010; if ( chip_disabled_pri & !pri) continue; if (!chip_disabled_pri & (pri>>4)) continue; ox = RamSpr3[attr_start + 1] & 0x01ff; xsize = (RamSpr3[attr_start + 2] & 0x0700) >> 8; zoomx = (RamSpr3[attr_start + 1] & 0xf000) >> 12; oy = RamSpr3[attr_start + 0] & 0x01ff; ysize = (RamSpr3[attr_start + 2] & 0x7000) >> 12; zoomy = (RamSpr3[attr_start + 0] & 0xf000) >> 12; flipx = RamSpr3[attr_start + 2] & 0x0800; flipy = RamSpr3[attr_start + 2] & 0x8000; color = (RamSpr3[attr_start + 2] & 0x000f) << 4; // + 16 * spritepalettebank; map_start = RamSpr3[attr_start + 3]; // aerofgt has this adjustment, but doing it here would break turbo force title screen // ox += (xsize*zoomx+2)/4; // oy += (ysize*zoomy+2)/4; zoomx = 32 - zoomx; zoomy = 32 - zoomy; for (y = 0;y <= ysize;y++) { int sx,sy; if (flipy) sy = ((oy + zoomy * (ysize - y)/2 + 16) & 0x1ff) - 16 - 1; else sy = ((oy + zoomy * y / 2 + 16) & 0x1ff) - 16 - 1; for (x = 0;x <= xsize;x++) { int code; if (flipx) sx = ((ox + zoomx * (xsize - x) / 2 + 16) & 0x1ff) - 16 - 8; else sx = ((ox + zoomx * x / 2 + 16) & 0x1ff) - 16 - 8; if (chip == 0) code = RamSpr1[map_start & RamSpr1SizeMask]; else code = RamSpr2[map_start & RamSpr2SizeMask]; aerofgtb_pdrawgfxzoom(chip,code,color,flipx,flipy,sx,sy,zoomx << 11, zoomy << 11); map_start++; } if (xsize == 2) map_start += 1; if (xsize == 4) map_start += 3; if (xsize == 5) map_start += 2; if (xsize == 6) map_start += 1; } } } static int aerofgtbDraw() { aerofgtbTileBackground_1(RamBg1V, DeRomBg, RamCurPal); aerofgtbTileBackground_2(RamBg2V, DeRomBg + 0x100000, RamCurPal + 256); aerofgtb_drawsprites(0, 0); aerofgtb_drawsprites(0,-1); aerofgtb_drawsprites(1, 0); aerofgtb_drawsprites(1,-1); return 0; } static int aerofgtbFrame() { if (DrvReset) DrvDoReset(); // Compile digital inputs DrvInput[0] = 0x00; // Joy1 DrvInput[1] = 0x00; // Joy2 DrvInput[2] = 0x00; // Buttons for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvJoy1[i] & 1) << i; DrvInput[1] |= (DrvJoy2[i] & 1) << i; DrvInput[2] |= (DrvButton[i] & 1) << i; } SekNewFrame(); ZetNewFrame(); nCyclesTotal[0] = 10000000 / 60; nCyclesTotal[1] = 4000000 / 60; SekOpen(0); ZetOpen(0); SekRun(nCyclesTotal[0]); SekSetIRQLine(1, SEK_IRQSTATUS_AUTO); BurnTimerEndFrame(nCyclesTotal[1]); BurnYM2610Update(pBurnSoundOut, nBurnSoundLen); ZetClose(); SekClose(); if (pBurnDraw) aerofgtbDraw(); return 0; } struct BurnDriver BurnDrvAerofgtb = { "aerofgtb", "aerofgt", NULL, "1992", "Aero Fighters (Turbo Force hardware set 1)\0", NULL, "Video System Co.", "Video System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL | BDF_16BIT_ONLY, 2, HARDWARE_MISC_POST90S, NULL, aerofgtbRomInfo, aerofgtbRomName, aerofgtInputInfo, aerofgtDIPInfo, aerofgtbInit,DrvExit,aerofgtbFrame,aerofgtbDraw,DrvScan, 0, NULL, NULL, NULL, NULL, 224,320,3,4 }; struct BurnDriver BurnDrvAerofgtc = { "aerofgtc", "aerofgt", NULL, "1992", "Aero Fighters (Turbo Force hardware set 2)\0", NULL, "Video System Co.", "Video System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL | BDF_16BIT_ONLY, 2, HARDWARE_MISC_POST90S, NULL, aerofgtcRomInfo, aerofgtcRomName, aerofgtInputInfo, aerofgtDIPInfo, aerofgtbInit,DrvExit,aerofgtbFrame,aerofgtbDraw,DrvScan, 0, NULL, NULL, NULL, NULL, 224,320,3,4 }; struct BurnDriver BurnDrvSonicwi = { "sonicwi", "aerofgt", NULL, "1992", "Sonic Wings (Japan)\0", NULL, "Video System Co.", "Video System", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL | BDF_16BIT_ONLY, 2, HARDWARE_MISC_POST90S, NULL, sonicwiRomInfo, sonicwiRomName, aerofgtInputInfo, aerofgtDIPInfo, aerofgtbInit,DrvExit,aerofgtbFrame,aerofgtbDraw,DrvScan, 0, NULL, NULL, NULL, NULL, 224,320,3,4 };
[ "exmortis@yandex.ru" ]
exmortis@yandex.ru
9ee2f5d6e87f87d43d5fe1a1789f86c3815cbca8
6eec58f79b86d3629c874a1a2069a5e6753bfc43
/2018_fall_oop-master/team/dijkstra.cpp
f22621baf16f828e888025f7da612b12427a1aba
[]
no_license
eel0511/2018_OOP
c0d9c07e462f87f9e00b4f124636071a8eb9f200
950b70e0f572657429bac700ec421212e59d214b
refs/heads/master
2020-11-25T16:38:34.479730
2019-12-18T04:40:43
2019-12-18T04:40:43
228,759,172
0
0
null
null
null
null
UTF-8
C++
false
false
2,178
cpp
//suhyung #include <limits> #include <iostream> #include "dijkstra.h" using namespace std; #define MAXV 1000 void dijkstra::init_vars(bool discovered[], int distance[], int parent[]){ for(int i = 1; i < (MAXV + 1); i ++){ discovered[i] = false; distance[i] = std::numeric_limits<int>::max(); parent[i] = -1; } } void dijkstra::dijkstra_shortest_path(Graph *g, int parent[], int distance[], int start){ bool discovered[MAXV + 1]; EdgeNode *curr; int v_curr; int v_neighbor; int weight; int smallest_dist; init_vars(discovered, distance, parent); distance[start] = 0; v_curr = start; while(discovered[v_curr] == false){ discovered[v_curr] = true; curr = g->edges[v_curr]; while(curr != NULL){ v_neighbor = curr->key; weight = curr->weight; if((distance[v_curr] + weight) < distance[v_neighbor]){ distance[v_neighbor] = distance[v_curr] + weight; parent[v_neighbor] = v_curr; } curr = curr->next; } smallest_dist = std::numeric_limits<int>::max(); for(int i = 1; i < (MAXV + 1); i ++){ if(!discovered[i] && (distance[i] < smallest_dist)){ v_curr = i; smallest_dist = distance[i]; } } } } void dijkstra::print_shortest_path(int v, int parent[]){ if(v > 0 && v < (MAXV + 1) && parent[v] != -1){ print_shortest_path(parent[v], parent); cout <<parent[v] <<" -> "; } } void dijkstra::print_distances(int start, int distance[]){ for(int i = 1; i < (MAXV + 1); i ++){ if(distance[i] != std::numeric_limits<int>::max()){ cout << "Shortest distance from " << start << " to " << i << " is: " << distance[i] << endl; } } } void dijkstra::make_and_print(Graph *g,int arrive, int parent[],int start, int distance[]){ dijkstra_shortest_path(g, parent, distance, start); cout<<endl<<"dijkstra Shortest Path is : "; print_shortest_path(arrive,parent); cout<<arrive<<endl<<endl; }
[ "eel0511@gmail.com" ]
eel0511@gmail.com
5da9c97f739e209cd1dc1573251c7f98eff2c426
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Tracking/TrkDetDescr/TrkDetDescrUnitTests/src/components/TrkDetDescrUnitTests_entries.cxx
a2b19454a611165c17d4bbbbf2863d6ccfa2012a
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
908
cxx
#include "GaudiKernel/DeclareFactoryEntries.h" #include "TrkDetDescrUnitTests/TrkDetDescrTPCnvTest.h" #include "TrkDetDescrUnitTests/BinUtilityTest.h" #include "TrkDetDescrUnitTests/TrackingGeometryTest.h" #include "TrkDetDescrUnitTests/SurfaceIntersectionTest.h" #include "TrkDetDescrUnitTests/MappingTest.h" using namespace Trk; DECLARE_ALGORITHM_FACTORY( BinUtilityTest ) DECLARE_ALGORITHM_FACTORY( TrkDetDescrTPCnvTest ) DECLARE_ALGORITHM_FACTORY( TrackingGeometryTest ) DECLARE_ALGORITHM_FACTORY( SurfaceIntersectionTest ) DECLARE_ALGORITHM_FACTORY( MappingTest ) /** factory entries need to have the name of the package */ DECLARE_FACTORY_ENTRIES( TrkDetDescrUnitTests ) { DECLARE_ALGORITHM( BinUtilityTest ) DECLARE_ALGORITHM( TrkDetDescrTPCnvTest ) DECLARE_ALGORITHM( TrackingGeometryTest ) DECLARE_ALGORITHM( SurfaceIntersectionTest ) DECLARE_ALGORITHM( MappingTest ) }
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
f262c7c8bd7fa43e13b74048d5f9f02e6dc1f12f
932a00f0d0d29ec138eac1c2c903fa717c30428d
/src/grains.cpp
8be836b43f1d98d67e253e904f8b6f320e105d17
[]
no_license
sideb0ard/SoundB0ard
8678c17632b2d9446e24b7ae15e9f1f47e1c8476
76350a9eff0054e52216b3dc11d1b5e03d37dbba
refs/heads/main
2023-09-01T14:31:07.016773
2023-09-01T05:53:33
2023-09-01T05:53:33
44,464,395
48
1
null
2023-07-12T04:04:57
2015-10-18T03:34:56
C
UTF-8
C++
false
false
1,665
cpp
#include <grains.h> #include <iostream> namespace { void check_idx(int *index, int buffer_len) { while (*index < 0.0) *index += buffer_len; while (*index >= buffer_len) *index -= buffer_len; } } // namespace namespace SBAudio { void SoundGrainSample::Initialize(SoundGrainParams params) { if (params.grain_type != type) { std::cerr << "Putting DIESEL IN AN UNLEADED!!\n"; return; } grain_len_frames = params.dur_frames; grain_frame_counter = 0; audiobuffer_num_channels = params.num_channels; degrade_by = params.degrade_by; reverse_mode = params.reverse_mode; if (params.reverse_mode) { audiobuffer_cur_pos = params.starting_idx + (params.dur_frames * params.num_channels) - 1; incr = -1.0 * params.pitch; } else { audiobuffer_cur_pos = params.starting_idx; incr = params.pitch; } audio_buffer = params.audio_buffer; active = true; } StereoVal SoundGrainSample::Generate() { StereoVal out = {0., 0.}; if (!active) return out; if (degrade_by > 0) { if (rand() % 100 < degrade_by) return out; } int read_idx = (int)audiobuffer_cur_pos; check_idx(&read_idx, audio_buffer->size()); out.left = (*audio_buffer)[read_idx]; if (audiobuffer_num_channels == 1) { out.right = out.left; } else if (audiobuffer_num_channels == 2) { int read_idx_right = read_idx + 1; check_idx(&read_idx_right, audio_buffer->size()); out.right = (*audio_buffer)[read_idx_right]; } audiobuffer_cur_pos += (incr * audiobuffer_num_channels); grain_frame_counter++; if (grain_frame_counter > grain_len_frames) { active = false; } return out; } } // namespace SBAudio
[ "thorsten.sideb0ard@gmail.com" ]
thorsten.sideb0ard@gmail.com
c58b2de9d71ca7d96a575d5dee0f0027426c1252
bf80344321eb93450a3992083cc2ff48fe3fb263
/test/Parser/cxx-altivec.cpp
a26eee4ef487433082c28aa2a16678e7a2784133
[ "NCSA" ]
permissive
albertz/clang
22faf9d58881234130c39a727de4dabf13834566
292f520b74b449be401d37c8da567d631dbb8b96
refs/heads/master
2021-03-12T19:17:30.831652
2010-02-19T00:31:17
2010-02-19T00:31:17
527,570
1
1
null
null
null
null
UTF-8
C++
false
false
4,603
cpp
// RUN: %clang_cc1 -faltivec -fsyntax-only -verify %s // This is the same as the C version: __vector char vv_c; __vector signed char vv_sc; __vector unsigned char vv_uc; __vector short vv_s; __vector signed short vv_ss; __vector unsigned short vv_us; __vector short int vv_si; __vector signed short int vv_ssi; __vector unsigned short int vv_usi; __vector int vv_i; __vector signed int vv_sint; __vector unsigned int vv_ui; __vector float vv_f; __vector bool vv_b; __vector __pixel vv_p; __vector pixel vv__p; __vector int vf__r(); void vf__a(__vector int a); void vf__a2(int b, __vector int a); vector char v_c; vector signed char v_sc; vector unsigned char v_uc; vector short v_s; vector signed short v_ss; vector unsigned short v_us; vector short int v_si; vector signed short int v_ssi; vector unsigned short int v_usi; vector int v_i; vector signed int v_sint; vector unsigned int v_ui; vector float v_f; vector bool v_b; vector __pixel v_p; vector pixel v__p; vector int f__r(); void f_a(vector int a); void f_a2(int b, vector int a); // These should have warnings. __vector long vv_l; // expected-warning {{Use of "long" with "__vector" is deprecated}} __vector signed long vv_sl; // expected-warning {{Use of "long" with "__vector" is deprecated}} __vector unsigned long vv_ul; // expected-warning {{Use of "long" with "__vector" is deprecated}} __vector long int vv_li; // expected-warning {{Use of "long" with "__vector" is deprecated}} __vector signed long int vv_sli; // expected-warning {{Use of "long" with "__vector" is deprecated}} __vector unsigned long int vv_uli; // expected-warning {{Use of "long" with "__vector" is deprecated}} vector long v_l; // expected-warning {{Use of "long" with "__vector" is deprecated}} vector signed long v_sl; // expected-warning {{Use of "long" with "__vector" is deprecated}} vector unsigned long v_ul; // expected-warning {{Use of "long" with "__vector" is deprecated}} vector long int v_li; // expected-warning {{Use of "long" with "__vector" is deprecated}} vector signed long int v_sli; // expected-warning {{Use of "long" with "__vector" is deprecated}} vector unsigned long int v_uli; // expected-warning {{Use of "long" with "__vector" is deprecated}} __vector long double vv_ld; // expected-warning {{Use of "long" with "__vector" is deprecated}} expected-error {{cannot use "double" with "__vector"}} vector long double v_ld; // expected-warning {{Use of "long" with "__vector" is deprecated}} expected-error {{cannot use "double" with "__vector"}} // These should have errors. __vector double vv_d1; // expected-error {{cannot use "double" with "__vector"}} vector double v_d2; // expected-error {{cannot use "double" with "__vector"}} __vector long double vv_ld3; // expected-warning {{Use of "long" with "__vector" is deprecated}} expected-error {{cannot use "double" with "__vector"}} vector long double v_ld4; // expected-warning {{Use of "long" with "__vector" is deprecated}} expected-error {{cannot use "double" with "__vector"}} void f() { __vector unsigned int v = {0,0,0,0}; __vector int v__cast = (__vector int)v; __vector int v_cast = (vector int)v; __vector char vb_cast = (vector char)v; // Check some casting between gcc and altivec vectors. #define gccvector __attribute__((vector_size(16))) gccvector unsigned int gccv = {0,0,0,0}; gccvector unsigned int gccv1 = gccv; gccvector int gccv2 = (gccvector int)gccv; gccvector unsigned int gccv3 = v; __vector unsigned int av = gccv; __vector int avi = (__vector int)gccv; gccvector unsigned int gv = v; gccvector int gvi = (gccvector int)v; __attribute__((vector_size(8))) unsigned int gv8; gv8 = gccv; // expected-error {{incompatible type assigning '__attribute__((__vector_size__(4 * sizeof(unsigned int)))) unsigned int', expected '__attribute__((__vector_size__(2 * sizeof(unsigned int)))) unsigned int'}} av = gv8; // expected-error {{incompatible type assigning '__attribute__((__vector_size__(2 * sizeof(unsigned int)))) unsigned int', expected '__vector unsigned int'}} v = gccv; __vector unsigned int tv = gccv; gccv = v; gccvector unsigned int tgv = v; } // Now for the C++ version: class vc__v { __vector int v; __vector int f__r(); void f__a(__vector int a); void f__a2(int b, __vector int a); }; class c_v { vector int v; vector int f__r(); void f__a(vector int a); void f__a2(int b, vector int a); };
[ "john.thompson.jtsoftware@gmail.com" ]
john.thompson.jtsoftware@gmail.com
bdaad76b9e5ef39401dd4da45c1160025b6b243f
ad206aa0d228d5d3e41261316b88e190437e21c4
/src/qt/rpcconsole.h
b3e2f7c2d36e758da6d5407b9e9ea495e8626883
[ "MIT" ]
permissive
gtacoin-dev/gtacoin
a0188517948afb4458913d87b2f600ffaf9b6803
f66f063b47ba973856c200074db1b95abf5ab794
refs/heads/master
2021-01-22T10:59:35.068066
2017-02-15T15:29:16
2017-02-15T15:29:16
82,058,190
0
0
null
null
null
null
UTF-8
C++
false
false
4,421
h
// Copyright (c) 2011-2015 The Gtacoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef GTACOIN_QT_RPCCONSOLE_H #define GTACOIN_QT_RPCCONSOLE_H #include "guiutil.h" #include "peertablemodel.h" #include "net.h" #include <QWidget> #include <QCompleter> #include <QThread> class ClientModel; class PlatformStyle; class RPCTimerInterface; namespace Ui { class RPCConsole; } QT_BEGIN_NAMESPACE class QMenu; class QItemSelection; QT_END_NAMESPACE /** Local Gtacoin RPC console. */ class RPCConsole: public QWidget { Q_OBJECT public: explicit RPCConsole(const PlatformStyle *platformStyle, QWidget *parent); ~RPCConsole(); void setClientModel(ClientModel *model); enum MessageClass { MC_ERROR, MC_DEBUG, CMD_REQUEST, CMD_REPLY, CMD_ERROR }; enum TabTypes { TAB_INFO = 0, TAB_CONSOLE = 1, TAB_GRAPH = 2, TAB_PEERS = 3 }; protected: virtual bool eventFilter(QObject* obj, QEvent *event); void keyPressEvent(QKeyEvent *); private Q_SLOTS: void on_lineEdit_returnPressed(); void on_tabWidget_currentChanged(int index); /** open the debug.log from the current datadir */ void on_openDebugLogfileButton_clicked(); /** change the time range of the network traffic graph */ void on_sldGraphRange_valueChanged(int value); /** update traffic statistics */ void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut); void resizeEvent(QResizeEvent *event); void showEvent(QShowEvent *event); void hideEvent(QHideEvent *event); /** Show custom context menu on Peers tab */ void showPeersTableContextMenu(const QPoint& point); /** Show custom context menu on Bans tab */ void showBanTableContextMenu(const QPoint& point); /** Hides ban table if no bans are present */ void showOrHideBanTableIfRequired(); /** clear the selected node */ void clearSelectedNode(); public Q_SLOTS: void clear(bool clearHistory = true); void fontBigger(); void fontSmaller(); void setFontSize(int newSize); /** Append the message to the message widget */ void message(int category, const QString &message, bool html = false); /** Set number of connections shown in the UI */ void setNumConnections(int count); /** Set number of blocks and last block date shown in the UI */ void setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers); /** Set size (number of transactions and memory usage) of the mempool in the UI */ void setMempoolSize(long numberOfTxs, size_t dynUsage); /** Go forward or back in history */ void browseHistory(int offset); /** Scroll console view to end */ void scrollToEnd(); /** Handle selection of peer in peers list */ void peerSelected(const QItemSelection &selected, const QItemSelection &deselected); /** Handle updated peer information */ void peerLayoutChanged(); /** Disconnect a selected node on the Peers tab */ void disconnectSelectedNode(); /** Ban a selected node on the Peers tab */ void banSelectedNode(int bantime); /** Unban a selected node on the Bans tab */ void unbanSelectedNode(); /** set which tab has the focus (is visible) */ void setTabFocus(enum TabTypes tabType); Q_SIGNALS: // For RPC command executor void stopExecutor(); void cmdRequest(const QString &command); private: static QString FormatBytes(quint64 bytes); void startExecutor(); void setTrafficGraphRange(int mins); /** show detailed information on ui about selected node */ void updateNodeDetail(const CNodeCombinedStats *stats); enum ColumnWidths { ADDRESS_COLUMN_WIDTH = 200, SUBVERSION_COLUMN_WIDTH = 150, PING_COLUMN_WIDTH = 80, BANSUBNET_COLUMN_WIDTH = 200, BANTIME_COLUMN_WIDTH = 250 }; Ui::RPCConsole *ui; ClientModel *clientModel; QStringList history; int historyPtr; NodeId cachedNodeid; const PlatformStyle *platformStyle; RPCTimerInterface *rpcTimerInterface; QMenu *peersTableContextMenu; QMenu *banTableContextMenu; int consoleFontSize; QCompleter *autoCompleter; QThread thread; }; #endif // GTACOIN_QT_RPCCONSOLE_H
[ "coinbitex@coinbitex.local" ]
coinbitex@coinbitex.local
9d3f09c0bbe934e0650e0a91c52bf7f471d61af7
d2f493f794151b2f0b927617b10f0f9338572ff0
/SPOJ/P185PROI.cpp
467f9669cd6d16d5aa3f4acfa70081ed08af1480
[]
no_license
hungnt61h/PTIT-Algorithms
320aa078216fc17203ec7f14d70fbfa8a577e2a1
d53786a87a0b0a8fe2efbbaaf886f835a0d27f34
refs/heads/master
2020-03-07T22:46:24.188916
2018-04-07T06:39:43
2018-04-07T06:39:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
#include <iostream> using namespace std; long long count(long long x) { long long count = 0, n = 1; while (x != 0) { if (x%2 == 0) count += n; n <<= 1; x >>= 1; } return count; } void run() { long long x; cin>>x; cout<<count(x)<<endl; } int main() { int T; cin>>T; while(T--) { run(); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
f25a26e53e13c34b56583bbdb8eb1c429d383758
c7e0e533e783ffb9a49568ea3d560830ba86e1d1
/vendor/RectangleBinPack/MaxRectsBinPack.h
770b251b771de9f48dfa74fb03e1ea77519ae594
[ "LicenseRef-scancode-public-domain", "MIT" ]
permissive
iomeone/run-on-coal
fb8ee173fa82a854c314ef3f521a4d2386c96e39
5095b15996b8747038d330140e17222de6de0c0e
refs/heads/master
2022-11-27T07:56:15.006487
2020-08-08T07:55:44
2020-08-08T07:55:44
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,802
h
/** @file MaxRectsBinPack.h @author Jukka Jylänki @brief Implements different bin packer algorithms that use the MAXRECTS data structure. This work is released to Public Domain, do whatever you want with it. */ #pragma once #include <vector> #include "Rect.h" namespace rbp { /** MaxRectsBinPack implements the MAXRECTS data structure and different bin packing algorithms that use this structure. */ class MaxRectsBinPack { public: /// Instantiates a bin of size (0,0). Call Init to create a new bin. MaxRectsBinPack(); /// Instantiates a bin of the given size. MaxRectsBinPack(int width, int height, bool rotations = true); /// (Re)initializes the packer to an empty bin of width x height units. Call whenever /// you need to restart with a new bin. void Init(int width, int height, bool rotations = true); /// Specifies the different heuristic rules that can be used when deciding where to place a new rectangle. enum FreeRectChoiceHeuristic { RectBestShortSideFit, ///< -BSSF: Positions the rectangle against the short side of a free rectangle into which it fits the best. RectBestLongSideFit, ///< -BLSF: Positions the rectangle against the long side of a free rectangle into which it fits the best. RectBestAreaFit, ///< -BAF: Positions the rectangle into the smallest free rect into which it fits. RectBottomLeftRule, ///< -BL: Does the Tetris placement. RectContactPointRule ///< -CP: Choosest the placement where the rectangle touches other rects as much as possible. }; /// Inserts the given list of rectangles in an offline/batch mode, possibly rotated. /// @param rects The list of rectangles to insert. This vector will be destroyed in the process. /// @param dst [out] This list will contain the packed rectangles. The indices will not correspond to that of rects. /// @param method The rectangle placement rule to use when packing. void Insert(std::vector<RectSize> &rects, std::vector<Rect> &dst, FreeRectChoiceHeuristic method); /// Inserts a single rectangle into the bin, possibly rotated. Rect Insert(int width, int height, FreeRectChoiceHeuristic method); /// Computes the ratio of used surface area to the total bin area. float Occupancy() const; private: int binWidth; int binHeight; bool allowRotations; // Ported from C# class std::vector<Rect> usedRectangles; std::vector<Rect> freeRectangles; /// Computes the placement score for placing the given rectangle with the given method. /// @param score1 [out] The primary placement score will be outputted here. /// @param score2 [out] The secondary placement score will be outputted here. This isu sed to break ties. /// @return This struct identifies where the rectangle would be placed if it were placed. Rect ScoreRect(int width, int height, FreeRectChoiceHeuristic method, int &score1, int &score2) const; /// Places the given rectangle into the bin. void PlaceRect(const Rect &node); /// Computes the placement score for the -CP variant. int ContactPointScoreNode(int x, int y, int width, int height) const; Rect FindPositionForNewNodeBottomLeft(int width, int height, int &bestY, int &bestX) const; Rect FindPositionForNewNodeBestShortSideFit(int width, int height, int &bestShortSideFit, int &bestLongSideFit) const; Rect FindPositionForNewNodeBestLongSideFit(int width, int height, int &bestShortSideFit, int &bestLongSideFit) const; Rect FindPositionForNewNodeBestAreaFit(int width, int height, int &bestAreaFit, int &bestShortSideFit) const; Rect FindPositionForNewNodeContactPoint(int width, int height, int &contactScore) const; /// @return True if the free node was split. bool SplitFreeNode(Rect &freeNode, const Rect &usedNode); /// Goes through the free rectangle list and removes any redundant entries. void PruneFreeList(); }; }
[ "sdraw5130@gmail.com" ]
sdraw5130@gmail.com
6815ecc8f9c9e7a2a181b2618209e5eac540cef6
c41e646305b0e2267e06de36a9fcca171c2862fb
/src/qt/bitcoinamountfield.cpp
6f65a58ca2aeb4604a146a6e268e45a0f72616ae
[ "MIT" ]
permissive
ZippyNetworks/pfzercoin
302d4f4da08ab8510386e5074fcfc1dd56d407e2
50b4a64b744b4b8c3b5245162ee79e6b44844c31
refs/heads/master
2023-07-13T13:34:09.728655
2021-08-08T00:19:13
2021-08-08T00:19:13
400,015,216
1
0
null
null
null
null
UTF-8
C++
false
false
9,109
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2021-2021 The PfzerCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinamountfield.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "qvaluecombobox.h" #include <QAbstractSpinBox> #include <QApplication> #include <QHBoxLayout> #include <QKeyEvent> #include <QLineEdit> /** QSpinBox that uses fixed-point numbers internally and uses our own * formatting/parsing functions. */ class AmountSpinBox : public QAbstractSpinBox { Q_OBJECT public: explicit AmountSpinBox(QWidget* parent) : QAbstractSpinBox(parent), currentUnit(BitcoinUnits::PFZR), singleStep(100000) // satoshis { setAlignment(Qt::AlignRight); connect(lineEdit(), SIGNAL(textEdited(QString)), this, SIGNAL(valueChanged())); } QValidator::State validate(QString& text, int& pos) const { if (text.isEmpty()) return QValidator::Intermediate; bool valid = false; parse(text, &valid); /* Make sure we return Intermediate so that fixup() is called on defocus */ return valid ? QValidator::Intermediate : QValidator::Invalid; } void fixup(QString& input) const { bool valid = false; CAmount val = parse(input, &valid); if (valid) { input = BitcoinUnits::format(currentUnit, val, false, BitcoinUnits::separatorAlways); lineEdit()->setText(input); } } CAmount value(bool* valid_out = 0) const { return parse(text(), valid_out); } void setValue(const CAmount& value) { lineEdit()->setText(BitcoinUnits::format(currentUnit, value, false, BitcoinUnits::separatorAlways)); emit valueChanged(); } void stepBy(int steps) { bool valid = false; CAmount val = value(&valid); val = val + steps * singleStep; val = qMin(qMax(val, CAmount(0)), BitcoinUnits::maxMoney()); setValue(val); } void setDisplayUnit(int unit) { bool valid = false; CAmount val = value(&valid); currentUnit = unit; if (valid) setValue(val); else clear(); } void setSingleStep(const CAmount& step) { singleStep = step; } QSize minimumSizeHint() const { if (cachedMinimumSizeHint.isEmpty()) { ensurePolished(); const QFontMetrics fm(fontMetrics()); int h = lineEdit()->minimumSizeHint().height(); int w = fm.width(BitcoinUnits::format(BitcoinUnits::PFZR, BitcoinUnits::maxMoney(), false, BitcoinUnits::separatorAlways)); w += 2; // cursor blinking space QStyleOptionSpinBox opt; initStyleOption(&opt); QSize hint(w, h); QSize extra(35, 6); opt.rect.setSize(hint + extra); extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this).size(); // get closer to final result by repeating the calculation opt.rect.setSize(hint + extra); extra += hint - style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this).size(); hint += extra; hint.setHeight(h); opt.rect = rect(); cachedMinimumSizeHint = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this).expandedTo(QApplication::globalStrut()); } return cachedMinimumSizeHint; } private: int currentUnit; CAmount singleStep; mutable QSize cachedMinimumSizeHint; /** * Parse a string into a number of base monetary units and * return validity. * @note Must return 0 if !valid. */ CAmount parse(const QString& text, bool* valid_out = 0) const { CAmount val = 0; bool valid = BitcoinUnits::parse(currentUnit, text, &val); if (valid) { if (val < 0 || val > BitcoinUnits::maxMoney()) valid = false; } if (valid_out) *valid_out = valid; return valid ? val : 0; } protected: bool event(QEvent* event) { if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); return QAbstractSpinBox::event(&periodKeyEvent); } } return QAbstractSpinBox::event(event); } StepEnabled stepEnabled() const { StepEnabled rv = 0; if (isReadOnly()) // Disable steps when AmountSpinBox is read-only return StepNone; if (text().isEmpty()) // Allow step-up with empty field return StepUpEnabled; bool valid = false; CAmount val = value(&valid); if (valid) { if (val > 0) rv |= StepDownEnabled; if (val < BitcoinUnits::maxMoney()) rv |= StepUpEnabled; } return rv; } signals: void valueChanged(); }; #include "bitcoinamountfield.moc" BitcoinAmountField::BitcoinAmountField(QWidget* parent) : QWidget(parent), amount(0) { this->setObjectName("BitcoinAmountField"); // ID as CSS-reference // For whatever reasons the Gods of Qt-CSS-manipulation won't let us change this class' stylesheet in the CSS file. // Workaround for the people after me: // - name all UI objects, preferably with a unique name // - address those names globally in the CSS file amount = new AmountSpinBox(this); // According to the Qt-CSS specs this should work, but doesn't amount->setStyleSheet("QSpinBox::up-button:hover { background-color: #f2f2f2; }" "QSpinBox::down-button:hover { background-color: #f2f2f2; }"); amount->setLocale(QLocale::c()); amount->installEventFilter(this); amount->setMaximumWidth(170); QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0, 0, 0, 0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged()), this, SIGNAL(valueChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } void BitcoinAmountField::setEnabled(bool fEnabled) { amount->setEnabled(fEnabled); unit->setEnabled(fEnabled); } bool BitcoinAmountField::validate() { bool valid = false; value(&valid); setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) // According to the Qt-CSS specs this should work, but doesn't amount->setStyleSheet("QSpinBox::up-button:hover { background-color: #f2f2f2 }" "QSpinBox::down-button:hover { background-color: #f2f2f2 }"); else amount->setStyleSheet(STYLE_INVALID); } bool BitcoinAmountField::eventFilter(QObject* object, QEvent* event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } return QWidget::eventFilter(object, event); } QWidget* BitcoinAmountField::setupTabChain(QWidget* prev) { QWidget::setTabOrder(prev, amount); QWidget::setTabOrder(amount, unit); return unit; } CAmount BitcoinAmountField::value(bool* valid_out) const { return amount->value(valid_out); } void BitcoinAmountField::setValue(const CAmount& value) { amount->setValue(value); } void BitcoinAmountField::setReadOnly(bool fReadOnly) { amount->setReadOnly(fReadOnly); unit->setEnabled(!fReadOnly); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); amount->setDisplayUnit(newUnit); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); } void BitcoinAmountField::setSingleStep(const CAmount& step) { amount->setSingleStep(step); }
[ "PFZER777@gmail.com" ]
PFZER777@gmail.com
d8e3e44304552931b35a76eb6f3b89da41f0f511
49250c0ef62660f04fadb71ea06cdddb1a82c727
/src/storage/path.hpp
3257d74bc01444058c1cf2a58b15f0b7e43f6da2
[ "BSD-2-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
derofim/boost_server_example
fb22f29c1c306e403c759386cd3dfc14052068a9
b524adbf842faa75fd5f5d46486dff605b96bfde
refs/heads/master
2020-04-18T03:17:59.766866
2019-01-28T12:34:19
2019-01-28T12:34:19
167,193,719
0
0
null
null
null
null
UTF-8
C++
false
false
308
hpp
#pragma once #include <filesystem> #include <string> namespace boostander { namespace storage { std::filesystem::path getThisBinaryPath(); std::filesystem::path getThisBinaryDirectoryPath(); std::string getFileContents(const std::filesystem::path& path); } // namespace storage } // namespace boostander
[ "derofim@yandex.ru" ]
derofim@yandex.ru
e656b7be43c7cff5a419e198b68050443afd3e34
19fc6bf42d1050df14d5236c07c61d2f5b409984
/src/function.cpp
985e9cb2c1011de2686bf4cfa4db96afe50b7bb3
[]
no_license
smallzhong/C-project
347631b2c7eae80aaa4db70f01a4e1ff4b93f843
5a283db38a52a5d82a9fc0600e7c6a743c580b83
refs/heads/main
2023-02-02T12:38:13.739269
2020-12-19T09:22:48
2020-12-19T09:22:48
322,809,471
3
0
null
null
null
null
GB18030
C++
false
false
22,833
cpp
#include "head.h" extern bool flag; extern int lines; extern FILE *fp_lines; extern char txt1[]; extern struct Node nodes[N]; void initWindow(char *title) { //设置窗口大小 // system("mode con:cols=100 lines=1000"); // system("mode con:cols=100"); //设置窗口字体的颜色 system("color 7D"); //循环输出标题(条件:) while (*title != 0) { //输出字符指针所指向的内容 printf("%c", *title); //将指针指向下一个字符 title++; //休眠 Sleep(50); } } void start_print() { printf("\t\t\t\t----------功能列表-------\n"); printf("\t\t\t\t------1------展示记录\n"); printf("\t\t\t\t------2------添加记录\n"); printf("\t\t\t\t------3------进行排序\n"); printf("\t\t\t\t-----------------------------------\n"); printf("\t\t\t\t------4------查找消费记录\n"); printf("\t\t\t\t------5------展示所有的消费记录并进行删除操作\n"); printf("\t\t\t\t------6-----统计当前的总金额\n"); printf("\t\t\t\t------7-----更改记录中的内容\n"); printf("\t\t\t\t------8-----关于我们\n"); printf("\t\t\t\t------9-----附件\n"); printf("\t\t\t\t------10-----退出当前程序\n"); printf("\t\t\t\t-----------------------------------------------\n"); } void delete_print(int n) { FILE *fp; // fp = open_rplus("1.txt"); fp = fopen("1.txt", "r"); if (fp == NULL) { perror("出错啦: "); system("pause"); exit(EXIT_FAILURE); } fseek(fp, 0L, SEEK_SET); if (flag == false) { get_data(n); flag = true; } // printf("%10s %10s %10s\n", "日期", "金额", "用途"); // for (int i = 1; i <= n; i++) // { // printf("id:%d %10d %10.2lf %10s\n", i, nodes[i].date, nodes[i].cost, nodes[i].usage); // } char buf[BUFSIZE]; int i = 1; // while (1) // { // fgets(buf, 10000, fp); // if (feof(fp)) // break; // printf("id = %d:%s", i++, buf); // } while (fgets(buf, 10000, fp) != NULL) { if (i > lines) { break; //如果当前读取的行数大于总的行数,说明读取到了空行,跳出循环 } printf("id = %d:%s", i, buf); i++; } if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; } bool cost_desc_cmp(Node a, Node b) { if (fabs(a.cost - b.cost) > esp) //如果a.cost不等于b.cost { return a.cost > b.cost; } return a.date < b.date; //如果等于,就以日期从大到小输出 } bool date_desc_cmp(Node a, Node b) { if (a.date != b.date) { return a.date > b.date; } return a.cost > b.cost; } bool date_asc_cmp(Node a, Node b) { if (a.date != b.date) { return a.date < b.date; } return a.cost > b.cost; } bool cost_asc_cmp(Node a, Node b) { if (fabs(a.cost - b.cost) > esp) //如果a.cost不等于b.cost { return a.cost < b.cost; } return a.date < b.date; //如果等于,就以日期从大到小输出 } void print_sort_cost_desc(int n) { FILE *fp; fp = open_rplus(txt1); if (flag == false) //如果当前的数据并没有被读进到结构体里面 { get_data(n); flag = true; } sort(nodes + 1, nodes + 1 + n, cost_desc_cmp); printf("---------------start-------------------------\n"); printf("%10s %10s %10s\n", "日期", "金额", "用途"); for (int i = 1; i <= n; i++) { printf("%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } printf("-----共有%d条记录-----\n-------------------end---------------------------\n\n", lines); if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; system("pause"); } void print_sort_date_desc(int n) { FILE *fp; fp = open_rplus(txt1); if (flag == false) //如果当前的数据并没有被读进到结构体里面 { get_data(n); flag = true; } sort(nodes + 1, nodes + 1 + n, date_desc_cmp); printf("-------------------start---------------------------\n"); printf("%10s %10s %10s\n", "日期", "金额", "用途"); for (int i = 1; i <= n; i++) { printf("%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } printf("-----共有%d条记录-----\n-------------------end---------------------------\n\n", lines); if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; system("pause"); } void print_sort_date_asc(int n) { FILE *fp; fp = open_rplus(txt1); if (flag == false) //如果当前的数据并没有被读进到结构体里面 { get_data(n); flag = true; } sort(nodes + 1, nodes + 1 + n, date_asc_cmp); printf("-------------------start---------------------------\n"); printf("%10s %10s %10s\n", "日期", "金额", "用途"); for (int i = 1; i <= n; i++) { printf("%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } printf("-----共有%d条记录-----\n-------------------end---------------------------\n\n", lines); if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; system("pause"); } void print_sort_cost_asc(int n) { FILE *fp; fp = open_rplus(txt1); if (flag == false) //如果当前的数据并没有被读进到结构体里面 { get_data(n); flag = true; } sort(nodes + 1, nodes + 1 + n, cost_asc_cmp); printf("-------------------start---------------------------\n"); printf("%10s %10s %10s\n", "日期", "金额", "用途"); for (int i = 1; i <= n; i++) { printf("%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } printf("-----共有%d条记录-----\n-------------------end---------------------------\n\n", lines); if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; system("pause"); } void get_data(int n) { FILE *fp; fp = open_rplus(txt1); rewind(fp); for (int i = 1; i <= n; i++) { int date; double cost; char usage[110]; fscanf(fp, "%d %lf %s", &date, &cost, usage); nodes[i].date = date; nodes[i].cost = cost; strcpy(nodes[i].usage, usage); } if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } } void print_all() { // FILE *fp; // // fp = open_rplus("1.txt"); // fp = fopen("1.txt", "r"); // if (fp == NULL) // { // perror("出错啦:"); // system("pause"); // exit(EXIT_FAILURE); // } // rewind(fp); // printf("\n-----------start--------\n"); // char buf[BUFSIZE]; // int i = 1; //用来记录当前的行数。如果多于总行数就跳出循环,防止输出空行 // while (fgets(buf, sizeof(buf), fp) != NULL) // { // if (i > lines) // { // break; //跳出循环 // } // printf("%s", buf); // i++; // } // printf("-----共有%d条记录-----\n-----------end--------\n\n", lines); // if (fclose(fp) != 0) // { // fprintf(stderr, "关闭文件的时候出现错误!\n"); // exit(EXIT_FAILURE); // } FILE *fp; fp = open_rplus(txt1); if (flag == false) //如果当前的数据并没有被读进到结构体里面 { get_data(lines); flag = true; } printf("-------------------start---------------------------\n"); printf("%10s %10s %10s\n", "日期", "金额", "用途"); for (int i = 1; i <= lines; i++) { printf("%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } printf("-----共有%d条记录-----\n-------------------end---------------------------\n\n", lines); if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } system("pause"); } void insert() { FILE *fp; fp = open_rplus(txt1); { lines++; rewind(fp_lines); fprintf(fp_lines, "%d", lines); } //首先将line.txt更新 fseek(fp, 0L, SEEK_END); //将文件指针指到文件的结尾 int year, mon, day; printf("请输入当前的日期,格式为 20XX.XX.XX\n"); scanf("%d.%d.%d", &year, &mon, &day); int date = year * 10000 + mon * 100 + day; // cout<<date; printf("请输入您想记录的金额\n"); double cost; scanf("%lf", &cost); char usage[110]; printf("请输入用途\n"); scanf("%s", usage); // printf("%10s %10s %10s\n", "日期", "金额", "用途"); // fprintf(fp, "%10d %10.2lf %10s\n", date, cost, usage); fprintf(fp, "%d %.2lf %s\n", date, cost, usage); flag = false; if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; system("pause"); } void my_sort(int n) //传入文件指针和当前文件里面的记录的总条数 { int type; FILE *fp; fp = open_rplus(txt1); printf("-------------以下是排序功能-----------\n"); while (1) { printf("---1------按每次消费的金额降序输出当前的消费记录\n"); printf("---2------按每次消费的金额升序输出当前的消费记录\n"); printf("---3------按日期降序输出当前的消费记录\n"); printf("---4------按日期升序输出当前的消费记录\n"); printf("---0------返回上一级\n"); scanf("%d", &type); if (type == 1) { print_sort_cost_desc(lines); break; } else if (type == 2) { print_sort_cost_asc(lines); break; } else if (type == 3) { print_sort_date_desc(lines); break; } else if (type == 4) { print_sort_date_asc(lines); break; } else if (type == 0) return; else { printf("输入不合法!请重新输入。\n"); continue; } } if (flag == false) //如果当前的数据并没有被读进到结构体里面 { get_data(n); flag = true; } sort(nodes + 1, nodes + 1 + n, file_sort); //进行对当前文件里面的东西的排序 rewind(fp); // printf("%10s %10s %10s\n", "日期", "金额", "用途"); for (int i = 1; i <= n; i++) { fprintf(fp, "%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); // fprintf(stdout, "%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } if (fclose(fp) != 0) { fprintf(stderr, "关闭文件的时候出现错误!\n"); exit(EXIT_FAILURE); } } void delete_one(int n) { FILE *fp; // fp = open_rplus("1.txt"); fp = fopen("1.txt", "r"); if (fp == NULL) { perror("出错啦:"); system("pause"); exit(EXIT_FAILURE); } FILE *fpt; char buf[BUFSIZE]; fpt = fopen("temp.txt", "w"); if (fpt == NULL) { perror("出错啦:"); system("pause"); exit(EXIT_FAILURE); } // while (1) // { // i++; // if (i == n) // { // fgets(buf, sizeof(buf), fp); //除了需要删除的那一行,其他的全部放到temp.txt里面去 // // if (feof(fp) || buf[0] == '\n') //如果当前到达了文件的末尾或者读了一个换行符进来(也说明这是文件的末尾),break // // break; // if (fgets(buf, 100, fp) == NULL) // break; // if (buf[0] == '\n') // break; // printf("i == n buf = %s", buf); // } // else // { // if (fgets(buf, 100, fp) == NULL) // break; // if (buf[0] == '\n') // break; // // if (feof(fp) || buf[0] == '\n') //如果当前到达了文件的末尾或者读了一个换行符进来(也说明这是文件的末尾),break // // break; // printf("%s", buf); // fputs(buf, fpt); // } // } int i = 1; //用来记录当前读的是第几行 while (fgets(buf, 1000, fp) != NULL) { // if (i > lines) // { // break;//如果当前行数的id大于总的行数, // } if (i == n) { i++; continue; } else { i++; fputs(buf, fpt); } } fclose(fp); fclose(fpt); //全部关闭 // system("erase 1.txt"); //将源文件删除 // remove("1.txt"); const char A[10] = "1.txt"; if (remove(A)) { printf("删除失败\n"); perror("remove"); system("pause"); exit(EXIT_FAILURE); } if (rename("temp.txt", "1.txt")) { perror("重命名时出现错误: "); system("pause"); exit(EXIT_FAILURE); } //至此1.txt文件里面的内容全部修改完毕 //开始修改line.txt里面的内容 lines--; //先减少一行 FILE *lfp; lfp = fopen("line.txt", "w"); if (lfp == NULL) { printf("can't open line.txt\n"); perror("错误信息: "); system("pause"); exit(EXIT_FAILURE); } fprintf(fp, "%d", lines); if (fclose(lfp) != 0) //用来关闭lfp { perror("关闭line.txt时发生错误"); system("pause"); exit(EXIT_FAILURE); } // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; flag = false; system("pause"); } void print_sum() { if (flag == false) { get_data(lines); flag = true; } double sum = 0; for (int i = 1; i <= lines; i++) { sum += nodes[i].cost; } printf("当前所有记录的总钱数是:%.2lf\n", sum); // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; system("pause"); } void change() { // delete_print(lines); get_data(lines); flag = false; FILE *fp; fp = open_rplus(txt1); char buf[BUFSIZE]; int i = 1; while (fgets(buf, 10000, fp) != NULL) { if (i > lines) { break; //如果当前读取的行数大于总的行数,说明读取到了空行,跳出循环 } printf("id = %d:%s", i, buf); i++; } // for (int i = 1; i <= lines; i++) // { // printf("%d %.2lf %s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); // } printf("如果您想修改某条记录的日期,请输入1,想修改金额请输入2,想修改记录的用途请输入3\n"); int type; scanf("%d", &type); while (!(type == 1 || type == 2 || type == 3)) { printf("输入不合法,请重新输入:"); scanf("%d", &type); } int line_to_alter; printf("请输入您想要修改的记录的id\n"); scanf("%d", &line_to_alter); while (line_to_alter < 1 || line_to_alter > lines) { printf("输入不合法,请重新输入:"); scanf("%d", &line_to_alter); } if (type == 1) { printf("请输入想修改成的日期:"); int date; scanf("%d", &date); nodes[line_to_alter].date = date; } else if (type == 2) { printf("请输入想修改成的金额:"); double money; scanf("%lf", &money); nodes[line_to_alter].cost = money; } else if (type == 3) { char temp[BUFSIZE]; printf("请输入想要修改成的用途:"); scanf("%s", temp); strcpy(nodes[line_to_alter].usage, temp); } printf("=============修改后的记录============\n"); printf("%10s %10s %10s\n", "日期", "金额", "用途"); for (int i = 1; i <= lines; i++) { printf("%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } printf("===================================\n"); FILE *fp2; fp2 = fopen("temp.txt", "w"); if (fp2 == NULL) { perror("出错啦:"); system("pause"); exit(EXIT_FAILURE); } printf("%10s %10s %10s\n", "日期", "金额", "用途"); for (int i = 1; i <= lines; i++) { fprintf(fp2, "%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } if (fclose(fp) == EOF) { perror("can't close fp:"); system("pause"); exit(EXIT_FAILURE); } if (fclose(fp2) == EOF) { perror("can't close fp2"); system("pause"); exit(EXIT_FAILURE); } if (remove("1.txt") != 0) { printf("can't remove 1.txt!\n"); system("pause"); exit(EXIT_FAILURE); } if (rename("temp.txt", "1.txt") != 0) { printf("can't rename it!\n"); system("pause"); exit(EXIT_FAILURE); } system("pause"); } void get_special_date(int n) { if (flag == false) //如果当前的数据并没有被读进到结构体里面 { get_data(lines); } flag = false; //因为要将结构体里面的东西进行排序,所以下一次读取数据的时候要重新读取 sort(nodes + 1, nodes + 1 + lines, sort_asc); bool tflag = false; //用来记录需要查找的日期到底有没有记录 int ct = 0; //用来记录一共查找到了几条记录 for (int i = 1; i <= lines; i++) { if (nodes[i].date > n) break; //如果当前遍历到的已经大于需要查找的日期,跳出循环 if (nodes[i].date == n) { ct++; if (tflag == false) { printf("-------查找到的记录如下----------\n"); printf("%10s %10s %10s\n", "日期", "金额", "用途"); } tflag = true; printf("%10d %10.2lf %10s\n", nodes[i].date, nodes[i].cost, nodes[i].usage); } } if (tflag == false) //如果没有找到 { printf("对不起,未查到您输入日期当日的消费记录。\n"); } else { printf("-------以上共查找到了%d条记录-------\n", ct); } // printf("-----0------返回上一级\n"); // int type; // scanf("%d", &type); // if (type == 0) // return; system("pause"); } FILE *open_rplus(char *filename) { FILE *fp; if ((fp = fopen(filename, "r+")) == NULL) { fprintf(stderr, "打开%s文件的时候出现错误,有可能是因为该文件不存在,如果不存在请先创建文件\n", filename); perror(filename); system("pause"); exit(EXIT_FAILURE); } return fp; } void init() { FILE *fp1; fp1 = fopen("1.txt", "wb"); if (fp1 == NULL) { perror("出错啦:"); system("pause"); exit(EXIT_FAILURE); } fclose(fp1); FILE *fp2; fp2 = fopen("line.txt", "w"); if (fp2 == NULL) { perror("出错啦:"); system("pause"); exit(EXIT_FAILURE); } fprintf(fp2, "0"); fclose(fp2); //创立两个文件并向记录行数的文件里面记录行数为0 lines = 0; return; } void fujian() { printf("\t\t\t\t----------功能列表-------\n"); int type; while (1) { printf("\t\t\t\t------1------------计算器\n"); scanf("%d", &type); if (type == 1) { cul(); break; } else { printf("输入不合法,请重新输入。\n"); continue; } } } void cul() { // 分别存放第一个操作数和第二个操作数以及结果的变量 double x1, x2, result; // 存放运算符的变量 char m; int ttt = 1; while (ttt) { printf("请输入第一个数:\n"); // 下面这得注意,接收double型的数据得用lf%,接收float用f% scanf("%lf", &x1); printf("请输入运算操作(+ - * /):\n"); cin >> m; printf("\n"); printf("请输入第二个数:\n"); scanf("%lf", &x2); switch (m) { case '+': printf("加法\n"); result = x1 + x2; printf("%lf + %lf = %lf\n", x1, x2, result); break; case '-': printf("减法\n"); result = x1 - x2; printf("%lf - %lf = %lf\n", x1, x2, result); break; case '*': printf("乘法\n"); result = x1 * x2; printf("%lf * %lf = %lf\n", x1, x2, result); break; case '/': printf("除法\n"); if (x2 == 0) { printf("除数不能为0.\n"); } else { result = x1 / x2; printf("%lf / %lf = %lf\n", x1, x2, result); } break; default: break; } printf("是否继续?输入0退出\n"); scanf("%d", &ttt); // cout << "是否继续" << e // cin >> ttt; } } bool file_sort(Node a, Node b) { return a.date < b.date; } bool sort_asc(Node a, Node b) { if (a.date != b.date) { return a.date < b.date; } return a.cost < b.cost; }
[ "2211261685@qq.com" ]
2211261685@qq.com
bfa574c3a89f16e28f8caebd240098ba0eb20122
064741ef54df109388c291db9e5820bc90b9f664
/cfcontest/721/B.cpp
3454b62c2056fcab5b4f6e2928c11b7ee0212b4b
[]
no_license
overlorde/codeforces
2bf48bb3b638e8c8406d39c25c265b84115043fa
87a6fdde921abaccbe88e13d75b0a929bea7117c
refs/heads/master
2023-06-14T15:22:38.483292
2021-07-08T09:45:57
2021-07-08T09:45:57
266,014,269
0
0
null
null
null
null
UTF-8
C++
false
false
712
cpp
#include <bits/stdc++.h> using namespace std; #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL) #define ll long long #define ld long double #define vi vector<ll> #define vd vector<ld> #define vc vector<char> void solve() { bool flag = 0; ll n;cin>>n; ll m=0,k=0; for(ll i=0;i<n;i++) { char c;cin>>c; if(c=='0')k++; else m++; } if(k==1){ cout<<"BOB\n"<<endl; } if(k%2==0 && flag ==0){ cout<<"BOB"<<endl; flag=1; }else if(k%2==0 && flag==1){ cout<<"DRAW"<<endl; flag=0; } else if(k%2==1 && k!=1){ cout<<"ALICE"<<endl; } } int main() { fastio; freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int t; cin>>t; while(t--){ solve(); } }
[ "farhansaif488@gmail.com" ]
farhansaif488@gmail.com
93ccba480e7a5c3c8718efcd83887e276d336e42
b3c47795e8b6d95ae5521dcbbb920ab71851a92f
/POJ/2/2228.cc
2c4866a367113c0f07deb66c8af0a0ebce0d8656
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Wizmann/ACM-ICPC
6afecd0fd09918c53a2a84c4d22c244de0065710
7c30454c49485a794dcc4d1c09daf2f755f9ecc1
refs/heads/master
2023-07-15T02:46:21.372860
2023-07-09T15:30:27
2023-07-09T15:30:27
3,009,276
51
23
null
null
null
null
UTF-8
C++
false
false
1,686
cc
//Result:wizmann 2228 Accepted 808K 125MS G++ 1312B #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <algorithm> #include <iostream> #include <bitset> using namespace std; #define print(x) cout<<x<<endl #define input(x) cin>>x #define SIZE 3850 #define INF 1<<30 int dp[2][SIZE][2]; //dp[x][y][z(0,1)]数组的意义是:在现在处于第x个时间段,已经休息了y时间段,现在的状态是(清醒/迷糊) int array[SIZE]; int n,b; int slove(bool ring=false) { int pos=0; for(int i=1;i<n;i++) { for(int j=1;j<=b;j++) { dp[pos][j][0]=max(dp[pos^1][j][0],dp[pos^1][j][1]); //=>max(保持清醒状态,从睡眠中醒过来) dp[pos][j][1]=max(dp[pos^1][j-1][0], j>1?dp[pos^1][j-1][1]+array[i]:0); //=>max(从这点开始睡,在这点接着睡) } pos^=1; } if(!ring) return max(dp[pos^1][b][0],dp[pos^1][b][1]); else return dp[pos^1][b][1]; } int main() { freopen("input.txt","r",stdin); while(input(n>>b)) { int ans=-INF; memset(dp,0,sizeof(dp)); for(int i=0;i<n;i++) input(array[i]); ans=max(ans,slove(false));//普通线性解 memset(dp,0,sizeof(dp)); //去环文艺解法 //Eg. 有4个时间段 //把环展开成线: // Nr.0 1 2 3 | 0 1 2 3 // 0 1 2 3 | 4 5 6 7 //如果属于环状情况,那么,在4点必为深睡眠 dp[1][1][1]=array[0];//预处理:在3点处迷糊,4点睡着 ans=max(ans,slove(true)); print(ans);//213输出答案 } return 0; }
[ "mail.kuuy@gmail.com" ]
mail.kuuy@gmail.com
c513386e87e70d06884e77cb46d2fac2654c79a2
9515e3321c33709258e4686a7cd71e98a8c3a03e
/NfdcAppCore/ViewFactory.h
114eabb82848ffd6e252ddb3929843d3cdb2863f
[ "Apache-2.0" ]
permissive
Mason-Wmx/ViewFramework
f9bc534df86f5cf640a9dbf963b9ea17a8e93562
d8117adc646c369ad29d64477788514c7a75a797
refs/heads/main
2023-06-29T04:12:37.042638
2021-07-28T09:26:55
2021-07-28T09:26:55
374,267,631
1
0
null
null
null
null
UTF-8
C++
false
false
3,338
h
#pragma once #include "stdafx.h" #include "export.h" #include <vtkSmartPointer.h> #include <vtkActor.h> #include <vtkLookupTable.h> #include "ViewData.h" #include <headers/ObjectId.h> #include "DocCommand.h" namespace SIM { class Object; class View3D; class ViewActor; class NFDCAPPCORE_EXPORT ViewFactory { public: ViewFactory(View3D& view3D, std::string objectType); ViewFactory(View3D& view3D); virtual ~ViewFactory(void); std::unordered_set<std::string>& GetObjectTypes(){ return _types; } virtual std::shared_ptr<ViewActor> CreateViewActor(); virtual vtkSmartPointer<vtkProp> AddObjectToActorGeometry(ObjectId objId, ViewActor& viewActor); virtual vtkSmartPointer<vtkProp> GenerateActorForViewActor(ViewActor& viewActor); virtual vtkSmartPointer<vtkProp> GenerateActorForObject(Object& obj); virtual void RemoveGeometryForObject(ObjectId id, ViewActor& viewActor); virtual bool IsViewActorValid(Object& object, ViewActor& actor); virtual void SetViewActorData(Object& object, ViewActor& actor); virtual void Update(vtkActor& existingActor); virtual void Update(ViewActor& actor){} virtual void Update(ViewActor& actor, ObjectId id,const std::string& context) {} virtual bool RegenerateViewActorOnUpdate(const std::string& context) { return false; } virtual bool CreateNewGeometryForSelection(){ return false; } virtual void SetColor(ViewActor& actor,EMode mode); virtual void SetColor(ViewActor& actor,ObjectId objId,EMode mode, std::string selectionContext); virtual void UpdateColor(ViewActor& actor); virtual void Zoomed(ViewActor& actor, double height, int screenHeight){} virtual void CameraChanged(ViewActor& actor, vtkCamera* camera){} virtual bool IsVisible(ViewActor& actor){return true;} virtual void SelectionContextChanged(ViewActor& actor, const std::string& context); virtual bool OwnPickMechanism(){ return false; } virtual bool Pick( ViewActor& actor,Vec3 & ptStart, Vec3 & ptEnd, Vec3 & crossPt, ObjectId& result){ return false; } virtual void PickArea( ViewActor& actor, int* min, int* max, bool respectBoundCells, vtkPlanes* frustum, std::unordered_set<ObjectId> result) {} virtual std::vector<std::string> GetContextCommands(Object& obj); virtual bool IsObjectVisible(ObjectId objId); virtual int GetRenderer(ViewActor& actor) { return 0; } virtual bool CanBeHidden(Object& obj) { return false; } virtual bool UseLocatorForSelection(int actorIndex) { return true; } protected: virtual vtkSmartPointer<vtkProp> CreateActor(Object& obj, ViewActor * viewActor, vtkProp* existingActor) = 0; virtual vtkSmartPointer<vtkProp> CreateActor(ViewActor& viewActor); virtual vtkSmartPointer<vtkProp> CreateEmptyActor(RenderProps* renderProps = nullptr, int trianglesCount = -1, int pointsCount = -1); vtkSmartPointer<vtkLookupTable> CreateLookupTable(int colorNumbers = 1); virtual RenderProps& GetRenderProps(int actorIndex = 0); void AddAttribute(vtkPolyDataMapper* mapper, vtkPolyData* trianglePolyData, int numberOfComponents, const char* name, vtkAbstractArray* array = nullptr); void AddTriangle(vtkCellArray* vtktriangles,int n1, int n2, int n3); void AppendPolyData(vtkPolyData * from, vtkPolyData * to, double xTrans = 0); View3D& _view3D; std::unordered_set<std::string> _types; }; }
[ "mingxin.wang@peraglobal.com" ]
mingxin.wang@peraglobal.com
323669ad14835764711da0d9ab96d63704ce09d4
000f594afc9880aaae9e1cdc44083f993e9c1358
/Sample_buffer.h
786c04eaf69d92a0903bc712a0b1766f3c175ef6
[]
no_license
davidanew/synth_rtos
b061920703a07805f4cabca121b96bd440c1fc0c
2889489dbc2e17ba6b896fbfb9115274d04eb69f
refs/heads/master
2020-06-29T22:11:43.071459
2019-11-20T09:45:08
2019-11-20T09:45:08
200,638,180
2
1
null
null
null
null
UTF-8
C++
false
false
855
h
#pragma once //This is a buffer between the sample calculation class and the ISR sample output //It is needed as sample calculation is not running all the time //TODO: This doesn't need to to be extern'd extern "C" { #include <stm32f4xx_hal.h> } #include <array> //When the sample is recieved it may not be valid if the buffer is empty //So a validity is needed //TODO: Look at std::optional for this struct Float_optional { float value; bool valid; }; //40 samples per tick //At worst the sample calculator should be running 50% of the time //This should ne enough #define SAMPLE_BUFFER_LENGTH 256 class Sample_buffer { static std::array<float, SAMPLE_BUFFER_LENGTH> buffer; static uint32_t last_output_index; static uint32_t last_input_index; public: static bool add_sample(const float sample); static Float_optional get_next_sample(); };
[ "46327493+davidanew@users.noreply.github.com" ]
46327493+davidanew@users.noreply.github.com
7f790460a0982e1f26bd803869d07fc50e568cfc
e76ea38dbe5774fccaf14e1a0090d9275cdaee08
/src/content/zygote/zygote_main_linux.cc
503b3487f470dc6ddc78a800e41a646bcc9d4bd6
[ "BSD-3-Clause" ]
permissive
eurogiciel-oss/Tizen_Crosswalk
efc424807a5434df1d5c9e8ed51364974643707d
a68aed6e29bd157c95564e7af2e3a26191813e51
refs/heads/master
2021-01-18T19:19:04.527505
2014-02-06T13:43:21
2014-02-06T13:43:21
16,070,101
1
3
null
null
null
null
UTF-8
C++
false
false
18,941
cc
// 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. #include "content/zygote/zygote_main.h" #include <dlfcn.h> #include <fcntl.h> #include <pthread.h> #include <stdio.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "base/basictypes.h" #include "base/command_line.h" #include "base/linux_util.h" #include "base/native_library.h" #include "base/pickle.h" #include "base/posix/eintr_wrapper.h" #include "base/posix/unix_domain_socket_linux.h" #include "base/rand_util.h" #include "base/sys_info.h" #include "build/build_config.h" #include "content/common/child_process_sandbox_support_impl_linux.h" #include "content/common/font_config_ipc_linux.h" #include "content/common/pepper_plugin_list.h" #include "content/common/sandbox_linux.h" #include "content/common/zygote_commands_linux.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "content/public/common/pepper_plugin_info.h" #include "content/public/common/sandbox_linux.h" #include "content/public/common/zygote_fork_delegate_linux.h" #include "content/zygote/zygote_linux.h" #include "crypto/nss_util.h" #include "sandbox/linux/services/libc_urandom_override.h" #include "sandbox/linux/suid/client/setuid_sandbox_client.h" #include "third_party/icu/source/i18n/unicode/timezone.h" #include "third_party/skia/include/ports/SkFontConfigInterface.h" #if defined(OS_LINUX) #include <sys/epoll.h> #include <sys/prctl.h> #include <sys/signal.h> #else #include <signal.h> #endif #if defined(ENABLE_WEBRTC) #include "third_party/libjingle/overrides/init_webrtc.h" #endif namespace content { // See http://code.google.com/p/chromium/wiki/LinuxZygote static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output, char* timezone_out, size_t timezone_out_len) { Pickle request; request.WriteInt(LinuxSandbox::METHOD_LOCALTIME); request.WriteString( std::string(reinterpret_cast<char*>(&input), sizeof(input))); uint8_t reply_buf[512]; const ssize_t r = UnixDomainSocket::SendRecvMsg( GetSandboxFD(), reply_buf, sizeof(reply_buf), NULL, request); if (r == -1) { memset(output, 0, sizeof(struct tm)); return; } Pickle reply(reinterpret_cast<char*>(reply_buf), r); PickleIterator iter(reply); std::string result, timezone; if (!reply.ReadString(&iter, &result) || !reply.ReadString(&iter, &timezone) || result.size() != sizeof(struct tm)) { memset(output, 0, sizeof(struct tm)); return; } memcpy(output, result.data(), sizeof(struct tm)); if (timezone_out_len) { const size_t copy_len = std::min(timezone_out_len - 1, timezone.size()); memcpy(timezone_out, timezone.data(), copy_len); timezone_out[copy_len] = 0; output->tm_zone = timezone_out; } else { output->tm_zone = NULL; } } static bool g_am_zygote_or_renderer = false; // Sandbox interception of libc calls. // // Because we are running in a sandbox certain libc calls will fail (localtime // being the motivating example - it needs to read /etc/localtime). We need to // intercept these calls and proxy them to the browser. However, these calls // may come from us or from our libraries. In some cases we can't just change // our code. // // It's for these cases that we have the following setup: // // We define global functions for those functions which we wish to override. // Since we will be first in the dynamic resolution order, the dynamic linker // will point callers to our versions of these functions. However, we have the // same binary for both the browser and the renderers, which means that our // overrides will apply in the browser too. // // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or // renderer process. It's set in ZygoteMain and inherited by the renderers when // they fork. (This means that it'll be incorrect for global constructor // functions and before ZygoteMain is called - beware). // // Our replacement functions can check this global and either proxy // the call to the browser over the sandbox IPC // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the // current module. // // Other avenues: // // Our first attempt involved some assembly to patch the GOT of the current // module. This worked, but was platform specific and doesn't catch the case // where a library makes a call rather than current module. // // We also considered patching the function in place, but this would again by // platform specific and the above technique seems to work well enough. typedef struct tm* (*LocaltimeFunction)(const time_t* timep); typedef struct tm* (*LocaltimeRFunction)(const time_t* timep, struct tm* result); static pthread_once_t g_libc_localtime_funcs_guard = PTHREAD_ONCE_INIT; static LocaltimeFunction g_libc_localtime; static LocaltimeFunction g_libc_localtime64; static LocaltimeRFunction g_libc_localtime_r; static LocaltimeRFunction g_libc_localtime64_r; static void InitLibcLocaltimeFunctions() { g_libc_localtime = reinterpret_cast<LocaltimeFunction>( dlsym(RTLD_NEXT, "localtime")); g_libc_localtime64 = reinterpret_cast<LocaltimeFunction>( dlsym(RTLD_NEXT, "localtime64")); g_libc_localtime_r = reinterpret_cast<LocaltimeRFunction>( dlsym(RTLD_NEXT, "localtime_r")); g_libc_localtime64_r = reinterpret_cast<LocaltimeRFunction>( dlsym(RTLD_NEXT, "localtime64_r")); if (!g_libc_localtime || !g_libc_localtime_r) { // http://code.google.com/p/chromium/issues/detail?id=16800 // // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces // it with a version which doesn't work. In this case we'll get a NULL // result. There's not a lot we can do at this point, so we just bodge it! LOG(ERROR) << "Your system is broken: dlsym doesn't work! This has been " "reported to be caused by Nvidia's libGL. You should expect" " time related functions to misbehave. " "http://code.google.com/p/chromium/issues/detail?id=16800"; } if (!g_libc_localtime) g_libc_localtime = gmtime; if (!g_libc_localtime64) g_libc_localtime64 = g_libc_localtime; if (!g_libc_localtime_r) g_libc_localtime_r = gmtime_r; if (!g_libc_localtime64_r) g_libc_localtime64_r = g_libc_localtime_r; } // Define localtime_override() function with asm name "localtime", so that all // references to localtime() will resolve to this function. Notice that we need // to set visibility attribute to "default" to export the symbol, as it is set // to "hidden" by default in chrome per build/common.gypi. __attribute__ ((__visibility__("default"))) struct tm* localtime_override(const time_t* timep) __asm__ ("localtime"); __attribute__ ((__visibility__("default"))) struct tm* localtime_override(const time_t* timep) { if (g_am_zygote_or_renderer) { static struct tm time_struct; static char timezone_string[64]; ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string, sizeof(timezone_string)); return &time_struct; } else { CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard, InitLibcLocaltimeFunctions)); return g_libc_localtime(timep); } } // Use same trick to override localtime64(), localtime_r() and localtime64_r(). __attribute__ ((__visibility__("default"))) struct tm* localtime64_override(const time_t* timep) __asm__ ("localtime64"); __attribute__ ((__visibility__("default"))) struct tm* localtime64_override(const time_t* timep) { if (g_am_zygote_or_renderer) { static struct tm time_struct; static char timezone_string[64]; ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string, sizeof(timezone_string)); return &time_struct; } else { CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard, InitLibcLocaltimeFunctions)); return g_libc_localtime64(timep); } } __attribute__ ((__visibility__("default"))) struct tm* localtime_r_override(const time_t* timep, struct tm* result) __asm__ ("localtime_r"); __attribute__ ((__visibility__("default"))) struct tm* localtime_r_override(const time_t* timep, struct tm* result) { if (g_am_zygote_or_renderer) { ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0); return result; } else { CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard, InitLibcLocaltimeFunctions)); return g_libc_localtime_r(timep, result); } } __attribute__ ((__visibility__("default"))) struct tm* localtime64_r_override(const time_t* timep, struct tm* result) __asm__ ("localtime64_r"); __attribute__ ((__visibility__("default"))) struct tm* localtime64_r_override(const time_t* timep, struct tm* result) { if (g_am_zygote_or_renderer) { ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0); return result; } else { CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard, InitLibcLocaltimeFunctions)); return g_libc_localtime64_r(timep, result); } } #if defined(ENABLE_PLUGINS) // Loads the (native) libraries but does not initialize them (i.e., does not // call PPP_InitializeModule). This is needed by the zygote on Linux to get // access to the plugins before entering the sandbox. void PreloadPepperPlugins() { std::vector<PepperPluginInfo> plugins; ComputePepperPluginList(&plugins); for (size_t i = 0; i < plugins.size(); ++i) { if (!plugins[i].is_internal && plugins[i].is_sandboxed) { std::string error; base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path, &error); DLOG_IF(WARNING, !library) << "Unable to load plugin " << plugins[i].path.value() << " " << error; (void)library; // Prevent release-mode warning. } } } #endif // This function triggers the static and lazy construction of objects that need // to be created before imposing the sandbox. static void PreSandboxInit() { base::RandUint64(); base::SysInfo::AmountOfPhysicalMemory(); base::SysInfo::MaxSharedMemorySize(); // ICU DateFormat class (used in base/time_format.cc) needs to get the // Olson timezone ID by accessing the zoneinfo files on disk. After // TimeZone::createDefault is called once here, the timezone ID is // cached and there's no more need to access the file system. scoped_ptr<icu::TimeZone> zone(icu::TimeZone::createDefault()); #if defined(USE_NSS) // NSS libraries are loaded before sandbox is activated. This is to allow // successful initialization of NSS which tries to load extra library files. crypto::LoadNSSLibraries(); #elif defined(USE_OPENSSL) // OpenSSL is intentionally not supported in the sandboxed processes, see // http://crbug.com/99163. If that ever changes we'll likely need to init // OpenSSL here (at least, load the library and error strings). #else // It's possible that another hypothetical crypto stack would not require // pre-sandbox init, but more likely this is just a build configuration error. #error Which SSL library are you using? #endif #if defined(ENABLE_PLUGINS) // Ensure access to the Pepper plugins before the sandbox is turned on. PreloadPepperPlugins(); #endif #if defined(ENABLE_WEBRTC) InitializeWebRtcModule(); #endif SkFontConfigInterface::SetGlobal( new FontConfigIPC(GetSandboxFD()))->unref(); } // Do nothing here static void SIGCHLDHandler(int signal) { } // The current process will become a process reaper like init. // We fork a child that will continue normally, when it dies, we can safely // exit. // We need to be careful we close the magic kZygoteIdFd properly in the parent // before this function returns. static bool CreateInitProcessReaper() { int sync_fds[2]; // We want to use send, so we can't use a pipe if (socketpair(AF_UNIX, SOCK_STREAM, 0, sync_fds)) { LOG(ERROR) << "Failed to create socketpair"; return false; } // We use normal fork, not the ForkDelegate in this case since we are not a // true Zygote yet. pid_t child_pid = fork(); if (child_pid == -1) { (void) HANDLE_EINTR(close(sync_fds[0])); (void) HANDLE_EINTR(close(sync_fds[1])); return false; } if (child_pid) { // We are the parent, assuming the role of an init process. // The disposition for SIGCHLD cannot be SIG_IGN or wait() will only return // once all of our childs are dead. Since we're init we need to reap childs // as they come. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = &SIGCHLDHandler; CHECK(sigaction(SIGCHLD, &action, NULL) == 0); (void) HANDLE_EINTR(close(sync_fds[0])); shutdown(sync_fds[1], SHUT_RD); // This "magic" socket must only appear in one process. (void) HANDLE_EINTR(close(kZygoteIdFd)); // Tell the child to continue CHECK(HANDLE_EINTR(send(sync_fds[1], "C", 1, MSG_NOSIGNAL)) == 1); (void) HANDLE_EINTR(close(sync_fds[1])); for (;;) { // Loop until we have reaped our one natural child siginfo_t reaped_child_info; int wait_ret = HANDLE_EINTR(waitid(P_ALL, 0, &reaped_child_info, WEXITED)); if (wait_ret) _exit(1); if (reaped_child_info.si_pid == child_pid) { int exit_code = 0; // We're done waiting if (reaped_child_info.si_code == CLD_EXITED) { exit_code = reaped_child_info.si_status; } // Exit with the same exit code as our parent. This is most likely // useless. _exit with 0 if we got signaled. _exit(exit_code); } } } else { // The child needs to wait for the parent to close kZygoteIdFd to avoid a // race condition (void) HANDLE_EINTR(close(sync_fds[1])); shutdown(sync_fds[0], SHUT_WR); char should_continue; int read_ret = HANDLE_EINTR(read(sync_fds[0], &should_continue, 1)); (void) HANDLE_EINTR(close(sync_fds[0])); if (read_ret == 1) return true; else return false; } } // This will set the *using_suid_sandbox variable to true if the SUID sandbox // is enabled. This does not necessarily exclude other types of sandboxing. static bool EnterSuidSandbox(LinuxSandbox* linux_sandbox, bool* using_suid_sandbox, bool* has_started_new_init) { *using_suid_sandbox = false; *has_started_new_init = false; sandbox::SetuidSandboxClient* setuid_sandbox = linux_sandbox->setuid_sandbox_client(); if (!setuid_sandbox) return false; PreSandboxInit(); // Check that the pre-sandbox initialization didn't spawn threads. DCHECK(linux_sandbox->IsSingleThreaded()); if (setuid_sandbox->IsSuidSandboxChild()) { // Use the SUID sandbox. This still allows the seccomp sandbox to // be enabled by the process later. *using_suid_sandbox = true; if (!setuid_sandbox->IsSuidSandboxUpToDate()) { LOG(WARNING) << "You are using a wrong version of the setuid binary!\n" "Please read " "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment." "\n\n"; } if (!setuid_sandbox->ChrootMe()) return false; if (getpid() == 1) { // The setuid sandbox has created a new PID namespace and we need // to assume the role of init. if (!CreateInitProcessReaper()) { LOG(ERROR) << "Error creating an init process to reap zombies"; return false; } *has_started_new_init = true; } #if !defined(OS_OPENBSD) // Previously, we required that the binary be non-readable. This causes the // kernel to mark the process as non-dumpable at startup. The thinking was // that, although we were putting the renderers into a PID namespace (with // the SUID sandbox), they would nonetheless be in the /same/ PID // namespace. So they could ptrace each other unless they were non-dumpable. // // If the binary was readable, then there would be a window between process // startup and the point where we set the non-dumpable flag in which a // compromised renderer could ptrace attach. // // However, now that we have a zygote model, only the (trusted) zygote // exists at this point and we can set the non-dumpable flag which is // inherited by all our renderer children. // // Note: a non-dumpable process can't be debugged. To debug sandbox-related // issues, one can specify --allow-sandbox-debugging to let the process be // dumpable. const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) { prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) { LOG(ERROR) << "Failed to set non-dumpable flag"; return false; } } #endif } return true; } bool ZygoteMain(const MainFunctionParams& params, ZygoteForkDelegate* forkdelegate) { g_am_zygote_or_renderer = true; sandbox::InitLibcUrandomOverrides(); LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance(); // This will pre-initialize the various sandboxes that need it. linux_sandbox->PreinitializeSandbox(); if (forkdelegate != NULL) { VLOG(1) << "ZygoteMain: initializing fork delegate"; forkdelegate->Init(GetSandboxFD()); } else { VLOG(1) << "ZygoteMain: fork delegate is NULL"; } // Turn on the sandbox. bool using_suid_sandbox = false; bool has_started_new_init = false; if (!EnterSuidSandbox(linux_sandbox, &using_suid_sandbox, &has_started_new_init)) { LOG(FATAL) << "Failed to enter sandbox. Fail safe abort. (errno: " << errno << ")"; return false; } sandbox::SetuidSandboxClient* setuid_sandbox = linux_sandbox->setuid_sandbox_client(); if (setuid_sandbox->IsInNewPIDNamespace() && !has_started_new_init) { LOG(ERROR) << "The SUID sandbox created a new PID namespace but Zygote " "is not the init process. Please, make sure the SUID " "binary is up to date."; } int sandbox_flags = linux_sandbox->GetStatus(); Zygote zygote(sandbox_flags, forkdelegate); // This function call can return multiple times, once per fork(). return zygote.ProcessRequests(); } } // namespace content
[ "ronan@fridu.net" ]
ronan@fridu.net
9b9ef894c3e6efda0bbeeee779125392de769d11
2bfddaf9c0ceb7bf46931f80ce84a829672b0343
/src/xtd.drawing/src/xtd/drawing/red_colors.cpp
c12f973ca1f1998b1590e006a3a499110497a0bf
[ "MIT" ]
permissive
gammasoft71/xtd
c6790170d770e3f581b0f1b628c4a09fea913730
ecd52f0519996b96025b196060280b602b41acac
refs/heads/master
2023-08-19T09:48:09.581246
2023-08-16T20:52:11
2023-08-16T20:52:11
170,525,609
609
53
MIT
2023-05-06T03:49:33
2019-02-13T14:54:22
C++
UTF-8
C++
false
false
1,762
cpp
#include "../../../include/xtd/drawing/red_colors.h" using namespace std; using namespace xtd; using namespace xtd::drawing; color red_colors::crimson() noexcept { return color::from_known_color(known_color::crimson); } color red_colors::dark_red() noexcept { return color::from_known_color(known_color::dark_red); } color red_colors::dark_salmon() noexcept { return color::from_known_color(known_color::dark_salmon); } color red_colors::firebrick() noexcept { return color::from_known_color(known_color::firebrick); } color red_colors::indian_red() noexcept { return color::from_known_color(known_color::indian_red); } color red_colors::light_coral() noexcept { return color::from_known_color(known_color::light_coral); } color red_colors::light_salmon() noexcept { return color::from_known_color(known_color::light_salmon); } color red_colors::red() noexcept { return color::from_known_color(known_color::red); } color red_colors::salmon() noexcept { return color::from_known_color(known_color::salmon); } const vector<color>& red_colors::get_colors() noexcept { static vector colors {red_colors::dark_red(), red_colors::red(), red_colors::firebrick(), red_colors::crimson(), red_colors::indian_red(), red_colors::light_coral(), red_colors::salmon(), red_colors::dark_salmon(), red_colors::light_salmon()}; return colors; } const vector<ustring>& red_colors::get_color_names() noexcept { static vector color_names {red_colors::dark_red().name(), red_colors::red().name(), red_colors::firebrick().name(), red_colors::crimson().name(), red_colors::indian_red().name(), red_colors::light_coral().name(), red_colors::salmon().name(), red_colors::dark_salmon().name(), red_colors::light_salmon().name()}; return color_names; }
[ "gammasoft71@gmail.com" ]
gammasoft71@gmail.com
6022e41f78e439c86bb46cbb3caadbc1474d3b5a
26fd0a6a093196795f59edfa3f102611b661cea0
/node_modules/v8-profiler-node8/src/cpu_profiler.h
c70885631335adc422192f8ca27834eee1da4c1e
[ "BSD-2-Clause" ]
permissive
HHchhhhh/RuanGong
e257f07f1b6188195b566e757246d0bad9a6b0a1
65de30bc94f529b2192409c38951f28592510dca
refs/heads/master
2023-09-01T02:28:41.343927
2021-10-21T09:50:07
2021-10-21T09:50:07
417,859,047
1
0
null
null
null
null
UTF-8
C++
false
false
520
h
#ifndef NODE_CPU_PROFILER_ #define NODE_CPU_PROFILER_ #include "v8-profiler.h" #include "node.h" #include "nan.h" namespace nodex { class CpuProfiler { public: static void Initialize(v8::Local<v8::Object> target); CpuProfiler(); virtual ~CpuProfiler(); protected: static NAN_METHOD(StartProfiling); static NAN_METHOD(StopProfiling); static NAN_METHOD(SetSamplingInterval); static NAN_METHOD(CollectSample); }; } //namespace nodex #endif // NODE_CPU_PROFILER_H
[ "2585917756@qq.com" ]
2585917756@qq.com
824c75f8845a6e9f6f63bae171f2f2d0a60c2100
b7161040ab4096ffac69723a8f91e21d0a90f80d
/9.0/mylab_d3d9/mylab_d3d9/Scene_Lightbox.cpp
6182a031939c97ea46f7c4ac1479101a30a923a5
[]
no_license
lcsszz/directx_9
3beac2f1c4614f4399cca3506b56c703e05fb153
d4dc286f97cf986fcdbafa63dee2df0787c8fa54
refs/heads/master
2021-01-10T09:16:38.835994
2015-11-11T08:03:59
2015-11-11T08:03:59
45,896,269
0
0
null
null
null
null
GB18030
C++
false
false
3,144
cpp
#include "StdAfx.h" #include "Scene_Lightbox.h" #include "Light.h" #include "QuadInlight.h" CScene_Lightbox::CScene_Lightbox(void): m_pLight(NULL), m_pQuadInlight(NULL) { } CScene_Lightbox::~CScene_Lightbox(void) { SAFE_RELEASE( m_pSphereMesh ); SAFE_RELEASE( m_pConeMesh ); } void CScene_Lightbox::Init( LPDIRECT3DDEVICE9 pDevice) { m_pDevice = pDevice; m_pLight = new CLight; m_pLight->Init(m_pDevice); m_pQuadInlight = new CQuadInlight; m_pQuadInlight->Init(m_pDevice); D3DXCreateSphere( m_pDevice, 0.25f, 20, 20, &m_pSphereMesh, NULL ); D3DXCreateCylinder( m_pDevice, 0.0f, 0.25f, 0.5f, 20, 20, &m_pConeMesh, NULL ); m_pDevice->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE); } void CScene_Lightbox::Update(float fElapsedTime) { //可以修改 D3DXMATRIX matRroj; //投影矩阵 D3DXMatrixPerspectiveFovLH( &matRroj, D3DX_PI/4, 4.f/3.f, 1.f, 500.0f ); //张角 宽高比 最近距离 最远距离 m_pDevice->SetTransform(D3DTS_PROJECTION, &matRroj); // 更新视矩阵 D3DXMATRIX matView; D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3(13.0f, 13.0f, 13.0f), &D3DXVECTOR3(0.0f, 0.0f, 0.0f), &D3DXVECTOR3(0.0f, 1.0f, 0.0f) ); //摄像机的坐标系 起点 终点 y轴 m_pDevice->SetTransform(D3DTS_VIEW, &matView); m_pLight->Update(fElapsedTime); } void CScene_Lightbox::Render() { m_pLight->Render(); D3DXMATRIX matWorld; D3DXMATRIX matTrans; D3DXMATRIX matRotate; // 绘制地面 D3DXMatrixTranslation( &matTrans, -5.0f, -5.0f, -5.0f ); D3DXMatrixRotationZ( &matRotate, 0.0f ); matWorld = matRotate * matTrans; m_pQuadInlight->Render( matWorld ); //m_pQuadSimple->Render(matWorld); // 绘制墙体 D3DXMatrixTranslation( &matTrans, -5.0f,5.0f, -5.0f ); D3DXMatrixRotationZ( &matRotate, -D3DXToRadian(90.0) ); matWorld = matRotate * matTrans; m_pQuadInlight->Render( matWorld ); // 绘制墙体 D3DXMatrixTranslation( &matTrans, -5.0f, 5.0f, -5.0f ); D3DXMatrixRotationX( &matRotate, D3DXToRadian(90.0) ); matWorld = matRotate * matTrans; m_pQuadInlight->Render( matWorld ); //设置光源的位置和方向 if( m_pLight->m_lightType == LIGHT_TYPE_POINT ) { // 设置位置 D3DXMatrixTranslation( &matWorld, m_pLight->m_light.Position.x, m_pLight->m_light.Position.y,m_pLight->m_light.Position.z ); m_pDevice->SetTransform( D3DTS_WORLD, &matWorld ); m_pDevice->SetTexture(0, NULL); m_pSphereMesh->DrawSubset(0); } else { // 设置位置及方向 D3DXVECTOR3 vecFrom( m_pLight->m_light.Position.x, m_pLight->m_light.Position.y, m_pLight->m_light.Position.z ); D3DXVECTOR3 vecAt( m_pLight->m_light.Position.x + m_pLight->m_light.Direction.x, m_pLight->m_light.Position.y + m_pLight->m_light.Direction.y, m_pLight->m_light.Position.z + m_pLight->m_light.Direction.z ); D3DXVECTOR3 vecUp( 0.0f, 1.0f, 0.0f ); D3DXMATRIX matWorldInv; D3DXMatrixLookAtLH( &matWorldInv, &vecFrom, &vecAt, &vecUp); D3DXMatrixInverse( &matWorld, NULL, &matWorldInv); m_pDevice->SetTransform( D3DTS_WORLD, &matWorld ); m_pDevice->SetTexture(0, NULL); m_pConeMesh->DrawSubset(0); } }
[ "lcsszz@163.com" ]
lcsszz@163.com
10992a720c929eb53f7e3694c2eb68416dc827ea
3745b5d4fb921a1bb703e54c4c059b920f598173
/NewTrainingFramework/Paralelipiped.h
6f24b1fd7d9e130738af7469bc2ff2133ef85021
[]
no_license
Andrei243/Game-Engine-Gameloft
ed1fc7a8f9f495a462f6060522bf29d543b6d8dd
39e9eeea01f0bea902729cc13a106a5ad3b74fac
refs/heads/master
2020-05-12T19:13:41.445159
2020-05-06T04:38:38
2020-05-06T04:38:38
181,542,280
0
0
null
null
null
null
UTF-8
C++
false
false
387
h
#pragma once #include <iostream> #include "Vertex.h" #include <vector> class Paralelipiped { public: float minx, miny, minz, maxx, maxy, maxz; std::string tag; static bool verificaColiziune(Paralelipiped x1, Paralelipiped x2); Paralelipiped calculeazaParalelipiped(Vector3 rotatie, Vector3 scale,Vector3 pozitie); Paralelipiped() {}; Paralelipiped(std::vector<Vertex> vertexi); };
[ "andrei243.nma@gmail.com" ]
andrei243.nma@gmail.com
44577874bc8c2235445f35feb40489475b53a89e
70abdf4e8e2e18318b1c451f1ecb8808c3af1153
/CBY_Projects/CBY_2D_DX_GameProjet/C_Move.h
6b0825f471391b62f1ed77bd47ce47d24e64ee8d
[]
no_license
Byeng-Yong-Choi/Byeng_Yong-Game
0815e0944cd8c7d8d0093fc1d58662f5bd75845f
0ac592e66f6d895b277ceb2c829338b13b94f14f
refs/heads/master
2023-03-11T07:12:34.809028
2021-02-22T19:10:29
2021-02-22T19:10:29
276,743,710
0
0
null
null
null
null
UTF-8
C++
false
false
212
h
#pragma once #include "C_ObjectMT.h" class C_Move :public C_MonsterStateProcess { public: public: void Process(std::vector<std::shared_ptr<C_Tower>>& Tower); public: C_Move(C_Monster* host); ~C_Move(); };
[ "cby0109@naver.com" ]
cby0109@naver.com
388876f3cd47ca4b0a0eaeb17ecfea27af199c1f
7ef1c8f1faf85b95681a0d8d719cc509f472c930
/03_/Chapter/3_3_tryThis.cpp
485aa94fb243648bc95b6ba083077968f49aacad
[]
no_license
karlh18/Cpp
766470db837f03a3f33b92c5c978272858328c95
95fb188cedddb74f48a9e4f887720aa5243653b1
refs/heads/master
2023-03-10T13:46:32.852111
2021-02-25T10:45:13
2021-02-25T10:45:13
339,972,159
0
0
null
null
null
null
UTF-8
C++
false
false
294
cpp
#include <iostream> using namespace std; double ageInMonths(double age){ return age*12; } int main(){ cout << "Please enter your first name and then your age\n"; string name; double age; cin >> name >> age; cout << "name: " << name << " age: in months: " << ageInMonths(age) << '\n'; }
[ "karlh18@student.sdu.datlassian.com" ]
karlh18@student.sdu.datlassian.com
51d2de4aac449975f14d5df15ac0f04f8c1f99b6
bfdbc93e78f72a212a1c077a2b14b90a671a03b0
/step5.pi/simulation.hpp
2950af81ed3f83f7fa4789a846bec06920a0d2a1
[]
no_license
galexv/ALPSCore_tutorial
1cb92a9ada1f4887751e4edf8e279f03d4c5ff44
d668e68b8a00a4462c82f3af85f9d39897cc06d7
refs/heads/master
2021-01-10T11:14:04.100048
2016-03-25T01:52:16
2016-03-25T01:52:16
49,966,710
0
0
null
null
null
null
UTF-8
C++
false
false
880
hpp
#include <alps/mc/mcbase.hpp> #include <alps/mc/mpiadapter.hpp> #include <alps/accumulators.hpp> class MySimulation : public alps::mcbase { private: long burnin_; long maxcount_; bool verbose_; double stepsize_; long istep_; double x_,y_; public: // These we need for the simulation. static bool is_inside_area(double x, double y); static double objective_function(double x, double y); // Accumulator type to collect observables. typedef alps::accumulators::FullBinningAccumulator<double> my_accumulator_type; MySimulation(const parameters_type& params, std::size_t seed_offset=0); void update(); void measure(); double fraction_completed() const; static parameters_type& define_parameters(parameters_type& params); }; typedef alps::mcmpiadapter<MySimulation> MyMpiSimulation;
[ "galexv@umich.edu" ]
galexv@umich.edu
55c13b10e465fdd160727acd79825155e287d137
3fb7acf6e12a63b71ca0cd7120232c780fd69e43
/src/AnimationSound.cpp
c0e79321716a232f0140c6657a0f607b4f5e4f52
[ "MIT" ]
permissive
mbasaglia/my-little-investigations
c678e3ee6c2c7079969ee7d80a0ef41864658d74
81634075b6d064d9734e57885899a68f5f1a0f6e
refs/heads/master
2021-01-14T12:31:06.586470
2014-04-11T15:17:33
2014-04-11T15:17:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,542
cpp
/** * Represents a sound to be played during an animation. * * @author GabuEx, dawnmew * @since 1.0 * * Licensed under the MIT License. * * Copyright (c) 2014 Equestrian Dreamers * * 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 "AnimationSound.h" #include "CaseInformation/Case.h" AnimationSound * AnimationSound::LoadSoundFromXml(XmlReader *pReader) { if (pReader->ElementExists("HoofstepSound")) { return new HoofstepSound(pReader); } else if (pReader->ElementExists("SpecifiedSound")) { return new SpecifiedSound(pReader); } else { throw Exception("Invalid sound type."); } } HoofstepSound::HoofstepSound() { } HoofstepSound::HoofstepSound(XmlReader *pReader) { pReader->StartElement("HoofstepSound"); pReader->EndElement(); } void HoofstepSound::Play(double volume) { Case::GetInstance()->GetAudioManager()->PlayRandomHoofstepSound("Gravel", volume); } AnimationSound * HoofstepSound::Clone() { AnimationSound *pSound = new HoofstepSound(); return pSound; } SpecifiedSound::SpecifiedSound(string sfxId) { this->sfxId = sfxId; } SpecifiedSound::SpecifiedSound(XmlReader *pReader) { pReader->StartElement("SpecifiedSound"); sfxId = pReader->ReadTextElement("SfxId"); pReader->EndElement(); } void SpecifiedSound::Play(double volume) { playSound(sfxId, volume); } AnimationSound * SpecifiedSound::Clone() { AnimationSound *pSound = new SpecifiedSound(sfxId); return pSound; }
[ "gabumon36@hotmail.com" ]
gabumon36@hotmail.com
01c69a083bb8ea8799757ac3024deed4692475a7
3471cdb1c6e31e2e891f57b20d72ba301c3d4ba7
/Source/PluginProcessor.cpp
f575e950398c3e8fc8c454135579957c5ab79caa
[]
no_license
MatDiaz/RC-Surround
f60d0b0eb0736c2cd503f6271234d0f37f1910cd
c5e7db8b71626e14df43bd4f03c6b47911519000
refs/heads/master
2020-04-02T08:47:18.138392
2019-03-05T04:44:54
2019-03-05T04:44:54
154,261,013
0
0
null
null
null
null
UTF-8
C++
false
false
9,678
cpp
/* ============================================================================== This file was auto-generated! It contains the basic framework code for a JUCE plugin processor. ============================================================================== */ #include "PluginProcessor.h" #include "GUI.h" //============================================================================== PluginAudioProcessor::PluginAudioProcessor() #ifndef JucePlugin_PreferredChannelConfigurations : AudioProcessor(BusesProperties() #if ! JucePlugin_IsMidiEffect #if ! JucePlugin_IsSynth .withInput("Input", AudioChannelSet::create5point1(), true) #endif .withOutput ("Output", AudioChannelSet::stereo(), true) #endif ) #endif { isLoaded = false; shouldProcessHeadphones = false; headphonesReady = false; outputGain = 1; previousOutputGain = 1; } PluginAudioProcessor::~PluginAudioProcessor() { } //============================================================================== const String PluginAudioProcessor::getName() const { return JucePlugin_Name; } bool PluginAudioProcessor::acceptsMidi() const { #if JucePlugin_WantsMidiInput return true; #else return false; #endif } bool PluginAudioProcessor::producesMidi() const { #if JucePlugin_ProducesMidiOutput return true; #else return false; #endif } bool PluginAudioProcessor::isMidiEffect() const { #if JucePlugin_IsMidiEffect return true; #else return false; #endif } double PluginAudioProcessor::getTailLengthSeconds() const { return 0.0; } int PluginAudioProcessor::getNumPrograms() { return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs, // so this should be at least 1, even if you're not really implementing programs. } int PluginAudioProcessor::getCurrentProgram() { return 0; } void PluginAudioProcessor::setCurrentProgram (int index) { } const String PluginAudioProcessor::getProgramName (int index) { return {}; } void PluginAudioProcessor::changeProgramName (int index, const String& newName) { } //============================================================================== void PluginAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock) { convolutionProperties.sampleRate = sampleRate; convolutionProperties.maximumBlockSize = samplesPerBlock; convolutionProperties.numChannels = 2; headphoneConvolutionProperties.sampleRate = sampleRate; headphoneConvolutionProperties.maximumBlockSize = samplesPerBlock; headphoneConvolutionProperties.numChannels = 1; for (int i = 0; i < 6; i++) { audioBufferList.add(new AudioBuffer<float>); audioBufferList[i]->setSize(1, samplesPerBlock, false, false, false); audioBufferList[i]->clear(); } nBufferL.setSize(1, samplesPerBlock); nBufferL.clear(); nBufferR.setSize(1, samplesPerBlock); nBufferR.clear(); } void PluginAudioProcessor::releaseResources() { // When playback stops, you can use this as an opportunity to free up any // spare memory, etc. } #ifndef JucePlugin_PreferredChannelConfigurations bool PluginAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const { #if JucePlugin_IsMidiEffect ignoreUnused (layouts); return true; #else // This is the place where you check if the layout is supported. // In this template code we only support mono or stereo. if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono() && layouts.getMainOutputChannelSet() != AudioChannelSet::stereo()) return false; // This checks if the input layout matches the output layout #if ! JucePlugin_IsSynth if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet()) return false; #endif return true; #endif } #endif void PluginAudioProcessor::processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiMessages) { ScopedNoDenormals noDenormals; auto totalNumInputChannels = getTotalNumInputChannels(); auto totalNumOutputChannels = getTotalNumOutputChannels(); if (isLoaded && totalNumInputChannels == 6 && totalNumOutputChannels == 2) { for (int i = 0; i < totalNumInputChannels; i++) { const float* channelK = buffer.getReadPointer(i); float* channelN = audioBufferList[i]->getWritePointer(0); memcpy(channelN, channelK, sizeof(float) * buffer.getNumSamples()); AudioBuffer<float> bufferCopy = *audioBufferList[i]; dsp::AudioBlock<float> tempAudioBufferL(*audioBufferList[i]), tempAudioBufferR(bufferCopy); dsp::ProcessContextReplacing<float> ctxL(tempAudioBufferL), ctxR(tempAudioBufferR); convolutionEngineListL[i]->process(ctxL); convolutionEngineListR[i]->process(ctxR); float* channelL = buffer.getWritePointer(0); float* channelR = buffer.getWritePointer(1); for (int j = 0; j < buffer.getNumSamples(); j++) { if (i == 0) channelL[j] = tempAudioBufferL.getSample(0, j); else if (i == 1) channelR[j] = tempAudioBufferR.getSample(0, j); else { channelL[j] += tempAudioBufferL.getSample(0, j); channelR[j] += tempAudioBufferR.getSample(0, j); } } } if (shouldProcessHeadphones && headphonesReady) { float* channelL = buffer.getWritePointer(0); float* channelR = buffer.getWritePointer(1); float* channelNL = nBufferL.getWritePointer(0); float* channelNR = nBufferR.getWritePointer(0); memcpy(channelNL, channelL, sizeof(float) * buffer.getNumSamples()); memcpy(channelNR, channelR, sizeof(float) * buffer.getNumSamples()); dsp::AudioBlock<float> headphoneBufferL(nBufferL), headphoneBufferR(nBufferR); dsp::ProcessContextReplacing<float> ctxxL(headphoneBufferL), ctxxR(headphoneBufferR); headphoneConvolutionEngineL.process(ctxxL); headphoneConvolutionEngineR.process(ctxxR); for (auto i = 0; i < buffer.getNumSamples(); i++) { channelL[i] = headphoneBufferL.getSample(0, i); channelR[i] = headphoneBufferR.getSample(0, i); } } buffer.applyGainRamp(0, buffer.getNumSamples(), previousOutputGain, outputGain); previousOutputGain = outputGain; } } //============================================================================== bool PluginAudioProcessor::hasEditor() const { return true; // (change this to false if you choose to not supply an editor) } AudioProcessorEditor* PluginAudioProcessor::createEditor() { return new PluginAudioProcessorEditor (*this); } //============================================================================== void PluginAudioProcessor::getStateInformation (MemoryBlock& destData) { // You should use this method to store your parameters in the memory block. // You could do that either as raw data, or use the XML or ValueTree classes // as intermediaries to make it easy to save and load complex data. } void PluginAudioProcessor::setStateInformation (const void* data, int sizeInBytes) { // You should use this method to restore your parameters from this memory block, // whose contents will have been created by the getStateInformation() call. } void PluginAudioProcessor::loadImpulseResponseToEngine(AudioBuffer<float>& LoadedIR, int position, double sampleRate, int fileSize) { AudioBuffer<float> tempBufferL, tempBufferR; tempBufferL.setSize(1, fileSize, false, false, false); tempBufferR = tempBufferL; tempBufferL.clear(); tempBufferR.clear(); float* channelL = LoadedIR.getWritePointer(0); float* channelR = LoadedIR.getWritePointer(1); for (int i = 0; i < fileSize; i++) { tempBufferL.setSample(0, i, channelL[i]); tempBufferR.setSample(0, i, channelR[i]); } convolutionEngineListL.add(new dsp::Convolution()); convolutionEngineListL[position]->prepare(convolutionProperties); convolutionEngineListL[position]->copyAndLoadImpulseResponseFromBuffer(tempBufferL, sampleRate, false, false, false, 0); convolutionEngineListR.add(new dsp::Convolution()); convolutionEngineListR[position]->prepare(convolutionProperties); convolutionEngineListR[position]->copyAndLoadImpulseResponseFromBuffer(tempBufferR, sampleRate, false, false, false, 0); } void PluginAudioProcessor::loadImpulseResponseHeadphones(AudioBuffer<float> &LoadedIR, double sampleRate, int fileSize) { AudioBuffer<float> tempBufferL, tempBufferR; tempBufferL.setSize(1, fileSize); tempBufferR = tempBufferL; float* channelL = LoadedIR.getWritePointer(0); float* channelR = LoadedIR.getWritePointer(1); for (int i = 0; i < fileSize; i++) { tempBufferL.setSample(0, i, channelL[i]); tempBufferR.setSample(0, i, channelR[i]); } headphoneConvolutionEngineL.prepare(headphoneConvolutionProperties); headphoneConvolutionEngineL.copyAndLoadImpulseResponseFromBuffer(tempBufferL, sampleRate, false, false, false, 0); headphoneConvolutionEngineR.prepare(headphoneConvolutionProperties); headphoneConvolutionEngineR.copyAndLoadImpulseResponseFromBuffer(tempBufferR, sampleRate, false, false, false, 0); headphonesReady = true; } //============================================================================== // This creates new instances of the plugin.. AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new PluginAudioProcessor(); }
[ "mateoyepes@iMac-de-Mateo.local" ]
mateoyepes@iMac-de-Mateo.local
82bb5a1a035aaf610ed68cbef515eb669ffffa81
58cbd7a2a989a5cb683e714a53e23e5d43afebac
/src/vlMFC/MDIWindow.cpp
861ff1f5ec1929a1bba4abe85ce63e194eba546e
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kmatheussen/Visualization-Library
91711bb067b9bf5da4fbe59dc54cf9a618f92dda
16a3e8105ccd63cd6ca667fa061a63596102ef79
refs/heads/master
2020-12-28T19:57:33.901418
2017-07-05T09:46:22
2017-07-05T09:46:22
16,648,504
1
1
null
null
null
null
UTF-8
C++
false
false
9,602
cpp
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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 OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include "StdAfx.h" #include <vlMFC/MDIWindow.hpp> #include <vlWin32/Win32Window.hpp> #include <vlCore/Log.hpp> #include <vlCore/Say.hpp> #include <vlCore/Time.hpp> #include <shellapi.h> using namespace vl; using namespace vlMFC; //----------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(MDIWindow, CView) ON_WM_CHAR() ON_WM_CLOSE() ON_WM_CREATE() ON_WM_KEYDOWN() ON_WM_KEYUP() ON_WM_LBUTTONDBLCLK() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_MBUTTONDBLCLK() ON_WM_MBUTTONDOWN() ON_WM_MBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_MOUSEWHEEL() ON_WM_PAINT() ON_WM_RBUTTONDBLCLK() ON_WM_RBUTTONDOWN() ON_WM_RBUTTONUP() ON_WM_SIZE() ON_WM_TIMER() ON_WM_DROPFILES() ON_WM_DESTROY() END_MESSAGE_MAP() /* WM_SYSKEYDOWN WM_SYSKEYUP WM_GETICON WM_SETCURSOR WM_SETICON WM_CAPTURECHANGED WM_MOUSEFIRST */ BOOL MDIWindow::PreCreateWindow(CREATESTRUCT & cs) { cs.dwExStyle |= WS_EX_ACCEPTFILES; cs.style |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS; return CView::PreCreateWindow(cs); } //----------------------------------------------------------------------------- MDIWindow::~MDIWindow() { dispatchDestroyEvent(); } //----------------------------------------------------------------------------- void MDIWindow::destroyGLContext() { // wglMakeCurrent(NULL, NULL) not needed if (hwnd()) { if (mHGLRC) { if ( wglDeleteContext(mHGLRC) == FALSE ) { MessageBox( L"OpenGL context creation failed.\n" L"The handle either doesn't specify a valid context or the context is being used by another thread.", L" MDIWindow::destroyGLContext() error!", MB_OK); } mHGLRC = NULL; } if (mHDC) { DeleteDC(mHDC); mHDC = NULL; } } } //----------------------------------------------------------------------------- void MDIWindow::OnDestroy() { dispatchDestroyEvent(); destroyGLContext(); } //----------------------------------------------------------------------------- void MDIWindow::OnPaint() { if (hwnd() && hdc() && hglrc()) dispatchRunEvent(); ValidateRect(NULL); } //----------------------------------------------------------------------------- /*void MDIWindow::OnDraw(CDC *pDC) { }*/ //----------------------------------------------------------------------------- /*void MDIWindow::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { unsigned short unicode_out = 0; vl::EKey key_out = Key_None; vlWin32::translateKeyEvent(nChar, nFlags, unicode_out, key_out); dispatchKeyPressEvent(unicode_out, key_out); }*/ //----------------------------------------------------------------------------- void MDIWindow::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { unsigned short unicode_out = 0; vl::EKey key_out = Key_None; vlWin32::translateKeyEvent(nChar, nFlags, unicode_out, key_out); dispatchKeyPressEvent(unicode_out, key_out); } //----------------------------------------------------------------------------- void MDIWindow::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { unsigned short unicode_out = 0; vl::EKey key_out = Key_None; vlWin32::translateKeyEvent(nChar, nFlags, unicode_out, key_out); dispatchKeyReleaseEvent(unicode_out, key_out); } //----------------------------------------------------------------------------- void MDIWindow::countAndCapture() { mMouseDownCount++; if (mMouseDownCount == 1) ::SetCapture(hwnd()); } //----------------------------------------------------------------------------- void MDIWindow::countAndRelease() { mMouseDownCount--; if (mMouseDownCount <= 0) { ReleaseCapture(); mMouseDownCount = 0; } } //----------------------------------------------------------------------------- void MDIWindow::OnLButtonDblClk(UINT nFlags, CPoint point) { countAndCapture(); dispatchMouseDownEvent( LeftButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnLButtonDown(UINT nFlags, CPoint point) { countAndCapture(); dispatchMouseDownEvent( LeftButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnLButtonUp(UINT nFlags, CPoint point) { countAndRelease(); dispatchMouseUpEvent( LeftButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnMButtonDblClk(UINT nFlags, CPoint point) { countAndCapture(); dispatchMouseDownEvent( MiddleButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnMButtonDown(UINT nFlags, CPoint point) { countAndCapture(); dispatchMouseDownEvent( MiddleButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnMButtonUp(UINT nFlags, CPoint point) { countAndRelease(); dispatchMouseUpEvent( MiddleButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnMouseMove(UINT nFlags, CPoint point) { dispatchMouseMoveEvent( point.x, point.y ); } //----------------------------------------------------------------------------- BOOL MDIWindow::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { dispatchMouseWheelEvent (zDelta/120); return FALSE; } //----------------------------------------------------------------------------- void MDIWindow::OnRButtonDblClk(UINT nFlags, CPoint point) { countAndCapture(); dispatchMouseDownEvent( RightButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnRButtonDown(UINT nFlags, CPoint point) { countAndCapture(); dispatchMouseDownEvent( RightButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnRButtonUp(UINT nFlags, CPoint point) { countAndRelease(); dispatchMouseUpEvent( RightButton, point.x, point.y ); } //----------------------------------------------------------------------------- void MDIWindow::OnDropFiles(HDROP hDrop) { int count = DragQueryFile(hDrop, 0xFFFFFFFF, 0, 0); const int char_count = 1024; std::vector<String> files; for(int i=0; i<count; ++i) { wchar_t file_path[char_count]; memset(file_path, 0, char_count); DragQueryFile(hDrop,i,file_path,char_count); files.push_back(file_path); } dispatchFileDroppedEvent(files); } //----------------------------------------------------------------------------- void MDIWindow::OnSize (UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); if (0 >= cx || 0 >= cy || nType == SIZE_MINIMIZED) return; framebuffer()->setWidth(cx); framebuffer()->setHeight(cy); dispatchResizeEvent(cx, cy); } //-----------------------------------------------------------------------------
[ "michele@visualizationlibrary.com" ]
michele@visualizationlibrary.com
dada4ade72250ff70070add31c0271af4554196e
3588eb4d452e60c042e6d9a6accc5ad90fadc33e
/linux-apps/lucene-r2p2/inc/lucene++/RussianLetterTokenizer.h
5bbe1544627dac889473b51a05b439806494cc12
[ "MIT" ]
permissive
gsol10/r2p2
1ffe658fe36b0b2fd078c076feaf7195fb82e102
de00e7a76564af0e77a49217874cc06e6935f31d
refs/heads/master
2021-01-08T23:04:56.313309
2019-08-24T17:21:48
2019-08-24T17:21:48
242,169,354
0
0
MIT
2020-02-21T15:22:35
2020-02-21T15:22:35
null
UTF-8
C++
false
false
1,336
h
///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009-2014 Alan Wright. All rights reserved. // Distributable under the terms of either the Apache License (Version 2.0) // or the GNU Lesser General Public License. ///////////////////////////////////////////////////////////////////////////// #ifndef RUSSIANLETTERTOKENIZER_H #define RUSSIANLETTERTOKENIZER_H #include "CharTokenizer.h" namespace Lucene { /// A RussianLetterTokenizer is a {@link Tokenizer} that extends {@link LetterTokenizer} by also /// allowing the basic Latin digits 0-9. class LPPCONTRIBAPI RussianLetterTokenizer : public CharTokenizer { public: /// Construct a new RussianLetterTokenizer. RussianLetterTokenizer(const ReaderPtr& input); /// Construct a new RussianLetterTokenizer using a given {@link AttributeSource}. RussianLetterTokenizer(const AttributeSourcePtr& source, const ReaderPtr& input); /// Construct a new RussianLetterTokenizer using a given {@link AttributeFactory}. RussianLetterTokenizer(const AttributeFactoryPtr& factory, const ReaderPtr& input); virtual ~RussianLetterTokenizer(); LUCENE_CLASS(RussianLetterTokenizer); public: /// Collects only characters which satisfy UnicodeUtil::isAlpha(c). virtual bool isTokenChar(wchar_t c); }; } #endif
[ "marios.kogias@epfl.ch" ]
marios.kogias@epfl.ch
87f5d09296c219dccdd4cec353d2a94515c7319b
88ac9162aa5a561daafc96bcfde66f50684de148
/Work/microblog/common/lo/loProperty.h
66f404fd6a5d2e23ffe024d583777a8fedaa10a5
[]
no_license
jielmn/MyStudio
e6d535aa7d8b72476bd9b6084560476ac8671609
f45a90dbd73dbbb65df442639ceceb6149117deb
refs/heads/master
2020-03-19T01:22:19.934472
2018-06-04T01:57:05
2018-06-04T01:57:05
135,540,356
1
0
null
null
null
null
GB18030
C++
false
false
923
h
#ifndef __lo_PROPERTY_H__ #define __lo_PROPERTY_H__ // namespace locom DEFINE_NAMESPACE(locom) /** 属性值 * * @author loach * * @date 2009-06-21 */ template< typename PROPERTY_KEY> struct loNovtableM IloPropertyItem { /** 添加一项(如果存在,就进行修改) */ virtual int Add(const PROPERTY_KEY& key,const char* value,size_t len) =0; /** 删除特定属性值 */ virtual int Remove(const PROPERTY_KEY& key) =0; /** 清空所有属性值 */ virtual void Clear(void) = 0; /** 获取相应的值 */ virtual const char* Get(const PROPERTY_KEY& key) const =0; /** 获取相应的值 */ virtual const char* Get(const PROPERTY_KEY& key , size_t& len) const = 0; /** 获取子属性值 */ virtual IloPropertyItem<PROPERTY_KEY>* GetChild(void) const = 0; virtual bool IsChild(void) const = 0; virtual bool NewChild(void) = 0; }; END_NAMESPACE(locom) #endif //
[ "jielmn@aliyun.com" ]
jielmn@aliyun.com
961af6a8e1acfb1c5f2595037c66e724345f31f5
44b306a8e0923e311bce9a14fc51bc2810f6a875
/sudooku_src/sudooku_core/solvers/solver.h
36afa3308e16a16dade5488cccb4db78a23c9872
[]
no_license
wlchs/SudOOku
ec2ccb47fce7c9cde1b56d73fd3439c9b7ea5080
314ae5f8e7345377f16dac49f2e3d00ebb28d557
refs/heads/master
2020-03-28T18:52:53.467506
2018-12-02T10:23:50
2018-12-02T10:23:50
148,922,583
0
0
null
2018-12-02T10:14:18
2018-09-15T17:08:36
C++
UTF-8
C++
false
false
1,006
h
// // Created by Borbély László on 2018. 09. 15.. // #ifndef SUDOOKU_SOLVER_H #define SUDOOKU_SOLVER_H #include <sudooku_core/matrix/matrix.h> #include <sudooku_core/strategies/solvingStrategy.h> /** * Class for solving the puzzle * It is possible to register several SolvingStrategies thus making the class much more flexible to future changes */ class Solver { private: Matrix initialMatrix; unsigned short int dimension{}; std::vector<SolvingStrategy *> strategies; std::vector<Matrix> solutions; void solve(Matrix &); bool isValid(Matrix const &) const; bool hasNoPotentialValues(Matrix const &) const; void optimize(Matrix &) const; bool isSolution(Matrix const &) const; public: Solver() = default; void setInitialMatrix(Matrix const &); void setRules(std::vector<SolvingStrategy *> const &); void addRule(SolvingStrategy *); void solve(); std::vector<Matrix> const &getSolutions() const; }; #endif //SUDOOKU_SOLVER_H
[ "laci.dj@gmail.com" ]
laci.dj@gmail.com
4f8a2a69b85eecc27424f3b87dc9867635202b63
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_1/W+RWC+dmb.sys.c.cbmc.cpp
4e8c49c1de4c29ebef50e8036c4ffcfd3d1e966e
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
44,382
cpp
// 0:vars:3 // 3:atom_1_X0_1:1 // 4:atom_1_X2_0:1 // 5:atom_2_X2_0:1 // 6:thr0:1 // 7:thr1:1 // 8:thr2:1 #define ADDRSIZE 9 #define NPROC 4 #define NCONTEXT 1 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NPROC*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NPROC*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NPROC*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NPROC*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NPROC*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NPROC*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NPROC*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NPROC*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NPROC*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NPROC]; int cdy[NPROC]; int cds[NPROC]; int cdl[NPROC]; int cisb[NPROC]; int caddr[NPROC]; int cctrl[NPROC]; int cstart[NPROC]; int creturn[NPROC]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; buff(0,7) = 0; pw(0,7) = 0; cr(0,7) = 0; iw(0,7) = 0; cw(0,7) = 0; cx(0,7) = 0; is(0,7) = 0; cs(0,7) = 0; crmax(0,7) = 0; buff(0,8) = 0; pw(0,8) = 0; cr(0,8) = 0; iw(0,8) = 0; cw(0,8) = 0; cx(0,8) = 0; is(0,8) = 0; cs(0,8) = 0; crmax(0,8) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; buff(1,7) = 0; pw(1,7) = 0; cr(1,7) = 0; iw(1,7) = 0; cw(1,7) = 0; cx(1,7) = 0; is(1,7) = 0; cs(1,7) = 0; crmax(1,7) = 0; buff(1,8) = 0; pw(1,8) = 0; cr(1,8) = 0; iw(1,8) = 0; cw(1,8) = 0; cx(1,8) = 0; is(1,8) = 0; cs(1,8) = 0; crmax(1,8) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; buff(2,7) = 0; pw(2,7) = 0; cr(2,7) = 0; iw(2,7) = 0; cw(2,7) = 0; cx(2,7) = 0; is(2,7) = 0; cs(2,7) = 0; crmax(2,7) = 0; buff(2,8) = 0; pw(2,8) = 0; cr(2,8) = 0; iw(2,8) = 0; cw(2,8) = 0; cx(2,8) = 0; is(2,8) = 0; cs(2,8) = 0; crmax(2,8) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; buff(3,4) = 0; pw(3,4) = 0; cr(3,4) = 0; iw(3,4) = 0; cw(3,4) = 0; cx(3,4) = 0; is(3,4) = 0; cs(3,4) = 0; crmax(3,4) = 0; buff(3,5) = 0; pw(3,5) = 0; cr(3,5) = 0; iw(3,5) = 0; cw(3,5) = 0; cx(3,5) = 0; is(3,5) = 0; cs(3,5) = 0; crmax(3,5) = 0; buff(3,6) = 0; pw(3,6) = 0; cr(3,6) = 0; iw(3,6) = 0; cw(3,6) = 0; cx(3,6) = 0; is(3,6) = 0; cs(3,6) = 0; crmax(3,6) = 0; buff(3,7) = 0; pw(3,7) = 0; cr(3,7) = 0; iw(3,7) = 0; cw(3,7) = 0; cx(3,7) = 0; is(3,7) = 0; cs(3,7) = 0; crmax(3,7) = 0; buff(3,8) = 0; pw(3,8) = 0; cr(3,8) = 0; iw(3,8) = 0; cw(3,8) = 0; cx(3,8) = 0; is(3,8) = 0; cs(3,8) = 0; crmax(3,8) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(3+0,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; mem(6+0,0) = 0; mem(7+0,0) = 0; mem(8+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; co(1,0) = 0; delta(1,0) = -1; co(2,0) = 0; delta(2,0) = -1; co(3,0) = 0; delta(3,0) = -1; co(4,0) = 0; delta(4,0) = -1; co(5,0) = 0; delta(5,0) = -1; co(6,0) = 0; delta(6,0) = -1; co(7,0) = 0; delta(7,0) = -1; co(8,0) = 0; delta(8,0) = -1; // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !37, metadata !DIExpression()), !dbg !46 // br label %label_1, !dbg !47 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !45), !dbg !48 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !38, metadata !DIExpression()), !dbg !49 // call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !49 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !50 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 1; mem(0,cw(1,0)) = 1; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbsy(), !dbg !51 // dumbsy: Guess old_cdy = cdy[1]; cdy[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[1] >= old_cdy); ASSUME(cdy[1] >= cisb[1]); ASSUME(cdy[1] >= cdl[1]); ASSUME(cdy[1] >= cds[1]); ASSUME(cdy[1] >= cctrl[1]); ASSUME(cdy[1] >= cw(1,0+0)); ASSUME(cdy[1] >= cw(1,0+1)); ASSUME(cdy[1] >= cw(1,0+2)); ASSUME(cdy[1] >= cw(1,3+0)); ASSUME(cdy[1] >= cw(1,4+0)); ASSUME(cdy[1] >= cw(1,5+0)); ASSUME(cdy[1] >= cw(1,6+0)); ASSUME(cdy[1] >= cw(1,7+0)); ASSUME(cdy[1] >= cw(1,8+0)); ASSUME(cdy[1] >= cr(1,0+0)); ASSUME(cdy[1] >= cr(1,0+1)); ASSUME(cdy[1] >= cr(1,0+2)); ASSUME(cdy[1] >= cr(1,3+0)); ASSUME(cdy[1] >= cr(1,4+0)); ASSUME(cdy[1] >= cr(1,5+0)); ASSUME(cdy[1] >= cr(1,6+0)); ASSUME(cdy[1] >= cr(1,7+0)); ASSUME(cdy[1] >= cr(1,8+0)); ASSUME(creturn[1] >= cdy[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !42, metadata !DIExpression()), !dbg !52 // call void @llvm.dbg.value(metadata i64 1, metadata !44, metadata !DIExpression()), !dbg !52 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !53 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !54 ret_thread_1 = (- 1); // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !57, metadata !DIExpression()), !dbg !76 // br label %label_2, !dbg !58 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !75), !dbg !78 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !60, metadata !DIExpression()), !dbg !79 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !61 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !62, metadata !DIExpression()), !dbg !79 // %conv = trunc i64 %0 to i32, !dbg !62 // call void @llvm.dbg.value(metadata i32 %conv, metadata !58, metadata !DIExpression()), !dbg !76 // call void (...) @dmbsy(), !dbg !63 // dumbsy: Guess old_cdy = cdy[2]; cdy[2] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[2] >= old_cdy); ASSUME(cdy[2] >= cisb[2]); ASSUME(cdy[2] >= cdl[2]); ASSUME(cdy[2] >= cds[2]); ASSUME(cdy[2] >= cctrl[2]); ASSUME(cdy[2] >= cw(2,0+0)); ASSUME(cdy[2] >= cw(2,0+1)); ASSUME(cdy[2] >= cw(2,0+2)); ASSUME(cdy[2] >= cw(2,3+0)); ASSUME(cdy[2] >= cw(2,4+0)); ASSUME(cdy[2] >= cw(2,5+0)); ASSUME(cdy[2] >= cw(2,6+0)); ASSUME(cdy[2] >= cw(2,7+0)); ASSUME(cdy[2] >= cw(2,8+0)); ASSUME(cdy[2] >= cr(2,0+0)); ASSUME(cdy[2] >= cr(2,0+1)); ASSUME(cdy[2] >= cr(2,0+2)); ASSUME(cdy[2] >= cr(2,3+0)); ASSUME(cdy[2] >= cr(2,4+0)); ASSUME(cdy[2] >= cr(2,5+0)); ASSUME(cdy[2] >= cr(2,6+0)); ASSUME(cdy[2] >= cr(2,7+0)); ASSUME(cdy[2] >= cr(2,8+0)); ASSUME(creturn[2] >= cdy[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !64, metadata !DIExpression()), !dbg !83 // %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !65 // LD: Guess old_cr = cr(2,0+2*1); cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+2*1)] == 2); ASSUME(cr(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cr(2,0+2*1) >= 0); ASSUME(cr(2,0+2*1) >= cdy[2]); ASSUME(cr(2,0+2*1) >= cisb[2]); ASSUME(cr(2,0+2*1) >= cdl[2]); ASSUME(cr(2,0+2*1) >= cl[2]); // Update creg_r1 = cr(2,0+2*1); crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+2*1) < cw(2,0+2*1)) { r1 = buff(2,0+2*1); } else { if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) { ASSUME(cr(2,0+2*1) >= old_cr); } pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1)); r1 = mem(0+2*1,cr(2,0+2*1)); } ASSUME(creturn[2] >= cr(2,0+2*1)); // call void @llvm.dbg.value(metadata i64 %1, metadata !66, metadata !DIExpression()), !dbg !83 // %conv4 = trunc i64 %1 to i32, !dbg !66 // call void @llvm.dbg.value(metadata i32 %conv4, metadata !63, metadata !DIExpression()), !dbg !76 // %cmp = icmp eq i32 %conv, 1, !dbg !67 // %conv5 = zext i1 %cmp to i32, !dbg !67 // call void @llvm.dbg.value(metadata i32 %conv5, metadata !67, metadata !DIExpression()), !dbg !76 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !68, metadata !DIExpression()), !dbg !87 // %2 = zext i32 %conv5 to i64 // call void @llvm.dbg.value(metadata i64 %2, metadata !70, metadata !DIExpression()), !dbg !87 // store atomic i64 %2, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !69 // ST: Guess iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,3); cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,3)] == 2); ASSUME(active[cw(2,3)] == 2); ASSUME(sforbid(3,cw(2,3))== 0); ASSUME(iw(2,3) >= max(creg_r0,0)); ASSUME(iw(2,3) >= 0); ASSUME(cw(2,3) >= iw(2,3)); ASSUME(cw(2,3) >= old_cw); ASSUME(cw(2,3) >= cr(2,3)); ASSUME(cw(2,3) >= cl[2]); ASSUME(cw(2,3) >= cisb[2]); ASSUME(cw(2,3) >= cdy[2]); ASSUME(cw(2,3) >= cdl[2]); ASSUME(cw(2,3) >= cds[2]); ASSUME(cw(2,3) >= cctrl[2]); ASSUME(cw(2,3) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,3) = (r0==1); mem(3,cw(2,3)) = (r0==1); co(3,cw(2,3))+=1; delta(3,cw(2,3)) = -1; ASSUME(creturn[2] >= cw(2,3)); // %cmp7 = icmp eq i32 %conv4, 0, !dbg !70 // %conv8 = zext i1 %cmp7 to i32, !dbg !70 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !71, metadata !DIExpression()), !dbg !76 // call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !72, metadata !DIExpression()), !dbg !90 // %3 = zext i32 %conv8 to i64 // call void @llvm.dbg.value(metadata i64 %3, metadata !74, metadata !DIExpression()), !dbg !90 // store atomic i64 %3, i64* @atom_1_X2_0 seq_cst, align 8, !dbg !72 // ST: Guess iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,4); cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,4)] == 2); ASSUME(active[cw(2,4)] == 2); ASSUME(sforbid(4,cw(2,4))== 0); ASSUME(iw(2,4) >= max(creg_r1,0)); ASSUME(iw(2,4) >= 0); ASSUME(cw(2,4) >= iw(2,4)); ASSUME(cw(2,4) >= old_cw); ASSUME(cw(2,4) >= cr(2,4)); ASSUME(cw(2,4) >= cl[2]); ASSUME(cw(2,4) >= cisb[2]); ASSUME(cw(2,4) >= cdy[2]); ASSUME(cw(2,4) >= cdl[2]); ASSUME(cw(2,4) >= cds[2]); ASSUME(cw(2,4) >= cctrl[2]); ASSUME(cw(2,4) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,4) = (r1==0); mem(4,cw(2,4)) = (r1==0); co(4,cw(2,4))+=1; delta(4,cw(2,4)) = -1; ASSUME(creturn[2] >= cw(2,4)); // ret i8* null, !dbg !73 ret_thread_2 = (- 1); // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !95, metadata !DIExpression()), !dbg !108 // br label %label_3, !dbg !53 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !107), !dbg !110 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !96, metadata !DIExpression()), !dbg !111 // call void @llvm.dbg.value(metadata i64 1, metadata !98, metadata !DIExpression()), !dbg !111 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !56 // ST: Guess iw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW old_cw = cw(3,0+2*1); cw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM // Check ASSUME(active[iw(3,0+2*1)] == 3); ASSUME(active[cw(3,0+2*1)] == 3); ASSUME(sforbid(0+2*1,cw(3,0+2*1))== 0); ASSUME(iw(3,0+2*1) >= 0); ASSUME(iw(3,0+2*1) >= 0); ASSUME(cw(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cw(3,0+2*1) >= old_cw); ASSUME(cw(3,0+2*1) >= cr(3,0+2*1)); ASSUME(cw(3,0+2*1) >= cl[3]); ASSUME(cw(3,0+2*1) >= cisb[3]); ASSUME(cw(3,0+2*1) >= cdy[3]); ASSUME(cw(3,0+2*1) >= cdl[3]); ASSUME(cw(3,0+2*1) >= cds[3]); ASSUME(cw(3,0+2*1) >= cctrl[3]); ASSUME(cw(3,0+2*1) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,0+2*1) = 1; mem(0+2*1,cw(3,0+2*1)) = 1; co(0+2*1,cw(3,0+2*1))+=1; delta(0+2*1,cw(3,0+2*1)) = -1; ASSUME(creturn[3] >= cw(3,0+2*1)); // call void (...) @dmbsy(), !dbg !57 // dumbsy: Guess old_cdy = cdy[3]; cdy[3] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[3] >= old_cdy); ASSUME(cdy[3] >= cisb[3]); ASSUME(cdy[3] >= cdl[3]); ASSUME(cdy[3] >= cds[3]); ASSUME(cdy[3] >= cctrl[3]); ASSUME(cdy[3] >= cw(3,0+0)); ASSUME(cdy[3] >= cw(3,0+1)); ASSUME(cdy[3] >= cw(3,0+2)); ASSUME(cdy[3] >= cw(3,3+0)); ASSUME(cdy[3] >= cw(3,4+0)); ASSUME(cdy[3] >= cw(3,5+0)); ASSUME(cdy[3] >= cw(3,6+0)); ASSUME(cdy[3] >= cw(3,7+0)); ASSUME(cdy[3] >= cw(3,8+0)); ASSUME(cdy[3] >= cr(3,0+0)); ASSUME(cdy[3] >= cr(3,0+1)); ASSUME(cdy[3] >= cr(3,0+2)); ASSUME(cdy[3] >= cr(3,3+0)); ASSUME(cdy[3] >= cr(3,4+0)); ASSUME(cdy[3] >= cr(3,5+0)); ASSUME(cdy[3] >= cr(3,6+0)); ASSUME(cdy[3] >= cr(3,7+0)); ASSUME(cdy[3] >= cr(3,8+0)); ASSUME(creturn[3] >= cdy[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !100, metadata !DIExpression()), !dbg !114 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !59 // LD: Guess old_cr = cr(3,0); cr(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM // Check ASSUME(active[cr(3,0)] == 3); ASSUME(cr(3,0) >= iw(3,0)); ASSUME(cr(3,0) >= 0); ASSUME(cr(3,0) >= cdy[3]); ASSUME(cr(3,0) >= cisb[3]); ASSUME(cr(3,0) >= cdl[3]); ASSUME(cr(3,0) >= cl[3]); // Update creg_r2 = cr(3,0); crmax(3,0) = max(crmax(3,0),cr(3,0)); caddr[3] = max(caddr[3],0); if(cr(3,0) < cw(3,0)) { r2 = buff(3,0); } else { if(pw(3,0) != co(0,cr(3,0))) { ASSUME(cr(3,0) >= old_cr); } pw(3,0) = co(0,cr(3,0)); r2 = mem(0,cr(3,0)); } ASSUME(creturn[3] >= cr(3,0)); // call void @llvm.dbg.value(metadata i64 %0, metadata !102, metadata !DIExpression()), !dbg !114 // %conv = trunc i64 %0 to i32, !dbg !60 // call void @llvm.dbg.value(metadata i32 %conv, metadata !99, metadata !DIExpression()), !dbg !108 // %cmp = icmp eq i32 %conv, 0, !dbg !61 // %conv1 = zext i1 %cmp to i32, !dbg !61 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !103, metadata !DIExpression()), !dbg !108 // call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !104, metadata !DIExpression()), !dbg !118 // %1 = zext i32 %conv1 to i64 // call void @llvm.dbg.value(metadata i64 %1, metadata !106, metadata !DIExpression()), !dbg !118 // store atomic i64 %1, i64* @atom_2_X2_0 seq_cst, align 8, !dbg !63 // ST: Guess iw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW old_cw = cw(3,5); cw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM // Check ASSUME(active[iw(3,5)] == 3); ASSUME(active[cw(3,5)] == 3); ASSUME(sforbid(5,cw(3,5))== 0); ASSUME(iw(3,5) >= max(creg_r2,0)); ASSUME(iw(3,5) >= 0); ASSUME(cw(3,5) >= iw(3,5)); ASSUME(cw(3,5) >= old_cw); ASSUME(cw(3,5) >= cr(3,5)); ASSUME(cw(3,5) >= cl[3]); ASSUME(cw(3,5) >= cisb[3]); ASSUME(cw(3,5) >= cdy[3]); ASSUME(cw(3,5) >= cdl[3]); ASSUME(cw(3,5) >= cds[3]); ASSUME(cw(3,5) >= cctrl[3]); ASSUME(cw(3,5) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,5) = (r2==0); mem(5,cw(3,5)) = (r2==0); co(5,cw(3,5))+=1; delta(5,cw(3,5)) = -1; ASSUME(creturn[3] >= cw(3,5)); // ret i8* null, !dbg !64 ret_thread_3 = (- 1); // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !128, metadata !DIExpression()), !dbg !168 // call void @llvm.dbg.value(metadata i8** %argv, metadata !129, metadata !DIExpression()), !dbg !168 // %0 = bitcast i64* %thr0 to i8*, !dbg !83 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #6, !dbg !83 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !130, metadata !DIExpression()), !dbg !170 // %1 = bitcast i64* %thr1 to i8*, !dbg !85 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #6, !dbg !85 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !134, metadata !DIExpression()), !dbg !172 // %2 = bitcast i64* %thr2 to i8*, !dbg !87 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #6, !dbg !87 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !135, metadata !DIExpression()), !dbg !174 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !136, metadata !DIExpression()), !dbg !175 // call void @llvm.dbg.value(metadata i64 0, metadata !138, metadata !DIExpression()), !dbg !175 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !90 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !139, metadata !DIExpression()), !dbg !177 // call void @llvm.dbg.value(metadata i64 0, metadata !141, metadata !DIExpression()), !dbg !177 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !92 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !142, metadata !DIExpression()), !dbg !179 // call void @llvm.dbg.value(metadata i64 0, metadata !144, metadata !DIExpression()), !dbg !179 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !94 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !145, metadata !DIExpression()), !dbg !181 // call void @llvm.dbg.value(metadata i64 0, metadata !147, metadata !DIExpression()), !dbg !181 // store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !96 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !148, metadata !DIExpression()), !dbg !183 // call void @llvm.dbg.value(metadata i64 0, metadata !150, metadata !DIExpression()), !dbg !183 // store atomic i64 0, i64* @atom_1_X2_0 monotonic, align 8, !dbg !98 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !151, metadata !DIExpression()), !dbg !185 // call void @llvm.dbg.value(metadata i64 0, metadata !153, metadata !DIExpression()), !dbg !185 // store atomic i64 0, i64* @atom_2_X2_0 monotonic, align 8, !dbg !100 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #6, !dbg !101 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call11 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #6, !dbg !102 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call12 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #6, !dbg !103 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !104, !tbaa !105 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r4 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r4 = buff(0,6); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r4 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // %call13 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !109 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !110, !tbaa !105 // LD: Guess old_cr = cr(0,7); cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,7)] == 0); ASSUME(cr(0,7) >= iw(0,7)); ASSUME(cr(0,7) >= 0); ASSUME(cr(0,7) >= cdy[0]); ASSUME(cr(0,7) >= cisb[0]); ASSUME(cr(0,7) >= cdl[0]); ASSUME(cr(0,7) >= cl[0]); // Update creg_r5 = cr(0,7); crmax(0,7) = max(crmax(0,7),cr(0,7)); caddr[0] = max(caddr[0],0); if(cr(0,7) < cw(0,7)) { r5 = buff(0,7); } else { if(pw(0,7) != co(7,cr(0,7))) { ASSUME(cr(0,7) >= old_cr); } pw(0,7) = co(7,cr(0,7)); r5 = mem(7,cr(0,7)); } ASSUME(creturn[0] >= cr(0,7)); // %call14 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !111 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !112, !tbaa !105 // LD: Guess old_cr = cr(0,8); cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,8)] == 0); ASSUME(cr(0,8) >= iw(0,8)); ASSUME(cr(0,8) >= 0); ASSUME(cr(0,8) >= cdy[0]); ASSUME(cr(0,8) >= cisb[0]); ASSUME(cr(0,8) >= cdl[0]); ASSUME(cr(0,8) >= cl[0]); // Update creg_r6 = cr(0,8); crmax(0,8) = max(crmax(0,8),cr(0,8)); caddr[0] = max(caddr[0],0); if(cr(0,8) < cw(0,8)) { r6 = buff(0,8); } else { if(pw(0,8) != co(8,cr(0,8))) { ASSUME(cr(0,8) >= old_cr); } pw(0,8) = co(8,cr(0,8)); r6 = mem(8,cr(0,8)); } ASSUME(creturn[0] >= cr(0,8)); // %call15 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !113 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !155, metadata !DIExpression()), !dbg !200 // %6 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !115 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r7 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r7 = buff(0,3); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r7 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i64 %6, metadata !157, metadata !DIExpression()), !dbg !200 // %conv = trunc i64 %6 to i32, !dbg !116 // call void @llvm.dbg.value(metadata i32 %conv, metadata !154, metadata !DIExpression()), !dbg !168 // call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !159, metadata !DIExpression()), !dbg !203 // %7 = load atomic i64, i64* @atom_1_X2_0 seq_cst, align 8, !dbg !118 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r8 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r8 = buff(0,4); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r8 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i64 %7, metadata !161, metadata !DIExpression()), !dbg !203 // %conv19 = trunc i64 %7 to i32, !dbg !119 // call void @llvm.dbg.value(metadata i32 %conv19, metadata !158, metadata !DIExpression()), !dbg !168 // call void @llvm.dbg.value(metadata i64* @atom_2_X2_0, metadata !163, metadata !DIExpression()), !dbg !206 // %8 = load atomic i64, i64* @atom_2_X2_0 seq_cst, align 8, !dbg !121 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r9 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r9 = buff(0,5); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r9 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i64 %8, metadata !165, metadata !DIExpression()), !dbg !206 // %conv23 = trunc i64 %8 to i32, !dbg !122 // call void @llvm.dbg.value(metadata i32 %conv23, metadata !162, metadata !DIExpression()), !dbg !168 // %and = and i32 %conv19, %conv23, !dbg !123 creg_r10 = max(creg_r8,creg_r9); ASSUME(active[creg_r10] == 0); r10 = r8 & r9; // call void @llvm.dbg.value(metadata i32 %and, metadata !166, metadata !DIExpression()), !dbg !168 // %and24 = and i32 %conv, %and, !dbg !124 creg_r11 = max(creg_r7,creg_r10); ASSUME(active[creg_r11] == 0); r11 = r7 & r10; // call void @llvm.dbg.value(metadata i32 %and24, metadata !167, metadata !DIExpression()), !dbg !168 // %cmp = icmp eq i32 %and24, 1, !dbg !125 // br i1 %cmp, label %if.then, label %if.end, !dbg !127 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg_r11); ASSUME(cctrl[0] >= 0); if((r11==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([98 x i8], [98 x i8]* @.str.1, i64 0, i64 0), i32 noundef 74, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #7, !dbg !128 // unreachable, !dbg !128 r12 = 1; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !131 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #6, !dbg !131 // %10 = bitcast i64* %thr1 to i8*, !dbg !131 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #6, !dbg !131 // %11 = bitcast i64* %thr0 to i8*, !dbg !131 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #6, !dbg !131 // ret i32 0, !dbg !132 ret_thread_0 = 0; ASSERT(r12== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
adbc2c53d274886f6828085df2d641024d1e7e66
2fcc9ad89cf0c85d12fa549f969973b6f4c68fdc
/SampleMathematics/NonlocalBlowup/GpuPdeSolver3.h
c5670e2f1dcbfc9d289f207a167fe4048aea1e70
[ "BSL-1.0" ]
permissive
nmnghjss/WildMagic
9e111de0a23d736dc5b2eef944f143ca84e58bc0
b1a7cc2140dde23d8d9a4ece52a07bd5ff938239
refs/heads/master
2022-04-22T09:01:12.909379
2013-05-13T21:28:18
2013-05-13T21:28:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,454
h
// Geometric Tools, LLC // Copyright (c) 1998-2012 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.3.0 (2010/09/07) #ifndef GPUPDESOLVER3_H #define GPUPDESOLVER3_H #include "OpenGLHelper.h" #include "Image3.h" class GpuPdeSolver3 { protected: // Abstract base class. The return 'success' is 'true' iff the solver is // successfully created. GpuPdeSolver3 (const GLchar* declarations, const GLchar* equation, int dimension0, int dimension1, int dimension2, const Image3<float>* initial, const Image3<unsigned char>* domain, float dt, float dx0, float dx1, float dx2, bool& success); public: virtual ~GpuPdeSolver3 (); // The function Enable() activates the GPU program and sets the shader // uniforms. The function Disable() deactives the GPU program. A derived // class should override these when additional shader uniforms must be set // or when other OpenGL state must be enabled or disabled. virtual bool Enable (); virtual bool Disable (); // Compute one step of the solver. This function must be called after // Enable() is called the first time. If an application performs OpenGL // operations that cause a change in active program, Enable() must be // recalled before Execute() to restore the solver program and set the // uniforms. The callback OnPreIteration(...) is called before the // solver step and the callback OnPostIteration(...) is called after // the solver step. A derived class may override these if additional // behavior is needed before and after the solver step. If the input // 'iteration' is zero, the solver assumes this is the initial step and // sets the flip-flop buffers accordingly. bool Execute (uint64_t iteration, int numGaussSeidel); protected: // Support for construction. bool CreateGraphicsObjects (const GLchar* declarations, const GLchar* equation); void SetShaderConstants (float dt, float dx0, float dx1, float dx2); void SetInitialValues (const Image3<float>* initial); void SetMaskValues (const Image3<unsigned char>* domain); // Support for memory mapping. void Map2Dto3D (int u, int v, int& x, int& y, int& z) const; void Map3Dto2D (int x, int y, int z, int& u, int& v) const; // Overrides to be specialized by derived classes. Return 'true' to // continue the solver, 'false' to terminate the solver. virtual bool OnPreIteration (uint64_t iteration); virtual bool OnPostIteration (uint64_t iteration); int mDimension[3], mNumTexels; int mFactor[2], mBound[2]; GLuint mVertexBuffer, mVertexShader, mFragmentShader, mProgram; GLuint mModelPositionAttribute; GLint mU0SamplerLocation, mU1SamplerLocation, mMaskSamplerLocation; GLint mDeltaLocation, mCoeff0Location, mCoeff1Location; GLint mUVDimensionsLocation, mXYDimensionsLocation, mTileColumnsLocation; GLuint mTexture[3], mFrameBuffer[3], mMaskTexture; float mUVDimensions[2], mXYDimensions[2], mTileColumns; float mDelta[4], mCoeff0[4], mCoeff1; int mActive[3]; private: static const float msSquare[4][2]; static const GLchar* msVertexText; static const GLchar* msFragmentDeclareText; static const GLchar* msFragmentSamplerText; static const GLchar* msFragmentResultText; }; #endif
[ "bazhenovc@bazhenovc-laptop" ]
bazhenovc@bazhenovc-laptop
7602ca85ec89971eb080f1b4557a7c4c1322e6e6
46100f3b30a53ae67de024b5e75bf7cf02149cd6
/cpp/d04/ex02/TacticalMarine.hpp
a1d825615822d292b17bd2c0684cf684d7c379b3
[]
no_license
cjulliar/home
c23dcb37c1b49cf8f82e06a93566998c2b363d4f
3674c66edf09002acfd4bd3a0a0e04665517d534
refs/heads/master
2021-01-21T11:19:24.358964
2019-07-12T00:31:40
2019-07-12T00:31:40
83,553,241
0
0
null
null
null
null
UTF-8
C++
false
false
499
hpp
#ifndef TACTICALMARINE_HPP # define TACTICALMARINE_HPP #include <iostream> #include "ISpaceMarine.hpp" class TacticalMarine : public ISpaceMarine { public: TacticalMarine(void); TacticalMarine(const TacticalMarine &src); ~TacticalMarine(void); TacticalMarine &operator= (const TacticalMarine &rhs); virtual void battleCry(void) const; virtual void meleeAttack(void) const; virtual void rangedAttack(void) const; virtual ISpaceMarine *clone(void) const; }; #endif
[ "cjulliar@student.42.fr" ]
cjulliar@student.42.fr
2ca19a4820b016b2d5cd6dabad0d713236b67091
34c6ea938f3ebc74053057884f984bf14950cf10
/libs/irrlicht/examples/22.MaterialViewer/main.cpp
d57a91be494fdc4eada663a84326d3a770db67f5
[ "Zlib", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mzeilfelder/hc1
62e2563e2ed19c35c89083e1e4dd6722e6c6e42e
6f717b1168a85e17582feb141338aaffc923d26a
refs/heads/master
2023-08-09T08:40:15.661233
2019-10-11T18:28:52
2019-10-11T18:28:52
272,798,185
13
5
null
2022-11-25T22:53:24
2020-06-16T19:47:14
C
UTF-8
C++
false
false
32,921
cpp
/** Example 022 Material Viewer This example can be used to play around with material settings and watch the results. Only the default non-shader materials are used in here. You have a node with a mesh, one dynamic light and global ambient light to play around with. You can move the light with cursor-keys and +/-. You can move the camera while left-mouse button is clicked. */ // TODO: Should be possible to set all material values by the GUI. // For now just change the defaultMaterial in CApp::init for the rest. // TODO: Allow users to switch between a sphere and a box meshĵ #include <irrlicht.h> #include "driverChoice.h" #include "main.h" using namespace irr; #ifdef _MSC_VER #pragma comment(lib, "Irrlicht.lib") #endif /* Variables within the empty namespace are globals which are restricted to this file. */ namespace { // For the gui id's enum EGUI_IDS { GUI_ID_OPEN_TEXTURE = 1, GUI_ID_QUIT, GUI_ID_MAX }; // Name used in texture selection to clear the textures on the node const core::stringw CLEAR_TEXTURE = L"CLEAR texture"; // some useful color constants const video::SColor SCOL_BLACK = video::SColor(255, 0, 0, 0); const video::SColor SCOL_BLUE = video::SColor(255, 0, 0, 255); const video::SColor SCOL_CYAN = video::SColor(255, 0, 255, 255); const video::SColor SCOL_GRAY = video::SColor(255, 128,128, 128); const video::SColor SCOL_GREEN = video::SColor(255, 0, 255, 0); const video::SColor SCOL_MAGENTA = video::SColor(255, 255, 0, 255); const video::SColor SCOL_RED = video::SColor(255, 255, 0, 0); const video::SColor SCOL_YELLOW = video::SColor(255, 255, 255, 0); const video::SColor SCOL_WHITE = video::SColor(255, 255, 255, 255); }; // namespace /* Returns a new unique number on each call. */ s32 makeUniqueId() { static int unique = GUI_ID_MAX; ++unique; return unique; } /* Find out which vertex-type is needed for the given material type. */ video::E_VERTEX_TYPE getVertexTypeForMaterialType(video::E_MATERIAL_TYPE materialType) { using namespace video; switch ( materialType ) { case EMT_SOLID: return EVT_STANDARD; case EMT_SOLID_2_LAYER: return EVT_STANDARD; case EMT_LIGHTMAP: case EMT_LIGHTMAP_ADD: case EMT_LIGHTMAP_M2: case EMT_LIGHTMAP_M4: case EMT_LIGHTMAP_LIGHTING: case EMT_LIGHTMAP_LIGHTING_M2: case EMT_LIGHTMAP_LIGHTING_M4: return EVT_2TCOORDS; case EMT_DETAIL_MAP: return EVT_2TCOORDS; case EMT_SPHERE_MAP: return EVT_STANDARD; case EMT_REFLECTION_2_LAYER: return EVT_2TCOORDS; case EMT_TRANSPARENT_ADD_COLOR: return EVT_STANDARD; case EMT_TRANSPARENT_ALPHA_CHANNEL: return EVT_STANDARD; case EMT_TRANSPARENT_ALPHA_CHANNEL_REF: return EVT_STANDARD; case EMT_TRANSPARENT_VERTEX_ALPHA: return EVT_STANDARD; case EMT_TRANSPARENT_REFLECTION_2_LAYER: return EVT_2TCOORDS; case EMT_NORMAL_MAP_SOLID: case EMT_NORMAL_MAP_TRANSPARENT_ADD_COLOR: case EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA: case EMT_PARALLAX_MAP_SOLID: case EMT_PARALLAX_MAP_TRANSPARENT_ADD_COLOR: case EMT_PARALLAX_MAP_TRANSPARENT_VERTEX_ALPHA: return EVT_TANGENTS; case EMT_ONETEXTURE_BLEND: return EVT_STANDARD; case EMT_FORCE_32BIT: return EVT_STANDARD; } return EVT_STANDARD; } /* Custom GUI-control to edit colorvalues. */ // Constructor CColorControl::CColorControl(gui::IGUIEnvironment* guiEnv, const core::position2d<s32> & pos, const wchar_t *text, IGUIElement* parent, s32 id) : gui::IGUIElement(gui::EGUIET_ELEMENT, guiEnv, parent,id, core::rect< s32 >(pos, pos+core::dimension2d<s32>(80, 75))) , DirtyFlag(true) , ColorStatic(0) , EditAlpha(0) , EditRed(0) , EditGreen(0) , EditBlue(0) { using namespace gui; ButtonSetId = makeUniqueId(); const core::rect< s32 > rectControls(0,0,AbsoluteRect.getWidth(),AbsoluteRect.getHeight() ); IGUIStaticText * groupElement = guiEnv->addStaticText (L"", rectControls, true, false, this, -1, false); groupElement->setNotClipped(true); guiEnv->addStaticText (text, core::rect<s32>(0,0,80,15), false, false, groupElement, -1, false); EditAlpha = addEditForNumbers(guiEnv, core::position2d<s32>(0,15), L"a", -1, groupElement ); EditRed = addEditForNumbers(guiEnv, core::position2d<s32>(0,30), L"r", -1, groupElement ); EditGreen = addEditForNumbers(guiEnv, core::position2d<s32>(0,45), L"g", -1, groupElement ); EditBlue = addEditForNumbers(guiEnv, core::position2d<s32>(0,60), L"b", -1, groupElement ); ColorStatic = guiEnv->addStaticText (L"", core::rect<s32>(60,15,80,75), true, false, groupElement, -1, true); guiEnv->addButton (core::rect<s32>(60,35,80,50), groupElement, ButtonSetId, L"set"); setEditsFromColor(Color); } // event receiver bool CColorControl::OnEvent(const SEvent &event) { if ( event.EventType != EET_GUI_EVENT ) return false; if ( event.GUIEvent.Caller->getID() == ButtonSetId && event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED ) { Color = getColorFromEdits(); setEditsFromColor(Color); } return false; } // set the color values void CColorControl::setColor(const video::SColor& col) { DirtyFlag = true; Color = col; setEditsFromColor(Color); } // Add a staticbox for a description + an editbox so users can enter numbers gui::IGUIEditBox* CColorControl::addEditForNumbers(gui::IGUIEnvironment* guiEnv, const core::position2d<s32> & pos, const wchar_t *text, s32 id, gui::IGUIElement * parent) { using namespace gui; core::rect< s32 > rect(pos, pos+core::dimension2d<s32>(10, 15)); guiEnv->addStaticText (text, rect, false, false, parent, -1, false); rect += core::position2d<s32>( 20, 0 ); rect.LowerRightCorner.X += 20; gui::IGUIEditBox* edit = guiEnv->addEditBox(L"0", rect, true, parent, id); return edit; } // Get the color value from the editfields video::SColor CColorControl::getColorFromEdits() const { video::SColor col; if (EditAlpha) { u32 alpha = core::strtoul10(core::stringc(EditAlpha->getText()).c_str()); if (alpha > 255) alpha = 255; col.setAlpha(alpha); } if (EditRed) { u32 red = core::strtoul10(core::stringc(EditRed->getText()).c_str()); if (red > 255) red = 255; col.setRed(red); } if (EditGreen) { u32 green = core::strtoul10(core::stringc(EditGreen->getText()).c_str()); if (green > 255) green = 255; col.setGreen(green); } if (EditBlue) { u32 blue = core::strtoul10(core::stringc(EditBlue->getText()).c_str()); if (blue > 255) blue = 255; col.setBlue(blue); } return col; } // Fill the editfields with the value for the given color void CColorControl::setEditsFromColor(video::SColor col) { DirtyFlag = true; if ( EditAlpha ) EditAlpha->setText( core::stringw(col.getAlpha()).c_str() ); if ( EditRed ) EditRed->setText( core::stringw(col.getRed()).c_str() ); if ( EditGreen ) EditGreen->setText( core::stringw(col.getGreen()).c_str() ); if ( EditBlue ) EditBlue->setText( core::stringw(col.getBlue()).c_str() ); if ( ColorStatic ) ColorStatic->setBackgroundColor(col); } /* Custom GUI-control for to edit all colors typically used in materials and lights */ // Constructor CTypicalColorsControl::CTypicalColorsControl(gui::IGUIEnvironment* guiEnv, const core::position2d<s32> & pos, bool hasEmissive, IGUIElement* parent, s32 id) : gui::IGUIElement(gui::EGUIET_ELEMENT, guiEnv, parent,id, core::rect<s32>(pos,pos+core::dimension2d<s32>(60,250))) , ControlAmbientColor(0), ControlDiffuseColor(0), ControlSpecularColor(0), ControlEmissiveColor(0) { ControlAmbientColor = new CColorControl( guiEnv, core::position2d<s32>(0, 0), L"Ambient", this); ControlDiffuseColor = new CColorControl( guiEnv, core::position2d<s32>(0, 75), L"Diffuse", this ); ControlSpecularColor = new CColorControl( guiEnv, core::position2d<s32>(0, 150), L"Specular", this ); if ( hasEmissive ) { ControlEmissiveColor = new CColorControl( guiEnv, core::position2d<s32>(0, 225), L"Emissive", this ); } } // Destructor CTypicalColorsControl::~CTypicalColorsControl() { ControlAmbientColor->drop(); ControlDiffuseColor->drop(); if ( ControlEmissiveColor ) ControlEmissiveColor->drop(); ControlSpecularColor->drop(); } // Set the color values to those within the material void CTypicalColorsControl::setColorsToMaterialColors(const video::SMaterial & material) { ControlAmbientColor->setColor(material.AmbientColor); ControlDiffuseColor->setColor(material.DiffuseColor); ControlEmissiveColor->setColor(material.EmissiveColor); ControlSpecularColor->setColor(material.SpecularColor); } // Update all changed colors in the material void CTypicalColorsControl::updateMaterialColors(video::SMaterial & material) const { if ( ControlAmbientColor->isDirty() ) material.AmbientColor = ControlAmbientColor->getColor(); if ( ControlDiffuseColor->isDirty() ) material.DiffuseColor = ControlDiffuseColor->getColor(); if ( ControlEmissiveColor->isDirty() ) material.EmissiveColor = ControlEmissiveColor->getColor(); if ( ControlSpecularColor->isDirty() ) material.SpecularColor = ControlSpecularColor->getColor(); } // Set the color values to those from the light data void CTypicalColorsControl::setColorsToLightDataColors(const video::SLight & lightData) { ControlAmbientColor->setColor(lightData.AmbientColor.toSColor()); ControlDiffuseColor->setColor(lightData.DiffuseColor.toSColor()); ControlSpecularColor->setColor(lightData.SpecularColor.toSColor()); } // Update all changed colors in the light data void CTypicalColorsControl::updateLightColors(video::SLight & lightData) const { if ( ControlAmbientColor->isDirty() ) lightData.AmbientColor = video::SColorf( ControlAmbientColor->getColor() ); if ( ControlDiffuseColor->isDirty() ) lightData.DiffuseColor = video::SColorf( ControlDiffuseColor->getColor() ); if ( ControlSpecularColor->isDirty() ) lightData.SpecularColor = video::SColorf(ControlSpecularColor->getColor() ); } // To reset the dirty flags void CTypicalColorsControl::resetDirty() { ControlAmbientColor->resetDirty(); ControlDiffuseColor->resetDirty(); ControlSpecularColor->resetDirty(); if ( ControlEmissiveColor ) ControlEmissiveColor->resetDirty(); } /* GUI-Control to offer a selection of available textures. */ CTextureControl::CTextureControl(gui::IGUIEnvironment* guiEnv, video::IVideoDriver * driver, const core::position2d<s32> & pos, IGUIElement* parent, s32 id) : gui::IGUIElement(gui::EGUIET_ELEMENT, guiEnv, parent,id, core::rect<s32>(pos,pos+core::dimension2d<s32>(150,15))) , DirtyFlag(true), ComboTexture(0) { core::rect<s32> rectCombo(0, 0, AbsoluteRect.getWidth(),AbsoluteRect.getHeight()); ComboTexture = guiEnv->addComboBox (rectCombo, this); updateTextures(driver); } bool CTextureControl::OnEvent(const SEvent &event) { if ( event.EventType != EET_GUI_EVENT ) return false; if ( event.GUIEvent.Caller == ComboTexture && event.GUIEvent.EventType == gui::EGET_COMBO_BOX_CHANGED ) { DirtyFlag = true; } return false; } // Workaround for a problem with comboboxes. // We have to get in front when the combobox wants to get in front or combobox-list might be drawn below other elements. bool CTextureControl::bringToFront(IGUIElement* element) { bool result = gui::IGUIElement::bringToFront(element); if ( Parent && element == ComboTexture ) result &= Parent->bringToFront(this); return result; } // return selected texturename (if any, otherwise 0) const wchar_t * CTextureControl::getSelectedTextureName() const { s32 selected = ComboTexture->getSelected(); if ( selected < 0 ) return 0; return ComboTexture->getItem(selected); } void CTextureControl::selectTextureByName(const irr::core::stringw& name) { for (u32 i=0; i< ComboTexture->getItemCount(); ++i) { if ( name == ComboTexture->getItem(i)) { ComboTexture->setSelected(i); DirtyFlag = true; return; } } } // Put the names of all currently loaded textures in a combobox void CTextureControl::updateTextures(video::IVideoDriver * driver) { s32 oldSelected = ComboTexture->getSelected(); s32 selectNew = -1; core::stringw oldTextureName; if ( oldSelected >= 0 ) { oldTextureName = ComboTexture->getItem(oldSelected); } ComboTexture->clear(); for ( u32 i=0; i < driver->getTextureCount(); ++i ) { video::ITexture * texture = driver->getTextureByIndex(i); core::stringw name( texture->getName() ); ComboTexture->addItem( name.c_str() ); if ( !oldTextureName.empty() && selectNew < 0 && name == oldTextureName ) selectNew = i; } // add another name which can be used to clear the texture ComboTexture->addItem( CLEAR_TEXTURE.c_str() ); if ( CLEAR_TEXTURE == oldTextureName ) selectNew = ComboTexture->getItemCount()-1; if ( selectNew >= 0 ) ComboTexture->setSelected(selectNew); DirtyFlag = true; } /* Control which allows setting some of the material values for a meshscenenode */ void SMaterialControl::init(scene::IMeshSceneNode* node, IrrlichtDevice * device, const core::position2d<s32> & pos, const wchar_t * description) { if ( Initialized || !node || !device) // initializing twice or with invalid data not allowed return; Driver = device->getVideoDriver (); gui::IGUIEnvironment* guiEnv = device->getGUIEnvironment(); scene::ISceneManager* smgr = device->getSceneManager(); const video::SMaterial & material = node->getMaterial(0); s32 top = pos.Y; // Description guiEnv->addStaticText(description, core::rect<s32>(pos.X, top, pos.X+60, top+15), false, false, 0, -1, false); top += 15; // Control for material type core::rect<s32> rectCombo(pos.X, top, 150, top+15); top += 15; ComboMaterial = guiEnv->addComboBox (rectCombo); for ( int i=0; i <= (int)video::EMT_ONETEXTURE_BLEND; ++i ) { ComboMaterial->addItem( core::stringw(video::sBuiltInMaterialTypeNames[i]).c_str() ); } ComboMaterial->setSelected( (s32)material.MaterialType ); // Control to enable/disabling material lighting core::rect<s32> rectBtn(core::position2d<s32>(pos.X, top), core::dimension2d<s32>(100, 15)); top += 15; ButtonLighting = guiEnv->addButton (rectBtn, 0, -1, L"Lighting"); ButtonLighting->setIsPushButton(true); ButtonLighting->setPressed(material.Lighting); core::rect<s32> rectInfo( rectBtn.LowerRightCorner.X, rectBtn.UpperLeftCorner.Y, rectBtn.LowerRightCorner.X+40, rectBtn.UpperLeftCorner.Y+15 ); InfoLighting = guiEnv->addStaticText(L"", rectInfo, true, false ); InfoLighting->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_CENTER ); // Controls for colors TypicalColorsControl = new CTypicalColorsControl(guiEnv, core::position2d<s32>(pos.X, top), true, guiEnv->getRootGUIElement()); top += 300; TypicalColorsControl->setColorsToMaterialColors(material); // Controls for selecting the material textures guiEnv->addStaticText(L"Textures", core::rect<s32>(pos.X, top, pos.X+60, top+15), false, false, 0, -1, false); top += 15; for (irr::u32 i=0; i<irr::video::MATERIAL_MAX_TEXTURES; ++i) { TextureControls[i] = new CTextureControl(guiEnv, Driver, core::position2di(pos.X, top), guiEnv->getRootGUIElement()); top += 15; } Initialized = true; } void SMaterialControl::update(scene::IMeshSceneNode* sceneNode, scene::IMeshSceneNode* sceneNode2T, scene::IMeshSceneNode* sceneNodeTangents) { if ( !Initialized ) return; video::SMaterial & material = sceneNode->getMaterial(0); video::SMaterial & material2T = sceneNode2T->getMaterial(0); video::SMaterial & materialTangents = sceneNodeTangents->getMaterial(0); s32 selectedMaterial = ComboMaterial->getSelected(); if ( selectedMaterial >= (s32)video::EMT_SOLID && selectedMaterial <= (s32)video::EMT_ONETEXTURE_BLEND) { // Show the node which has a mesh to work with the currently selected material video::E_VERTEX_TYPE vertexType = getVertexTypeForMaterialType((video::E_MATERIAL_TYPE)selectedMaterial); switch ( vertexType ) { case video::EVT_STANDARD: material.MaterialType = (video::E_MATERIAL_TYPE)selectedMaterial; sceneNode->setVisible(true); sceneNode2T->setVisible(false); sceneNodeTangents->setVisible(false); break; case video::EVT_2TCOORDS: material2T.MaterialType = (video::E_MATERIAL_TYPE)selectedMaterial; sceneNode->setVisible(false); sceneNode2T->setVisible(true); sceneNodeTangents->setVisible(false); break; case video::EVT_TANGENTS: materialTangents.MaterialType = (video::E_MATERIAL_TYPE)selectedMaterial; sceneNode->setVisible(false); sceneNode2T->setVisible(false); sceneNodeTangents->setVisible(true); break; } } // Always update materials of all nodes, otherwise the tool is confusing to use. updateMaterial(material); updateMaterial(material2T); updateMaterial(materialTangents); if ( ButtonLighting->isPressed() ) InfoLighting->setText(L"is on"); else InfoLighting->setText(L"is off"); TypicalColorsControl->resetDirty(); for (irr::u32 i=0; i<irr::video::MATERIAL_MAX_TEXTURES; ++i) TextureControls[i]->resetDirty(); } void SMaterialControl::updateTextures() { for (irr::u32 i=0; i<irr::video::MATERIAL_MAX_TEXTURES; ++i) TextureControls[i]->updateTextures(Driver); } void SMaterialControl::selectTextures(const irr::core::stringw& name) { for (irr::u32 i=0; i<irr::video::MATERIAL_MAX_TEXTURES; ++i) TextureControls[i]->selectTextureByName(name); } bool SMaterialControl::isLightingEnabled() const { return ButtonLighting && ButtonLighting->isPressed(); } void SMaterialControl::updateMaterial(video::SMaterial & material) { TypicalColorsControl->updateMaterialColors(material); material.Lighting = ButtonLighting->isPressed(); for (irr::u32 i=0; i<irr::video::MATERIAL_MAX_TEXTURES; ++i) { if ( TextureControls[i]->isDirty() ) { material.TextureLayer[i].Texture = Driver->getTexture( io::path(TextureControls[i]->getSelectedTextureName()) ); } } } /* Control to allow setting the color values of a lightscenenode. */ void SLightNodeControl::init(scene::ILightSceneNode* node, gui::IGUIEnvironment* guiEnv, const core::position2d<s32> & pos, const wchar_t * description) { if ( Initialized || !node || !guiEnv) // initializing twice or with invalid data not allowed return; guiEnv->addStaticText(description, core::rect<s32>(pos.X, pos.Y, pos.X+70, pos.Y+15), false, false, 0, -1, false); TypicalColorsControl = new CTypicalColorsControl(guiEnv, core::position2d<s32>(pos.X, pos.Y+15), false, guiEnv->getRootGUIElement()); const video::SLight & lightData = node->getLightData(); TypicalColorsControl->setColorsToLightDataColors(lightData); Initialized = true; } void SLightNodeControl::update(scene::ILightSceneNode* node) { if ( !Initialized ) return; video::SLight & lightData = node->getLightData(); TypicalColorsControl->updateLightColors(lightData); } /* Main application class */ /* Event handler */ bool CApp::OnEvent(const SEvent &event) { if (event.EventType == EET_GUI_EVENT) { gui::IGUIEnvironment* env = Device->getGUIEnvironment(); switch(event.GUIEvent.EventType) { case gui::EGET_MENU_ITEM_SELECTED: { gui::IGUIContextMenu* menu = (gui::IGUIContextMenu*)event.GUIEvent.Caller; s32 id = menu->getItemCommandId(menu->getSelectedItem()); switch(id) { case GUI_ID_OPEN_TEXTURE: // File -> Open Texture env->addFileOpenDialog(L"Please select a texture file to open"); break; case GUI_ID_QUIT: // File -> Quit setRunning(false); break; } } break; case gui::EGET_FILE_SELECTED: { // load the model file, selected in the file open dialog gui::IGUIFileOpenDialog* dialog = (gui::IGUIFileOpenDialog*)event.GUIEvent.Caller; loadTexture(io::path(dialog->getFileName()).c_str()); } break; default: break; } } else if (event.EventType == EET_KEY_INPUT_EVENT) { KeysPressed[event.KeyInput.Key] = event.KeyInput.PressedDown; } else if (event.EventType == EET_MOUSE_INPUT_EVENT) { if (!MousePressed && event.MouseInput.isLeftPressed()) { gui::IGUIEnvironment* guiEnv = Device->getGUIEnvironment(); if ( guiEnv->getHovered() == guiEnv->getRootGUIElement() ) // Click on background { MousePressed = true; MouseStart.X = event.MouseInput.X; MouseStart.Y = event.MouseInput.Y; } } else if (MousePressed && !event.MouseInput.isLeftPressed()) { MousePressed = false; } } return false; } // Application initialization // returns true when it was successful initialized, otherwise false. bool CApp::init(int argc, char *argv[]) { // ask user for driver Config.DriverType=driverChoiceConsole(); if (Config.DriverType==video::EDT_COUNT) return false; // create the device with the settings from our config Device = createDevice(Config.DriverType, Config.ScreenSize); if (!Device) return false; Device->setWindowCaption( core::stringw(video::DRIVER_TYPE_NAMES[Config.DriverType]).c_str() ); Device->setEventReceiver(this); scene::ISceneManager* smgr = Device->getSceneManager(); video::IVideoDriver * driver = Device->getVideoDriver (); gui::IGUIEnvironment* guiEnv = Device->getGUIEnvironment(); MeshManipulator = smgr->getMeshManipulator(); // set a nicer font gui::IGUISkin* skin = guiEnv->getSkin(); gui::IGUIFont* font = guiEnv->getFont("../../media/fonthaettenschweiler.bmp"); if (font) skin->setFont(font); // remove some alpha value because it makes those menus harder to read otherwise video::SColor col3dHighLight( skin->getColor(gui::EGDC_APP_WORKSPACE) ); col3dHighLight.setAlpha(255); video::SColor colHighLight( col3dHighLight ); skin->setColor(gui::EGDC_HIGH_LIGHT, colHighLight ); skin->setColor(gui::EGDC_3D_HIGH_LIGHT, col3dHighLight ); // Add some textures which are useful to test material settings createDefaultTextures(driver); // create a menu gui::IGUIContextMenu * menuBar = guiEnv->addMenu(); menuBar->addItem(L"File", -1, true, true); gui::IGUIContextMenu* subMenuFile = menuBar->getSubMenu(0); subMenuFile->addItem(L"Open texture ...", GUI_ID_OPEN_TEXTURE); subMenuFile->addSeparator(); subMenuFile->addItem(L"Quit", GUI_ID_QUIT); const s32 controlsTop = 20; // a static camera Camera = smgr->addCameraSceneNode (0, core::vector3df(0, 40, -40), core::vector3df(0, 10, 0), -1); // default material video::SMaterial defaultMaterial; defaultMaterial.Shininess = 20.f; // add the nodes which are used to show the materials SceneNode = smgr->addCubeSceneNode (30.0f, 0, -1, core::vector3df(0, 0, 0), core::vector3df(0.f, 45.f, 0.f), core::vector3df(1.0f, 1.0f, 1.0f)); SceneNode->getMaterial(0) = defaultMaterial; MeshMaterialControl.init( SceneNode, Device, core::position2d<s32>(10,controlsTop), L"Material" ); MeshMaterialControl.selectTextures(core::stringw("CARO_A8R8G8B8")); // set a useful default texture // create nodes with other vertex types scene::IMesh * mesh2T = MeshManipulator->createMeshWith2TCoords(SceneNode->getMesh()); SceneNode2T = smgr->addMeshSceneNode(mesh2T, 0, -1, SceneNode->getPosition(), SceneNode->getRotation(), SceneNode->getScale() ); mesh2T->drop(); scene::IMesh * meshTangents = MeshManipulator->createMeshWithTangents(SceneNode->getMesh(), false, false, false); SceneNodeTangents = smgr->addMeshSceneNode(meshTangents, 0, -1 , SceneNode->getPosition(), SceneNode->getRotation(), SceneNode->getScale() ); meshTangents->drop(); // add one light NodeLight = smgr->addLightSceneNode(0, core::vector3df(0, 0, -40), video::SColorf(1.0f, 1.0f, 1.0f), 35.0f); LightControl.init(NodeLight, guiEnv, core::position2d<s32>(550,controlsTop), L"Dynamic light" ); // one large cube around everything. That's mainly to make the light more obvious. scene::IMeshSceneNode* backgroundCube = smgr->addCubeSceneNode (200.0f, 0, -1, core::vector3df(0, 0, 0), core::vector3df(45, 0, 0), core::vector3df(1.0f, 1.0f, 1.0f)); backgroundCube->getMaterial(0).BackfaceCulling = false; // we are within the cube, so we have to disable backface culling to see it backgroundCube->getMaterial(0).EmissiveColor.set(255,50,50,50); // we keep some self lighting to keep texts visible // Add a the mesh vertex color control guiEnv->addStaticText(L"Mesh", core::rect<s32>(200, controlsTop, 270, controlsTop+15), false, false, 0, -1, false); ControlVertexColors = new CColorControl( guiEnv, core::position2d<s32>(200, controlsTop+15), L"Vertex colors", guiEnv->getRootGUIElement()); video::S3DVertex * vertices = (video::S3DVertex *)SceneNode->getMesh()->getMeshBuffer(0)->getVertices(); if ( vertices ) { ControlVertexColors->setColor(vertices[0].Color); } // Add a control for ambient light GlobalAmbient = new CColorControl( guiEnv, core::position2d<s32>(550, 300), L"Global ambient", guiEnv->getRootGUIElement()); GlobalAmbient->setColor( smgr->getAmbientLight().toSColor() ); return true; } /* Update one frame */ bool CApp::update() { using namespace irr; video::IVideoDriver* videoDriver = Device->getVideoDriver(); if ( !Device->run() ) return false; // Figure out delta time since last frame ITimer * timer = Device->getTimer(); u32 newTick = timer->getRealTime(); f32 deltaTime = RealTimeTick > 0 ? f32(newTick-RealTimeTick)/1000.0 : 0.f; // in seconds RealTimeTick = newTick; if ( Device->isWindowActive() || Config.RenderInBackground ) { gui::IGUIEnvironment* guiEnv = Device->getGUIEnvironment(); scene::ISceneManager* smgr = Device->getSceneManager(); gui::IGUISkin * skin = guiEnv->getSkin(); // update our controls MeshMaterialControl.update(SceneNode, SceneNode2T, SceneNodeTangents); LightControl.update(NodeLight); // Update vertices if ( ControlVertexColors->isDirty() ) { MeshManipulator->setVertexColors (SceneNode->getMesh(), ControlVertexColors->getColor()); MeshManipulator->setVertexColors (SceneNode2T->getMesh(), ControlVertexColors->getColor()); MeshManipulator->setVertexColors (SceneNodeTangents->getMesh(), ControlVertexColors->getColor()); ControlVertexColors->resetDirty(); } // update ambient light settings if ( GlobalAmbient->isDirty() ) { smgr->setAmbientLight( GlobalAmbient->getColor() ); GlobalAmbient->resetDirty(); } // Let the user move the light around const float zoomSpeed = 10.f * deltaTime; const float rotationSpeed = 100.f * deltaTime; if ( KeysPressed[KEY_PLUS] || KeysPressed[KEY_ADD]) ZoomOut(NodeLight, zoomSpeed); if ( KeysPressed[KEY_MINUS] || KeysPressed[KEY_SUBTRACT]) ZoomOut(NodeLight, -zoomSpeed); if ( KeysPressed[KEY_RIGHT]) RotateHorizontal(NodeLight, rotationSpeed); if ( KeysPressed[KEY_LEFT]) RotateHorizontal(NodeLight, -rotationSpeed); UpdateRotationAxis(NodeLight, LightRotationAxis); if ( KeysPressed[KEY_UP]) RotateAroundAxis(NodeLight, rotationSpeed, LightRotationAxis); if ( KeysPressed[KEY_DOWN]) RotateAroundAxis(NodeLight, -rotationSpeed, LightRotationAxis); // Let the user move the camera around if (MousePressed) { gui::ICursorControl* cursorControl = Device->getCursorControl(); const core::position2d<s32>& mousePos = cursorControl->getPosition (); RotateHorizontal(Camera, rotationSpeed * (MouseStart.X - mousePos.X)); RotateAroundAxis(Camera, rotationSpeed * (mousePos.Y - MouseStart.Y), CameraRotationAxis); MouseStart = mousePos; } // draw everything video::SColor bkColor( skin->getColor(gui::EGDC_APP_WORKSPACE) ); videoDriver->beginScene(true, true, bkColor); smgr->drawAll(); guiEnv->drawAll(); if ( MeshMaterialControl.isLightingEnabled() ) { // draw a line from the light to the target video::SMaterial lineMaterial; lineMaterial.Lighting = false; videoDriver->setMaterial(lineMaterial); videoDriver->setTransform(video::ETS_WORLD, core::IdentityMatrix); videoDriver->draw3DLine(NodeLight->getAbsolutePosition(), SceneNode->getAbsolutePosition()); } videoDriver->endScene(); } // be nice Device->sleep( 5 ); return true; } // Close down the application void CApp::quit() { IsRunning = false; if ( ControlVertexColors ) { ControlVertexColors->drop(); ControlVertexColors = NULL; } if ( GlobalAmbient ) { GlobalAmbient->drop(); GlobalAmbient = NULL; } if ( Device ) { Device->closeDevice(); Device->drop(); Device = NULL; } } // Create some useful textures. void CApp::createDefaultTextures(video::IVideoDriver * driver) { const u32 width = 256; const u32 height = 256; video::IImage * imageA8R8G8B8 = driver->createImage (video::ECF_A8R8G8B8, core::dimension2d<u32>(width, height)); if ( !imageA8R8G8B8 ) return; const u32 pitch = imageA8R8G8B8->getPitch(); // Some nice square-pattern with 9 typical colors // Note that the function put readability over speed, you shouldn't use setPixel at runtime but for initialization it's nice. for ( u32 y = 0; y < height; ++ y ) { for ( u32 x = 0; x < pitch; ++x ) { if ( y < height/3 ) { if ( x < width/3 ) imageA8R8G8B8->setPixel (x, y, SCOL_BLACK); else if ( x < 2*width/3 ) imageA8R8G8B8->setPixel (x, y, SCOL_BLUE); else imageA8R8G8B8->setPixel (x, y, SCOL_CYAN); } else if ( y < 2*height/3 ) { if ( x < width/3 ) imageA8R8G8B8->setPixel (x, y, SCOL_GRAY); else if ( x < 2*width/3 ) imageA8R8G8B8->setPixel (x, y, SCOL_GREEN); else imageA8R8G8B8->setPixel (x, y, SCOL_MAGENTA); } else { if ( x < width/3 ) imageA8R8G8B8->setPixel (x, y, SCOL_RED); else if ( x < 2*width/3 ) imageA8R8G8B8->setPixel (x, y, SCOL_YELLOW); else imageA8R8G8B8->setPixel (x, y, SCOL_WHITE); } } } driver->addTexture (io::path("CARO_A8R8G8B8"), imageA8R8G8B8); // all white imageA8R8G8B8->fill(SCOL_WHITE); driver->addTexture (io::path("WHITE_A8R8G8B8"), imageA8R8G8B8); // all black imageA8R8G8B8->fill(SCOL_BLACK); driver->addTexture (io::path("BLACK_A8R8G8B8"), imageA8R8G8B8); // gray-scale for ( u32 y = 0; y < height; ++ y ) { for ( u32 x = 0; x < pitch; ++x ) { imageA8R8G8B8->setPixel (x, y, video::SColor(y, x,x,x) ); } } driver->addTexture (io::path("GRAYSCALE_A8R8G8B8"), imageA8R8G8B8); imageA8R8G8B8->drop(); } // Load a texture and make sure nodes know it when more textures are available. void CApp::loadTexture(const io::path &name) { Device->getVideoDriver()->getTexture(name); MeshMaterialControl.updateTextures(); } void CApp::RotateHorizontal(irr::scene::ISceneNode* node, irr::f32 angle) { if ( node ) { core::vector3df pos(node->getPosition()); core::vector2df dir(pos.X, pos.Z); dir.rotateBy(angle); pos.X = dir.X; pos.Z = dir.Y; node->setPosition(pos); } } void CApp::RotateAroundAxis(irr::scene::ISceneNode* node, irr::f32 angle, const irr::core::vector3df& axis) { if ( node ) { // TOOD: yeah, doesn't rotate around top/bottom yet. Fixes welcome. core::vector3df pos(node->getPosition()); core::matrix4 mat; mat.setRotationAxisRadians (core::degToRad(angle), axis); mat.rotateVect(pos); node->setPosition(pos); } } void CApp::ZoomOut(irr::scene::ISceneNode* node, irr::f32 units) { if ( node ) { core::vector3df pos(node->getPosition()); irr::f32 len = pos.getLength() + units; pos.setLength(len); node->setPosition(pos); } } void CApp::UpdateRotationAxis(irr::scene::ISceneNode* node, irr::core::vector3df& axis) { // Find a perpendicular axis to the x,z vector. If none found (vector straight up/down) continue to use the existing one. core::vector3df pos(node->getPosition()); if ( !core::equals(pos.X, 0.f) || !core::equals(pos.Z, 0.f) ) { axis.X = -pos.Z; axis.Z = pos.X; axis.normalize(); } } /* Short main as most is done in classes. */ int main(int argc, char *argv[]) { CApp APP; if ( !APP.init(argc, argv) ) { printf("init failed\n"); APP.quit(); return 1; } APP.setRunning(true); /* main application loop */ while(APP.isRunning()) { if ( !APP.update() ) break; } APP.quit(); return 0; } /* **/
[ "info@michaelzeilfelder.de" ]
info@michaelzeilfelder.de
93a4908a972780dca4bf3ecd53fb9b96ca08f8e8
99686b20ac291d50ad1d90443af1507f617822d5
/BinaryToDecimal.cpp
6d76fb3dbb1751e9daf49f60d314cc248328f9e2
[ "MIT" ]
permissive
ramachandrajr/cpp-libs
7c6a15ec5d8d3bfc7952ee527d3b4ce059950187
ceee764946e347301bdeaaed0d57c98f9f10e6a6
refs/heads/master
2021-01-20T13:50:16.312882
2017-11-19T11:05:08
2017-11-19T11:05:08
90,529,732
0
0
null
null
null
null
UTF-8
C++
false
false
1,176
cpp
#include <iostream> #include <string> #include <cmath> /** * Convert string containing a 16-bit binary integer into decimal integer value * Recursive * @param bin binary integer string * @param current_position current digit position * @param sum total sum * @return decimal value or value of return recursive call */ int BinToDecimal(std::string bin, int current_position, int sum) { sum += (bin[7-current_position] - 48) * std::pow(2, current_position); if (current_position < 7) return BinToDecimal(bin, ++current_position, sum); else return sum; } /** * Convert string containing a 16-bit binary integer into decimal integer value * @param bin binary integer string * @return decimal value */ int BinToDecimal(std::string bin) { int sum = 0; char bit = 0; for (int i = 0; i <= 7; ++i) { bit = (bin[7-i] - 48); sum += bit * std::pow(2, i); } return sum; } int main() { std::cout << BinToDecimal("11110000", 0, 0) << "\n"; return 0; }
[ "noreply@github.com" ]
noreply@github.com
83f25441bcbb26f94dc733a67d48fd127fa3f5dc
03ab0be5556748e0743498bdd1ddff92b832828b
/open_constructor/app/src/main/jni/scene.h
55382fca2f459dd93a8900feb1dc51cd97a6e423
[ "LicenseRef-scancode-warranty-disclaimer", "Libpng", "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
noxo/tango
5215c183cd121fa5f06c7bb7d30c11e059149128
6d84de2af4564992611ba4f9c6884151ce9213fb
refs/heads/master
2020-04-27T22:30:30.862095
2019-03-28T10:15:28
2019-03-28T10:15:28
174,739,492
1
0
null
2019-03-09T19:52:12
2019-03-09T19:52:11
null
UTF-8
C++
false
false
976
h
#ifndef SCENE_H #define SCENE_H #include <vector> #include "data/file3d.h" #include "gl/glsl.h" #include "gl/renderer.h" #include "tango/scan.h" namespace oc { class Scene { public: Scene(); ~Scene(); void Render(bool frustum); void SetupViewPort(int w, int h); void UpdateFrustum(glm::vec3 pos, float zoom); std::string ColorFragmentShader(); std::string ColorVertexShader(); std::string TexturedFragmentShader(); std::string TexturedVertexShader(); GLuint Image2GLTexture(Image* img); Mesh frustum_; std::vector<Mesh> static_meshes_; GLSL* color_vertex_shader; GLSL* textured_shader; GLRenderer* renderer; std::string vertex; std::string fragment; float uniform; float uniformPitch; glm::vec3 uniformPos; private: std::string lastVertex; std::string lastFragment; }; } #endif
[ "lubos@mapfactor.com" ]
lubos@mapfactor.com
b97c1e3fcb964a0a2625c39b91a1bbd0a837d091
b6f7adfeb818bc28812b92e7b3de8f676717664c
/2224.cpp
a917eaf2116a613925cee4fc668e21866c29fb48
[]
no_license
easyhooon/BOJ_CODES
18b0aab741946859992ed90167d6196bf4fd8d48
720b976207faf96622bec1d9364a21428c77f1f2
refs/heads/master
2023-03-03T11:07:01.562536
2021-02-07T19:53:39
2021-02-07T19:53:39
293,607,565
0
0
null
null
null
null
UHC
C++
false
false
1,261
cpp
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int MAX = 52; int n; char x, y; string tmp; //버리는 문자열 int graph[MAX+1][MAX+1]; int ctoi(char c) { return c>='A' && c<='Z'?c-'A':c-'a'+26; } char itoc(int n) { return n<26?'A'+n:'a'+n-26; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); memset(graph, INF, sizeof(graph)); cin >> n; for(int i = 0; i < n; i++){ cin >> x >> tmp >> y; graph[ctoi(x)][ctoi(y)] = 1; } // Floyd-warshall for (int k = 0; k < 52; k++) { for (int i = 0; i < 52; i++) { for (int j = 0; j < 52; j++) { if (i != j && j != k && k != i) graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]); } } } int cnt = 0; for(int i = 0; i < 52; i++){ for(int j = 0; j < 52; j++){ if(i != j && graph[i][j] != INF) cnt++; } } cout << cnt << '\n'; for(int i = 0; i < 52; i++){ for(int j = 0; j < 52; j++){ if(i != j && graph[i][j] != INF) cout << itoc(i) << " => " << itoc(j) << '\n'; } } return 0; }
[ "51016231+easyhooon@users.noreply.github.com" ]
51016231+easyhooon@users.noreply.github.com
bd1162f363e5166edb8d3bd951bd4b272c751383
1fb15d09d1bde31521a18de500c2707d209ad197
/src/emitvalues/szlvalue.cc
2b08d99f198c552ca3e27e893d99fe24aebf630f
[ "BSD-3-Clause" ]
permissive
chen3feng/szl
5482cb996d8595ac1731c9a16c0c1c921a1cf9e1
9081619365f7fdc72bf28ddc063426bdc37f35ef
refs/heads/master
2023-05-01T15:29:34.052198
2020-06-08T17:56:51
2020-06-08T17:56:51
270,629,939
0
0
NOASSERTION
2020-06-08T10:44:05
2020-06-08T10:44:04
null
UTF-8
C++
false
false
43,956
cc
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ #include <assert.h> #include <algorithm> #include <string> #include <vector> #include "public/porting.h" #include "public/logging.h" #include "public/szlencoder.h" #include "public/szldecoder.h" #include "public/szlvalue.h" SzlValueCmp::~SzlValueCmp() { } SzlValueLess::SzlValueLess(const SzlOps* ops): ops_(ops) { } bool SzlValueLess::Cmp(const SzlValue& v1, const SzlValue& v2) const { return ops_->Less(v1, v2); } SzlValueGreater::SzlValueGreater(const SzlOps* ops): ops_(ops) { } bool SzlValueGreater::Cmp(const SzlValue& v1, const SzlValue& v2) const { return ops_->Less(v2, v1); } // A little helper function that returns whether the specified kind corresponds // to a "simple base" kind, which are all base kinds except for strings and // bytes. static inline bool IsSimpleBaseKind(SzlType::Kind kind) { return SzlType::BaseKind(kind) && kind != SzlType::STRING && kind != SzlType::BYTES; } // Check if values are ordered. // True for base types, and tuples thereof. bool SzlOps::IsOrdered(const SzlType& t) { switch (t.kind()) { case SzlType::BOOL: case SzlType::BYTES: case SzlType::STRING: case SzlType::TIME: case SzlType::INT: case SzlType::FINGERPRINT: case SzlType::FLOAT: return true; case SzlType::TUPLE: for (int i = 0; i < t.fields_size(); ++i) if (!IsOrdered(t.field(i).type())) return false; return true; default: return false; } } // Check if values can be Added, Subtracted, and Negated. // True for TIME, INT, FLOAT, and tuples and maps thereof. bool SzlOps::IsAddable(const SzlType& t) { switch (t.kind()) { case SzlType::TIME: case SzlType::INT: case SzlType::FLOAT: return true; case SzlType::TUPLE: for (int i = 0; i < t.fields_size(); ++i) if (!IsAddable(t.field(i).type())) return false; return true; case SzlType::MAP: if (!IsAddable(t.element()->type())) return false; return true; default: return false; } } // Check if can be multiplied, divided, and converted to Float. // True for INT, FLOAT, and tuples thereof. bool SzlOps::IsNumeric(const SzlType& t) { switch (t.kind()) { case SzlType::INT: case SzlType::FLOAT: return true; case SzlType::TUPLE: for (int i = 0; i < t.fields_size(); ++i) if (!IsNumeric(t.field(i).type())) return false; return true; default: return false; } } bool SzlOps::IsComplex() const { return flat_ops_ != NULL; } // Count the number of elements in the flattened rep. The argument "is_complex" // will be set to "true" for hierarchical structures, such as tuples with a // map or array field, or maps/arrays with. Note that a map itself is only // complex if either the index or element (or both) are non-base types. However, // a tuple of a map (even a "simple" map) is always complex. // Note: is_complex must be initialized to "false" before calling this function. static int SzlFlattenedVals(int depth, const SzlType& t, bool* is_complex) { if (t.BaseType()) { return 1; } else if (t.kind() == SzlType::MAP) { // If either the index or element type is a non-base type or the depth // is non-zero (= embedded map), then this map is complex. if (!t.index(0).type().BaseType() || !t.element()->type().BaseType() || depth > 0) { *is_complex = true; } return 1; } else if (t.kind() == SzlType::ARRAY) { // If either element type is a non-base type or the depth // is non-zero (= embedded array), then this map is complex. if (!t.element()->type().BaseType() || depth > 0) { *is_complex = true; } return 1; } else if (t.kind() == SzlType::TUPLE) { int n = 0; for (int i = 0; i < t.fields_size(); ++i) n += SzlFlattenedVals(depth + 1, t.field(i).type(), is_complex); return n; } else { LOG(FATAL) << "can't perform ops on " << t; } return 0; // Shouldn't get here. } // Create the flattened type array. static void SzlFlattenKinds(const SzlType& t, SzlType::Kind* flats, SzlOps** flat_ops, int* iota) { if (t.BaseType()) { flats[*iota] = t.kind(); ++*iota; } else if (t.kind() == SzlType::MAP || t.kind() == SzlType::ARRAY) { CHECK(flat_ops != NULL); flats[*iota] = t.kind(); flat_ops[*iota] = new SzlOps(t); ++*iota; } else if (t.kind() == SzlType::TUPLE) { for (int i = 0; i < t.fields_size(); ++i) { SzlFlattenKinds(t.field(i).type(), flats, flat_ops, iota); } } else { LOG(FATAL) << "can't perform ops on " << t; } } void SzlOps::Init() { // Maps and arrays are not type-flattened, hence special cases. if (type_.kind() == SzlType::MAP) { if (type_.indices_size() != 1) { LOG(FATAL) << "maps with multiple keys are not supported"; return; } const SzlType& index_type = type_.index(0).type(); const SzlType& element_type = type_.element()->type(); nflats_ = 2; // 1 key type and 1 value type. flats_ = new SzlType::Kind[nflats_]; flats_[0] = index_type.kind(); flats_[1] = element_type.kind(); // If the index or element is not a base type, then we're // dealing with a hierarchy. if (!index_type.BaseType() || !element_type.BaseType()) { flat_ops_ = new SzlOps*[nflats_]; flat_ops_[0] = index_type.BaseType() ? NULL : new SzlOps(index_type); flat_ops_[1] = element_type.BaseType() ? NULL : new SzlOps(element_type); } } else if (type_.kind() == SzlType::ARRAY) { const SzlType& element_type = type_.element()->type(); nflats_ = 1; // 1 value type. flats_ = new SzlType::Kind[nflats_]; flats_[0] = element_type.kind(); // If the element is not a base type, then we're dealing with a hierarchy. if (!element_type.BaseType()) { flat_ops_ = new SzlOps*[nflats_]; flat_ops_[0] = element_type.BaseType() ? NULL : new SzlOps(element_type); } } else { bool is_complex = false; // Must be initialized to "false". nflats_ = SzlFlattenedVals(0, type_, &is_complex); flats_ = new SzlType::Kind[nflats_]; // For complex structures we need to use embedded SzlOps for // certain values. if (is_complex) { flat_ops_ = new SzlOps*[nflats_]; memset(flat_ops_, 0, sizeof(flat_ops_) * nflats_); } int n = 0; SzlFlattenKinds(type_, flats_, flat_ops_, &n); CHECK_EQ(nflats_, n); } } SzlOps::SzlOps(const SzlType& type): type_(type), flat_ops_(NULL) { Init(); } SzlOps::SzlOps(const SzlOps& ops): type_(ops.type_), flat_ops_(NULL) { Init(); } void SzlOps::operator=(const SzlOps& ops) { // Check for self-assignment. if (&ops == this) return; // Delete old memory and re-initialize based on the new type. Delete(); type_ = ops.type_; Init(); } void SzlOps::Delete() { delete[] flats_; if (flat_ops_ != NULL) { for (int i = 0; i < nflats_; ++i) { delete flat_ops_[i]; } delete[] flat_ops_; } } SzlOps::~SzlOps() { Delete(); } // Return the amount of memory used to store s, nontrivial cases int SzlOps::MemoryInternal(const SzlValue& s) const { switch (type_.kind()) { case SzlType::TUPLE: case SzlType::ARRAY: case SzlType::MAP: { int mem = sizeof(SzlValue); if (s.s.len) { assert(type_.kind() != SzlType::TUPLE || s.s.len == nflats_); mem += s.s.len * sizeof(SzlValue); for (int i = 0; i < s.s.len; ++i) { int flat_i = i % nflats_; SzlType::Kind k = flats_[flat_i]; if (k == SzlType::STRING || k == SzlType::BYTES) { mem += s.s.vals[i].s.len; } else if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { // Need to subtract space for the type itself, since that is // already accounted for. Hence "- sizeof(SzlValue)". mem += flat_ops_[flat_i]->Memory(s.s.vals[i]) - sizeof(SzlValue); } else if (!IsSimpleBaseKind(k)) { LOG(FATAL) << "can't report memory usage for " << type_; return 0; } } } return mem; } default: LOG(FATAL) << "can't report memory usage for " << type_; return 0; } } void SzlOps::ClearInternal(SzlValue* val) const { switch (type_.kind()) { case SzlType::TUPLE: case SzlType::ARRAY: case SzlType::MAP: if (val->s.len) { assert(type_.kind() != SzlType::TUPLE || val->s.len == nflats_); for (int i = 0; i < val->s.len; ++i) { int flat_i = i % nflats_; SzlType::Kind k = flats_[flat_i]; if (k == SzlType::STRING || k == SzlType::BYTES) { delete[] val->s.vals[i].s.buf; val->s.vals[i].s.buf = NULL; val->s.vals[i].s.len = 0; } else if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { flat_ops_[flat_i]->Clear(&(val->s.vals[i])); } else if (!IsSimpleBaseKind(k)) { LOG(FATAL) << "can't clear for " << type_; return; } } delete[] val->s.vals; val->s.vals = NULL; val->s.len = 0; } break; default: LOG(FATAL) << "can't clear for " << type_; return; } } void SzlOps::AssignZero(SzlValue* val) const { switch (type_.kind()) { case SzlType::BOOL: case SzlType::FINGERPRINT: case SzlType::INT: case SzlType::TIME: val->i = 0; break; case SzlType::FLOAT: val->f = 0.0; break; case SzlType::STRING: case SzlType::BYTES: delete[] val->s.buf; val->s.buf = NULL; val->s.len = 0; break; case SzlType::TUPLE: { // We zero each of the tuple fields. Complex fields (maps and array) // are cleared (i.e., will become empty maps/arrays). SzlValue* vals = val->s.vals; if (vals == NULL) { vals = new SzlValue[nflats_]; val->s.vals = vals; val->s.len = nflats_; } else { assert(val->s.len == nflats_); } for (int i = 0; i < nflats_; ++i) { SzlType::Kind k = flats_[i]; if (flat_ops_ != NULL && flat_ops_[i] != NULL) { // Clear embedded structures (maps and arrays). flat_ops_[i]->Clear(&(vals[i])); } else if (k == SzlType::STRING || k == SzlType::BYTES) { delete[] vals[i].s.buf; vals[i].s.buf = NULL; vals[i].s.len = 0; } else if (k == SzlType::FLOAT) { vals[i].f = 0.0; } else if (IsSimpleBaseKind(k)) { vals[i].i = 0; } else { LOG(FATAL) << "can't assign zero for " << type_; return; } } break; } case SzlType::ARRAY: case SzlType::MAP: // "Zero" arrays and maps are completely empty, hence we can just clear // them. Clear(val); break; default: LOG(FATAL) << "can't assign zero for " << type_; return; } } // Cast every value to a double. // Only defined for INT and FLOAT elements, and tuples thereof. void SzlOps::ToFloat(const SzlValue& s, double* floats) const { switch (type_.kind()) { case SzlType::INT: floats[0] = s.i; break; case SzlType::FLOAT: floats[0] = s.f; break; case SzlType::TUPLE: if (s.s.len) { assert(s.s.len == nflats_); for (int i = 0; i < nflats_; ++i) { SzlType::Kind k = flats_[i]; if (k == SzlType::FLOAT) { floats[i] = s.s.vals[i].f; } else if (k == SzlType::INT) { floats[i] = s.s.vals[i].i; } else { LOG(FATAL) << "can't convert to float for " << type_; return; } } } else { for (int i = 0; i < nflats_; ++i) floats[i] = 0.; } break; default: LOG(FATAL) << "can't convert to float for " << type_; return; } } // Replace the string/bytes storage for val with buf static void ReplaceSzlValueBuf(const char* buf, int len, SzlValue* val) { // Make sure we don't smash ourselves. if (buf == val->s.buf) { CHECK_EQ(len, val->s.len); return; } if (val->s.len != len) { // Don't want to perform unnecessary reallocs. delete[] val->s.buf; val->s.len = len; if (len == 0) { val->s.buf = NULL; return; } val->s.buf = new char[len]; } if (buf != NULL && len > 0) { memmove(val->s.buf, buf, len); } } void SzlOps::AssignRange(const SzlValue& s, int start, int end, SzlValue* d) const { if (type_.kind() == SzlType::TUPLE || type_.kind() == SzlType::ARRAY || type_.kind() == SzlType::MAP) { if (s.s.len != d->s.len) { // If this is a tuple, then either the source or destination is empty. CHECK(type_.kind() != SzlType::TUPLE || s.s.len == 0 || d->s.len == 0); Clear(d); } if (s.s.len) { if (type_.kind() == SzlType::TUPLE) { CHECK_EQ(s.s.len, nflats_); } CHECK_GE(start, 0); CHECK_LE(end, s.s.len); CHECK_LE(start, end); SzlValue* svals = s.s.vals; SzlValue* dvals = d->s.vals; if (dvals == NULL) { dvals = new SzlValue[s.s.len]; d->s.vals = dvals; d->s.len = s.s.len; } else { CHECK_EQ(s.s.len, d->s.len); if (dvals == svals) { // Self assignment. return; } } for (int i = start; i < end; ++i) { int flat_i = i % nflats_; SzlType::Kind k = flats_[flat_i]; if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { flat_ops_[flat_i]->Assign(svals[i], &(dvals[i])); } else if (k == SzlType::STRING || k == SzlType::BYTES) { ReplaceSzlValueBuf(svals[i].s.buf, svals[i].s.len, &dvals[i]); } else if (k == SzlType::FLOAT) { dvals[i].f = svals[i].f; } else if (IsSimpleBaseKind(k)) { dvals[i].i = svals[i].i; } else { LOG(FATAL) << "can't assign for " << type_ << " at pos " << i; return; } } } } else { if (start + 1 != end || start != 0) { LOG(FATAL) << "can't assign range from " << start << " to " << end << " for " << type_; return; } Assign(s, d); } } void SzlOps::AssignAtPos(const SzlValue& s, int pos, SzlValue* d) const { AssignRange(s, pos, pos + 1, d); } // d = s; takes care of memory allocation. void SzlOps::Assign(const SzlValue& s, SzlValue* d) const { switch (type_.kind()) { case SzlType::BOOL: case SzlType::FINGERPRINT: case SzlType::INT: case SzlType::TIME: d->i = s.i; break; case SzlType::FLOAT: d->f = s.f; break; case SzlType::STRING: case SzlType::BYTES: ReplaceSzlValueBuf(s.s.buf, s.s.len, d); break; case SzlType::TUPLE: case SzlType::ARRAY: case SzlType::MAP: // Self assignment or empty assignment (NULL pointers)? if (s.s.vals == d->s.vals) { break; } // Assign the full range. AssignRange(s, 0, s.s.len, d); break; default: LOG(FATAL) << "can't assign for " << type_; return; } } SzlValue* SzlOps::SzlFlatValueAt(int pos, SzlValue* v, SzlType::Kind expected_kind) const { assert(pos >= 0 && pos < nflats_); if (flats_[pos] != expected_kind) { LOG(FATAL) << "can't get flat value at " << pos << " for " << type_ << ": expected kind " << expected_kind << " but found " << flats_[pos]; return NULL; } if (type_.kind() == SzlType::TUPLE) { SzlValue* vals = v->s.vals; if (vals == NULL) { vals = new SzlValue[nflats_]; v->s.vals = vals; v->s.len = nflats_; } v = &vals[pos]; } else { assert(nflats_ == 1); } return v; } // Put each basic type at the given flattened position. // REQUIRES: pos >= 0, pos < nflats() void SzlOps::PutBool(bool b, int pos, SzlValue* d) const { d = SzlFlatValueAt(pos, d, SzlType::BOOL); d->i = b; } void SzlOps::PutBytes(const char* s, int len, int pos, SzlValue* d) const { d = SzlFlatValueAt(pos, d, SzlType::BYTES); ReplaceSzlValueBuf(s, len, d); } void SzlOps::PutFloat(double f, int pos, SzlValue* d) const { d = SzlFlatValueAt(pos, d, SzlType::FLOAT); d->f = f; } void SzlOps::PutInt(int64 i, int pos, SzlValue* d) const { d = SzlFlatValueAt(pos, d, SzlType::INT); d->i = i; } void SzlOps::PutFingerprint(uint64 fp, int pos, SzlValue* d) const { d = SzlFlatValueAt(pos, d, SzlType::FINGERPRINT); d->i = fp; } void SzlOps::PutTime(uint64 t, int pos, SzlValue* d) const { d = SzlFlatValueAt(pos, d, SzlType::TIME); d->i = t; } void SzlOps::PutString(const char* s, int len, int pos, SzlValue* d) const { d = SzlFlatValueAt(pos, d, SzlType::STRING); // Internally, szl strings must be null terminated, // and empty strings must have length 0. if (len == 0) { delete[] d->s.buf; d->s.buf = NULL; d->s.len = 0; } else { ReplaceSzlValueBuf(s, len + 1, d); } } // d = -s, nontrivial cases void SzlOps::NegateInternal(const SzlValue& s, SzlValue* d) const { switch (type_.kind()) { case SzlType::TUPLE: case SzlType::ARRAY: case SzlType::MAP: if (s.s.len != d->s.len) { // If this is a tuple, then either the source or destination is empty. CHECK(type_.kind() != SzlType::TUPLE || s.s.len == 0 || d->s.len == 0); Clear(d); } if (s.s.len) { SzlValue* dvals = d->s.vals; SzlValue* svals = s.s.vals; if (dvals == NULL) { dvals = new SzlValue[s.s.len]; d->s.vals = dvals; d->s.len = s.s.len; } else { CHECK(d->s.len == s.s.len); } // Maps must have 1 key type and 1 value type. CHECK(type_.kind() != SzlType::MAP || nflats_ == 2); for (int i = 0; i < s.s.len; ++i) { int flat_i = i % nflats_; SzlType::Kind k = flats_[flat_i]; // For maps, we only want to negate the values, not the keys! // Keys must be copied instead. if ((i & 1) == 0 && type_.kind() == SzlType::MAP) { // This is a map key! Copy. AssignAtPos(s, i, d); } else { // Map value or tuple / array element. if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { flat_ops_[flat_i]->Negate(svals[i], &(dvals[i])); } else if (k == SzlType::FLOAT) { dvals[i].f = -s.s.vals[i].f; } else if (IsSimpleBaseKind(k)) { dvals[i].i = -s.s.vals[i].i; } else { LOG(FATAL) << "can't negate for " << type_; return; } } } } break; default: LOG(FATAL) << "can't negate for " << type_; return; } } // Candidate for inlining, needs to be measured. // static int SzlOps::CmpStr(const SzlValue* s0, const SzlValue* s1) { // Deal with NULL strings. A NULL string and an empty string // are equal, but a non-empty string is always more than a // NULL/empty string. if (s0 == NULL && s1 == NULL) { return 0; } else if (s0 == NULL) { assert(s1 != NULL); return CmpBaseT(0, s1->s.len); } else if (s1 == NULL) { assert(s0 != NULL); return CmpBaseT(s0->s.len, 0); } assert(s0 != NULL); assert(s1 != NULL); int len = s0->s.len; if (len > s1->s.len) { len = s1->s.len; } int c = memcmp(s0->s.buf, s1->s.buf, len); if (c == 0) { return CmpBaseT(s0->s.len, s1->s.len); } return c; } // Used for comparing flattened fields. It remains to be seen whether it's // worth looking into type traits for those. // static int SzlOps::CmpBase(SzlType::Kind kind, const SzlValue* s0, const SzlValue* s1) { switch (kind) { case SzlType::INT: return CmpBaseT(s0 == NULL ? 0 : s0->i, s1 == NULL ? 0 : s1->i); case SzlType::BOOL: case SzlType::FINGERPRINT: case SzlType::TIME: return CmpBaseT(s0 == NULL ? 0ULL : static_cast<uint64>(s0->i), s1 == NULL ? 0ULL : static_cast<uint64>(s1->i)); case SzlType::FLOAT: return CmpBaseT(s0 == NULL ? 0.0 : s0->f, s1 == NULL ? 0.0 : s1->f); case SzlType::STRING: case SzlType::BYTES: return CmpStr(s0, s1); default: LOG(FATAL) << "not a base kind: " << kind; return false; }; } // Returns -1 if s0 < s1, 0 if s0 == s1 and +1 if s0 > s1 , nontrivial cases int SzlOps::CmpInternal(const SzlValue* s0, const SzlValue* s1) const { switch (type_.kind()) { case SzlType::TUPLE: case SzlType::ARRAY: case SzlType::MAP: { const SzlValue* v0 = (s0 != NULL ? s0->s.vals : NULL); const SzlValue* v1 = (s1 != NULL ? s1->s.vals : NULL); int len0 = (s0 != NULL ? s0->s.len : 0); int len1 = (s1 != NULL ? s1->s.len : 0); if (len0 == 0 && len1 == 0) { return 0; } int len = nflats_; // An empty map/array is always smaller than a non-empty map/array, // which is not necessarily the case for tuples. if (type_.kind() == SzlType::MAP || type_.kind() == SzlType::ARRAY) { if (len0 == 0) { assert(len1 > 0); return -1; } else if (len1 == 0) { assert(len0 > 0); return 1; } assert(len0 > 0); assert(len1 > 0); len = MinInt(len0, len1); } else if (type_.kind() == SzlType::TUPLE) { assert(len0 == nflats_ || len0 == 0); assert(len1 == nflats_ || len1 == 0); } assert(len > 0); // Note: maps are compared on an key-value pair basis. I.e., first key[0] // is compared, then value[0], then key[1], etc. for (int i = 0; i < len; ++i) { int flat_i = i % nflats_; int res = 0; const SzlValue* v0_i = (len0 != 0 ? v0 + i : NULL); const SzlValue* v1_i = (len1 != 0 ? v1 + i : NULL); if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { res = flat_ops_[flat_i]->Cmp(v0_i, v1_i); } else { res = CmpBase(flats_[flat_i], v0_i, v1_i); } if (res != 0) { return res; } } // If this is a tuple, we're done -- the tuples are the same. if (type_.kind() == SzlType::TUPLE) { return 0; } // This is a map or array. One map/array is a superset of the other // map/array. return CmpBaseT(len0, len1); } default: LOG(FATAL) << "can't compare for " << type_; return 0; } } bool SzlOps::LessAtPos(const SzlValue& s0, int pos, const SzlValue& s1) const { if (type_.kind() != SzlType::TUPLE) { assert(pos == 0); return Less(s0, s1); } assert(pos < nflats_); SzlType::Kind k = flats_[pos]; // We only support base kinds (thus we only support "simple" tuples). if (!SzlType::BaseKind(k)) { LOG(FATAL) << "can't compare at position " << pos << " for " << type_; return false; } const SzlValue* v0 = s0.s.vals; const SzlValue* v1 = s1.s.vals; int len0 = s0.s.len; int len1 = s1.s.len; if (!len0) { if (!len1) return false; assert(len1 == nflats_); if (k == SzlType::STRING || k == SzlType::BYTES) { // empty string always less than non-empty string. return v1[pos].s.len; } else if (k == SzlType::FLOAT) { return 0. < v1[pos].f; } else if (k == SzlType::INT) { return 0 < v1[pos].i; } else { return 0 < static_cast<uint64>(v1[pos].i); } } else if (!len1) { assert(len0 == nflats_); // can never be < empty string or unsigned 0. if (k == SzlType::FLOAT) { return v0[pos].f < 0.; } else if (k == SzlType::INT) { return v0[pos].i < 0; } } else { assert(len0 == nflats_); assert(len1 == nflats_); if (k == SzlType::STRING || k == SzlType::BYTES) { return (CmpStr(v0 + pos, v1 + pos) < 0); } else if (k == SzlType::FLOAT) { return v0[pos].f < v1[pos].f; } else if (k == SzlType::INT) { return v0[pos].i < v1[pos].i; } else { return static_cast<uint64>(v0[pos].i) < static_cast<uint64>(v1[pos].i); } } return false; } // d += s , nontrivial cases void SzlOps::AddInternal(const SzlValue& s, SzlValue* d) const { switch (type_.kind()) { case SzlType::TUPLE: if (s.s.len) { if (!d->s.len) { Assign(s, d); return; } assert(s.s.len == nflats_); for (int i = 0; i < nflats_; ++i) { SzlType::Kind k = flats_[i]; if (flat_ops_ != NULL && flat_ops_[i] != NULL) { flat_ops_[i]->Add(s.s.vals[i], &(d->s.vals[i])); } else if (k == SzlType::FLOAT) { d->s.vals[i].f += s.s.vals[i].f; } else if (IsSimpleBaseKind(k)) { d->s.vals[i].i += s.s.vals[i].i; } else { LOG(FATAL) << "can't add for " << type_; return; } } } break; case SzlType::MAP: if (s.s.len) { if (!d->s.len) { Assign(s, d); return; } // When maps are emitted, the elements are sorted by key. This // allows us to quickly sum two maps. Therefore, our output // map should also be sorted again. Our strategy is as follows: // - Determine the index of the source and destination elements in // the summed map (sorted order). For example: // { a:0, b:1, e:3 } -> 0, 1, 4 // { b:1, c:4 } -> 1, 2 // - Add the elements. If the size of the destination map changes, // allocate a new array. // Thus, we need to make two passes over the elements, but we // only need to compare keys once. There is no real alternative, // since we need to know how large the resulting map is going to // be before we can start adding elements. if (type_.indices_size() != 1) { LOG(FATAL) << "maps with multiple keys are not supported"; return; } if (nflats_ != 2) { LOG(FATAL) << "unexpected number of key/value types (" << nflats_ << ")"; return; } assert(nflats_ == 2); SzlOps* key_ops = NULL; SzlType::Kind key_kind = flats_[0]; if (flat_ops_ != NULL && flat_ops_[0] != NULL) { key_ops = flat_ops_[0]; } SzlOps* value_ops = NULL; SzlType::Kind value_kind = flats_[1]; if (flat_ops_ != NULL && flat_ops_[1] != NULL) { value_ops = flat_ops_[1]; } // First pass: compare keys. vector<int> s_target_i; vector<int> d_target_i; vector<bool> s_target_copy; s_target_i.reserve(s.s.len); d_target_i.reserve(d->s.len); s_target_copy.reserve(s.s.len); int s_i = 0; int d_i = 0; int target_i = 0; while (s_i < s.s.len || d_i < d->s.len) { if (s_i < s.s.len && d_i < d->s.len) { int cmp_res = 0; if (key_ops != NULL) { cmp_res = key_ops->Cmp(s.s.vals + s_i, d->s.vals + d_i); } else { cmp_res = CmpBase( key_kind, s.s.vals + s_i, d->s.vals + d_i); } if (cmp_res < 0 || cmp_res == 0) { s_target_i.push_back(target_i); s_target_copy.push_back(cmp_res != 0); s_i += nflats_; } if (cmp_res > 0 || cmp_res == 0) { d_target_i.push_back(target_i); d_i += nflats_; } } else if (s_i < s.s.len) { assert(d_i >= d->s.len); s_target_i.push_back(target_i); s_target_copy.push_back(true); s_i += nflats_; } else { assert(d_i < d->s.len); d_target_i.push_back(target_i); d_i += nflats_; } ++target_i; } assert(s_target_i.size() * nflats_ == s.s.len); assert(d_target_i.size() * nflats_ == d->s.len); assert(s_target_i.size() == s_target_copy.size()); // Now know the number of target elements: target_i. // Second pass: Copy destination elements (if needed). int new_d_len = target_i * nflats_; if (new_d_len > d->s.len) { SzlValue* new_vals = new SzlValue[new_d_len]; // Put the values in the right locations. for (int i = 0; i < d_target_i.size(); ++i) { // We take ownership of all pointers and such. Effectively, we're // performing a swap here. memcpy(new_vals + d_target_i[i] * nflats_, d->s.vals + i * nflats_, sizeof(SzlValue) * nflats_); } delete [] d->s.vals; d->s.vals = new_vals; d->s.len = new_d_len; } // Add source to destination. for (int i = 0; i < s_target_i.size(); ++i) { // If this is a new key, just copy the results. if (s_target_copy[i]) { for (int z = 0; z < nflats_; ++z) { int s_j = i * nflats_ + z; int d_j = s_target_i[i] * nflats_ + z; assert(d_j < d->s.len); int flat_j = d_j % nflats_; SzlType::Kind k = flats_[flat_j]; if (flat_ops_ != NULL && flat_ops_[flat_j] != NULL) { flat_ops_[flat_j]->Assign(s.s.vals[s_j], &(d->s.vals[d_j])); } else if (k == SzlType::STRING || k == SzlType::BYTES) { ReplaceSzlValueBuf(s.s.vals[s_j].s.buf, s.s.vals[s_j].s.len, &d->s.vals[d_j]); } else if (k == SzlType::FLOAT) { d->s.vals[d_j].f = s.s.vals[s_j].f; } else if (IsSimpleBaseKind(k)) { d->s.vals[d_j].i = s.s.vals[s_j].i; } else { LOG(FATAL) << "can't add for " << type_; return; } } } else { int s_j = i * nflats_ + (nflats_ - 1); int d_j = s_target_i[i] * nflats_ + (nflats_ - 1); // Sum source to destination. if (value_ops) { value_ops->Add(s.s.vals[s_j], &(d->s.vals[d_j])); } else if (value_kind == SzlType::FLOAT) { d->s.vals[d_j].f += s.s.vals[s_j].f; } else if (IsSimpleBaseKind(value_kind)) { d->s.vals[d_j].i += s.s.vals[s_j].i; } else { LOG(FATAL) << "can't add for " << type_; return; } } } } break; default: LOG(FATAL) << "can't add for " << type_; return; } } // d -= s void SzlOps::Sub(const SzlValue& s, SzlValue* d) const { switch (type_.kind()) { case SzlType::BOOL: case SzlType::FINGERPRINT: case SzlType::INT: case SzlType::TIME: d->i -= s.i; break; case SzlType::FLOAT: d->f -= s.f; break; case SzlType::TUPLE: if (s.s.len) { assert(s.s.len == nflats_); if (!d->s.len) { Negate(s, d); return; } for (int i = 0; i < nflats_; ++i) { SzlType::Kind k = flats_[i]; if (flat_ops_ != NULL && flat_ops_[i] != NULL) { flat_ops_[i]->Sub(s.s.vals[i], &(d->s.vals[i])); } else if (k == SzlType::FLOAT) { d->s.vals[i].f -= s.s.vals[i].f; } else { d->s.vals[i].i -= s.s.vals[i].i; } } } break; default: LOG(FATAL) << "can't sub for " << type_; return; } } void SzlOps::AppendToString(const SzlValue& v, string* output) const { SzlEncoder enc; Encode(v, &enc); enc.Swap(output); } bool SzlOps::ParseFromArray(const char* buf, int len, SzlValue* val) const { SzlDecoder dec(buf, len); return Decode(&dec, val); } static inline void SzlOpsDoEncode(SzlType::Kind kind, const SzlValue& s, SzlEncoder* enc) { switch (kind) { case SzlType::BOOL: enc->PutBool(s.i); break; case SzlType::FINGERPRINT: enc->PutFingerprint(s.i); break; case SzlType::INT: enc->PutInt(s.i); break; case SzlType::TIME: enc->PutTime(s.i); break; case SzlType::FLOAT: enc->PutFloat(s.f); break; case SzlType::STRING: { const char* buf = s.s.buf; int len; if (buf == NULL) { buf = ""; len = 0; } else { len = s.s.len - 1; // exclude terminating zero } enc->PutString(buf, len); } break; case SzlType::BYTES: enc->PutBytes(s.s.buf, s.s.len); break; default: LOG(FATAL) << "can't encode for kind " << kind; break; } } // Encode a value to enc. static void EncodeDefaultBase(SzlType::Kind kind, SzlEncoder* enc) { switch (kind) { case SzlType::BOOL: enc->PutBool(false); break; case SzlType::FINGERPRINT: enc->PutFingerprint(0); break; case SzlType::INT: enc->PutInt(0); break; case SzlType::TIME: enc->PutTime(0); break; case SzlType::FLOAT: enc->PutFloat(0); break; case SzlType::STRING: enc->PutString("", 0); break; case SzlType::BYTES: enc->PutBytes("", 0); break; default: LOG(FATAL) << "can't encode for " << kind; break; } } // Encode a value to enc. void SzlOps::EncodeDefault(SzlEncoder* enc) const { if (type_.kind() == SzlType::TUPLE) { for (int i = 0; i < nflats_; ++i) { int flat_i = i % nflats_; if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { flat_ops_[flat_i]->EncodeDefault(enc); } else { EncodeDefaultBase(flats_[flat_i], enc); } } } else if (type_.kind() != SzlType::MAP) { EncodeDefaultBase(type_.kind(), enc); } } // Encode a value to enc. void SzlOps::EncodeInternal(const SzlValue& s, SzlEncoder* enc, bool top_level) const { if (type_.kind() == SzlType::TUPLE) { if (!top_level) { enc->Start(type_.kind()); } if (s.s.len) { assert(s.s.len == nflats_); for (int i = 0; i < s.s.len; ++i) { if (flat_ops_ != NULL && flat_ops_[i] != NULL) { flat_ops_[i]->EncodeInternal(s.s.vals[i], enc, false); } else { SzlOpsDoEncode(flats_[i], s.s.vals[i], enc); } } } else { EncodeDefault(enc); } if (!top_level) { enc->End(type_.kind()); } } else if (type_.kind() == SzlType::MAP || type_.kind() == SzlType::ARRAY) { enc->Start(type_.kind()); // A map is variable length and hence we need to explicitly encode the // length. Actually, we don't have to, but it's more efficient for // decoding. This is true for arrays too, but originally arrays were not // supported here and the code that emits arrays (in sawzall) doesn't emit // the length. We should consider fixing this at some point. if (type_.kind() == SzlType::MAP) { enc->PutInt(s.s.len); } if (s.s.len) { for (int i = 0; i < s.s.len; ++i) { int flat_i = i % nflats_; if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { flat_ops_[flat_i]->EncodeInternal(s.s.vals[i], enc, false); } else { SzlOpsDoEncode(flats_[flat_i], s.s.vals[i], enc); } } } enc->End(type_.kind()); } else { SzlOpsDoEncode(type_.kind(), s, enc); } } // Encode a value to enc. void SzlOps::Encode(const SzlValue& s, SzlEncoder* enc) const { EncodeInternal(s, enc, true); } // Decode a value from dec. static inline bool SzlOpsDoDecode(SzlType::Kind kind, SzlDecoder* dec, SzlValue* val) { switch (kind) { case SzlType::BOOL: { bool v; if (!dec->GetBool(&v)) return false; val->i = v; } break; case SzlType::FINGERPRINT: { uint64 v; if (!dec->GetFingerprint(&v)) return false; val->i = v; } break; case SzlType::INT: return dec->GetInt(&val->i); case SzlType::TIME: { uint64 v; if (!dec->GetTime(&v)) return false; val->i = v; } break; case SzlType::FLOAT: return dec->GetFloat(&val->f); case SzlType::STRING: { string str; if (!dec->GetString(&str)) return false; // Internally, szl strings must be null terminated, // and empty strings must have length 0. if (str.size() == 0) { delete[] val->s.buf; val->s.buf = NULL; val->s.len = 0; } else { ReplaceSzlValueBuf(str.c_str(), str.size() + 1, val); } } break; case SzlType::BYTES: { string str; if (!dec->GetBytes(&str)) return false; ReplaceSzlValueBuf(str.data(), str.size(), val); } break; default: LOG(ERROR) << "cannot decode for kind " << kind << " (\"" << SzlType::KindName(kind) << "\") -- not supported"; return false; } return true; } // Decode a value from dec. bool SzlOps::DecodeInternal(SzlDecoder* dec, SzlValue* val, bool top_level) const { if (type_.kind() == SzlType::TUPLE) { if (!top_level && !dec->GetStart(type_.kind())) { LOG(ERROR) << "Unable to get tuple start"; return false; } if (!val->s.len) { CHECK(val->s.vals == NULL); val->s.vals = new SzlValue[nflats_]; val->s.len = nflats_; } assert(val->s.len == nflats_); for (int i = 0; i < nflats_; ++i) { if (flat_ops_ != NULL && flat_ops_[i] != NULL) { if (!flat_ops_[i]->DecodeInternal(dec, &val->s.vals[i], false)) { return false; } } else { if (!SzlOpsDoDecode(flats_[i], dec, &val->s.vals[i])) { return false; } } } if (!top_level && !dec->GetEnd(type_.kind())) { LOG(ERROR) << "Unable to get tuple end"; return false; } } else if (type_.kind() == SzlType::MAP || type_.kind() == SzlType::ARRAY) { int64 len = 0; if (!dec->GetStart(type_.kind())) { LOG(ERROR) << "Unable to get the map/array start"; return false; } // Get the length of the map or array. Arrays don't emit their size and // hence we need to first count the number of elements. This is obviously // not very efficient and we should consider changing the way arrays are // emitted. if (type_.kind() == SzlType::MAP) { if (!dec->GetInt(&len)) { LOG(ERROR) << "Unable to get the length of the map"; return false; } } else { // Create a temporary decoder that we'll use to count the number // of elements in the array. CHECK_EQ(nflats_, 1); // Array always have a single value type. SzlDecoder dec2(dec->position(), static_cast<int>(dec->end() - dec->position())); while (!dec2.done()) { // End of array? if (dec2.IsEnd(type_.kind())) { break; } // Got an element. Skip it. if (flat_ops_ != NULL && flat_ops_[0] != NULL) { if (!flat_ops_[0]->SkipInternal(&dec2, false)) { LOG(ERROR) << "Unable to count length of array"; return false; } } else if (!dec2.Skip(flats_[0])) { LOG(ERROR) << "Unable to count length of array"; return false; } ++len; } } if (len != val->s.len) { Clear(val); } if (len > 0 && len != val->s.len) { CHECK(val->s.vals == NULL); val->s.vals = new SzlValue[len]; val->s.len = len; } for (int i = 0; i < val->s.len; ++i) { int flat_i = i % nflats_; if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { if (!flat_ops_[flat_i]->DecodeInternal(dec, &val->s.vals[i], false)) { return false; } } else if (!SzlOpsDoDecode(flats_[flat_i], dec, &val->s.vals[i])) { return false; } } if (!dec->GetEnd(type_.kind())) { LOG(ERROR) << "Unable to get map/array end"; return false; } } else { return SzlOpsDoDecode(type_.kind(), dec, val); } return true; } // Decode a value from dec. bool SzlOps::Decode(SzlDecoder* dec, SzlValue* val) const { return DecodeInternal(dec, val, true); } // Skip the value in dec. Returns whether the value had the correct form. bool SzlOps::SkipInternal(SzlDecoder* dec, bool top_level) const { switch (type_.kind()) { case SzlType::BOOL: case SzlType::BYTES: case SzlType::FINGERPRINT: case SzlType::INT: case SzlType::FLOAT: case SzlType::STRING: case SzlType::TIME: return dec->Skip(type_.kind()); case SzlType::TUPLE: if (!top_level && !dec->GetStart(type_.kind())) { return false; } for (int i = 0; i < nflats_; ++i) { if (flat_ops_ != NULL && flat_ops_[i] != NULL) { if (!flat_ops_[i]->SkipInternal(dec, false)) { return false; } } else if (!dec->Skip(flats_[i])) { return false; } } if (!top_level && !dec->GetEnd(type_.kind())) { return false; } break; case SzlType::MAP: if (!dec->GetStart(type_.kind())) { return false; } // Must get the length, can't skip that. { int64 len = 0; if (!dec->GetInt(&len)) { LOG(ERROR) << "Unable to get the length of the map"; return false; } for (int i = 0; i < len; ++i) { int flat_i = i % nflats_; if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { if (!flat_ops_[flat_i]->SkipInternal(dec, false)) { return false; } } else if (!dec->Skip(flats_[flat_i])) { return false; } } } if (!dec->GetEnd(type_.kind())) { return false; } break; case SzlType::ARRAY: if (!dec->GetStart(type_.kind())) { return false; } for (int i = 0; !dec->done(); ++i) { if (dec->IsEnd(type_.kind())) { break; } int flat_i = i % nflats_; if (flat_ops_ != NULL && flat_ops_[flat_i] != NULL) { if (!flat_ops_[flat_i]->SkipInternal(dec, false)) { return false; } } else if (!dec->Skip(flats_[flat_i])) { return false; } } if (!dec->GetEnd(type_.kind())) { return false; } break; // Can't handle other types. default: return false; } return true; } // Skip the value in dec. Returns whether the value had the correct form. bool SzlOps::Skip(SzlDecoder* dec) const { return SkipInternal(dec, true); }
[ "bgibbons@google.com@413cfee2-6280-6547-3bd8-6f5aabe6079b" ]
bgibbons@google.com@413cfee2-6280-6547-3bd8-6f5aabe6079b
dff5f16c94941cd8dc0dd21ff116253e4a43941d
5ff2e8d0d272f7a61ecb6cdf583d35e549cbb88a
/cpp/datatype/char.cpp
1a04e3650122a887b8c5c3419924a404ab465d25
[]
no_license
qjh817937/programming-language
9226b40585a8828498d668cf7abc47c57837897d
b99abd016affd9cd15d1b1ef5d6255b83439597d
refs/heads/master
2021-05-16T02:24:14.605597
2017-09-02T14:36:52
2017-09-02T14:36:52
32,622,312
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
#include "stdio.h" void test() { const int num = 300; char str[num]; for(int i = 0; i < num;i++) { str[i] = (char)i; int a = str[i]; printf("%c %d %u %x %d %d %d\n",str[i], str[i], str[i], str[i], a, +str[i], i); } } int main() { test(); }
[ "jianshen@taobao.com" ]
jianshen@taobao.com
3b72efad92a9b97f9083b5ba83360f2287175ac7
1ad82995bbedf2b62dea4eef1bdb12fca075cc15
/Lecture-03 Recursion Continued/merge_sort.cpp
aab160823d2bd1c2862b6a0a4dfdf8f2b8746505
[]
no_license
suryanshbhar/cbalgo-
415a8dfed5e48afd54d866d24ab6847d18c4ea1f
7624d464ff198bfaec10c16da5858870d8956166
refs/heads/master
2020-06-20T16:38:31.678653
2019-07-16T11:41:22
2019-07-16T11:41:22
197,180,684
1
0
null
null
null
null
UTF-8
C++
false
false
830
cpp
#include<iostream> using namespace std; void merge(int *arr,int s,int e){ int mid = (s+e)/2; int i = s; int j = mid+1; int k = s; int temp[1000]; while(i<=mid and j<=e){ if(arr[i]<arr[j]){ temp[k++] = arr[i++]; } else{ temp[k++] = arr[j++]; } } //copy the remaining elements while(i<=mid){ temp[k++] = arr[i++]; } while(j<=e){ temp[k++] = arr[j++]; } //final step //copy the elements back to arr for(int i=s;i<=e;i++){ arr[i] = temp[i]; } } void mergeSort(int *arr,int s,int e){ //base case if(s>=e){ return; } //rec case int mid = (s+e)/2; mergeSort(arr,s,mid); mergeSort(arr,mid+1,e); merge(arr,s,e); return; } int main(){ int arr[] = {5,1,2,0,7,9,6}; int n = sizeof(arr)/sizeof(int); mergeSort(arr,0,n-1); for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } return 0; }
[ "prateeknarang111@gmail.com" ]
prateeknarang111@gmail.com
47bfec0ac7450b75908f4e53353700fde0890242
948a69c723fabb12af7e28a99e8665e94a0453c0
/Temperature Sensor (LM35)/lm35_temp_sensor_sketch/lm35_temp_sensor_sketch.ino
958321bee0faf08b6b05eb98b93cad82ac44cf5c
[]
no_license
PanMaster13/ArdurinoLittleProjects
367c5957aff39130e41fc1f822c96851fd962280
75dea4aad80b73eaa8cd4305f419a06bed48a99b
refs/heads/master
2022-10-07T15:33:31.379829
2020-06-02T02:05:10
2020-06-02T02:05:10
251,235,622
0
0
null
null
null
null
UTF-8
C++
false
false
346
ino
int sensorValue; int sensorPin = 1; void setup() { Serial.begin(9600); } void loop() { // Obtain raw value from sensor (Not Celcius) sensorValue = analogRead(sensorPin); // Converting into Celcius float mv = (sensorValue/1024.0) * 5000; float cel = mv/10; Serial.print("Temperature: "); Serial.println(cel); delay(1000); }
[ "36907215+PanMaster13@users.noreply.github.com" ]
36907215+PanMaster13@users.noreply.github.com
14f4a1c35d9e3a0ab85e1bda406b076591f51073
ca56965a4b410ad1e66da520b3a9d859a402fb09
/gazebo/gazebo/rendering/CameraVisual.hh
6b6f3c7e6c9d66be171e4b5ebd7812af037814fb
[ "Apache-2.0" ]
permissive
UWARG/simSPIKE
46866b0a33b364e91fc4fda3662a03ae4652e4e5
69a5da0f409816e318a16da4e1a2b7b3efab6364
refs/heads/master
2021-05-04T10:32:15.667935
2016-11-06T04:17:38
2016-11-06T04:17:38
48,701,706
1
0
null
null
null
null
UTF-8
C++
false
false
1,881
hh
/* * Copyright (C) 2012-2014 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _CAMERAVISUAL_HH_ #define _CAMERAVISUAL_HH_ #include <string> #include "gazebo/msgs/MessageTypes.hh" #include "gazebo/rendering/Visual.hh" #include "gazebo/util/system.hh" namespace gazebo { namespace rendering { /// \addtogroup gazebo_rendering Rendering /// \{ class Camera; /// \class CameraVisual CameraVisual.hh rendering/rendering.hh /// \brief Basic camera visualization /// /// This class is used to visualize a camera image generated from /// a CameraSensor. The sensor's image is drawn on a billboard in the 3D /// environment. class GAZEBO_VISIBLE CameraVisual : public Visual { /// \brief Constructor /// \param[in] _name Name of the Visual /// \param[in] _vis Pointer to the parent Visual public: CameraVisual(const std::string &_name, VisualPtr _vis); /// \brief Destructor public: virtual ~CameraVisual(); /// \brief Load the Visual /// \param[in] _width Width of the Camera image /// \param[in] _height Height of the Camera image public: void Load(unsigned int _width, unsigned int _height); using Visual::Load; /// \brief Update the visual private: void Update(); }; /// \} } } #endif
[ "mehatfie@gmail.com" ]
mehatfie@gmail.com
a864a990db32ca5d5179aa0a56181a59a9cfbc2a
1c546675bc1ccb5bafda94975f5c9491805dc73a
/poc/emf4cpp/kevoree/NodeType.hpp
484f9fe434ac35c6538f3451b03de40094983c12
[]
no_license
Jean-Emile/kevoree-IoT
db05f7ed14d6916d7b0e26700c01691a2c167996
3b4177ea01dc07f19c3195309ffed53d066e9f76
refs/heads/master
2016-09-05T18:07:14.309159
2013-10-18T12:59:34
2013-10-18T12:59:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,029
hpp
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*- /* * kevoree/NodeType.hpp * Copyright (C) Cátedra SAES-UMU 2010 <andres.senac@um.es> * * EMF4CPP is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EMF4CPP is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef KEVOREE_NODETYPE_HPP #define KEVOREE_NODETYPE_HPP #include <kevoree_forward.hpp> #include <ecorecpp/mapping_forward.hpp> #include <ecore_forward.hpp> #include <kevoree/LifeCycleTypeDefinition.hpp> /*PROTECTED REGION ID(NodeType_pre) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ namespace kevoree { class NodeType: public virtual ::kevoree::LifeCycleTypeDefinition { public: NodeType(); virtual ~NodeType(); virtual void _initialize(); // Operations // Attributes // References ::ecorecpp::mapping::EList< ::kevoree::AdaptationPrimitiveType > & getManagedPrimitiveTypes(); ::ecorecpp::mapping::EList< ::kevoree::AdaptationPrimitiveTypeRef > & getManagedPrimitiveTypeRefs(); /*PROTECTED REGION ID(NodeType) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ // EObjectImpl virtual ::ecore::EJavaObject eGet(::ecore::EInt _featureID, ::ecore::EBoolean _resolve); virtual void eSet(::ecore::EInt _featureID, ::ecore::EJavaObject const& _newValue); virtual ::ecore::EBoolean eIsSet(::ecore::EInt _featureID); virtual void eUnset(::ecore::EInt _featureID); virtual ::ecore::EClass_ptr _eClass(); /*PROTECTED REGION ID(NodeTypeImpl) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ protected: // Attributes // References ::ecorecpp::mapping::out_ptr< ::ecorecpp::mapping::EList< ::kevoree::AdaptationPrimitiveType > > m_managedPrimitiveTypes; ::ecorecpp::mapping::out_ptr< ::ecorecpp::mapping::EList< ::kevoree::AdaptationPrimitiveTypeRef > > m_managedPrimitiveTypeRefs; }; } // kevoree #endif // KEVOREE_NODETYPE_HPP
[ "jedartois@gmail.com" ]
jedartois@gmail.com
bd7951134e5bb6eb733b825baa1f89eeea5d3d9f
9fe51daa213fcdf441456a2496b28d7f430bd344
/Algoritmo_V1/Algoritmo_V1.ino
38b336403d71fbf188168c3ff85268e435a63810
[]
no_license
jairoareyes/telecuidado
1b10207cbb652116849de8ecafa81fdda0405afe
5240b4002d19898435ff873f2ea2830aae1b957b
refs/heads/master
2020-06-25T16:48:05.730808
2019-07-29T03:14:28
2019-07-29T03:14:28
199,369,688
0
0
null
null
null
null
UTF-8
C++
false
false
2,295
ino
#include "teleciudadoLib.h" #define valvePin D5 #define pumpPin D7 #define analogInPin A0 #define REPORTING_PERIOD_MS 15000 char data; bool isTakePressureOn = false; void setup() { pinMode(valvePin,OUTPUT); pinMode(pumpPin,OUTPUT); Serial.begin(115200); Serial.println(" "); teleLib.initPulOxi(); } void loop() { teleLib.updatePulOxi(); if ((millis() - teleLib.tsLastReport2 > REPORTING_PERIOD_MS) && teleLib.isPulOxiOn) { float BPMProm=0; for (int i=0;i<teleLib.nSamples;i++){ BPMProm += teleLib.BPMArray[i]; } BPMProm = BPMProm/teleLib.nSamples; Serial.print("BPM Promedio: "); Serial.println(BPMProm); teleLib.nSamples=0; teleLib.shutdownPulOxi(); teleLib.isPulOxiOn=false; } if (Serial.available() > 0) { data = Serial.read(); if (data == '1'){ //Toma Pulso Oximetria Serial.println("Taking Pulse Oximeter"); teleLib.tsLastReport2 = millis(); teleLib.isPulOxiOn=true; } else if(data == '2'){ // Infla brazalete inflateCuff(); } else if(data == '3'){ // Toma la presion // poxi.begin(); // if (!poxi.begin()) { // Serial.println("FAILED"); // } // else { // Serial.println("SUCCESS"); // } // isTakePressureOn=true; takePressure(); } else if (data =='c'){ // Lee el valor de la presion float pressureValue=readPressure(); Serial.print("Presion: "); Serial.println(pressureValue); } } } void inflateCuff(){ float pressureValue = readPressure(); digitalWrite(valvePin,LOW); Serial.println("inflateCuff"); Serial.println(pressureValue); while (pressureValue<120){ digitalWrite(pumpPin,HIGH); pressureValue = readPressure(); } digitalWrite(pumpPin,LOW); } void takePressure(){ float pressureValue = readPressure(); Serial.println("Take Pressure"); while (pressureValue>50){ digitalWrite(valvePin,HIGH); pressureValue=readPressure(); Serial.println(pressureValue); } Serial.println("Finished!"); } float readPressure(){ float adcValue=0; for (int i=0; i<5; i++){ adcValue += analogRead(analogInPin); delay(5); } adcValue=adcValue/5; adcValue = (adcValue - 20.6); adcValue = adcValue/2.36; return adcValue; }
[ "jairo.314@hotmail.com" ]
jairo.314@hotmail.com
7e20ffb08851686e7e2b0d7d04bdd607b207d2d2
2e83a34664cbf86467bf3a03d559bf5017531824
/deps/boost-1.50.0/boost/test/utils/class_properties.hpp
a6a6bfa879256762fd0b02f98397db0f6f115750
[ "BSL-1.0" ]
permissive
argv0/riak-cxx
34c85e87de5fe3e026d650f85cac9139f9dadb1c
7ade8b30a5ba86511b5dc10ab6989804bde8f86d
refs/heads/master
2020-05-17T20:19:25.076003
2012-08-15T23:23:47
2012-08-15T23:23:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,508
hpp
// (C) Copyright Gennadiy Rozental 2001-2008. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 54633 $ // // Description : simple facility that mimmic notion of read-only read-write // properties in C++ classes. Original idea by Henrik Ravn. // *************************************************************************** #ifndef BOOST_TEST_CLASS_PROPERTIES_HPP_071894GER #define BOOST_TEST_CLASS_PROPERTIES_HPP_071894GER // Boost.Test #include <boost/test/detail/config.hpp> // Boost #if !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) #include <boost/preprocessor/seq/for_each.hpp> #endif #include <boost/call_traits.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/utility/addressof.hpp> // STL #include <iosfwd> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace riakboost { namespace unit_test { // ************************************************************************** // // ************** class_property ************** // // ************************************************************************** // template<class PropertyType> class class_property { protected: typedef typename call_traits<PropertyType>::const_reference read_access_t; typedef typename call_traits<PropertyType>::param_type write_param_t; typedef typename add_pointer<typename add_const<PropertyType>::type>::type address_res_t; public: // Constructor class_property() : value( PropertyType() ) {} explicit class_property( write_param_t init_value ) : value( init_value ) {} // Access methods operator read_access_t() const { return value; } read_access_t get() const { return value; } bool operator!() const { return !value; } address_res_t operator&() const { return &value; } // Data members #ifndef BOOST_TEST_NO_PROTECTED_USING protected: #endif PropertyType value; }; //____________________________________________________________________________// #ifdef BOOST_CLASSIC_IOSTREAMS template<class PropertyType> inline std::ostream& operator<<( std::ostream& os, class_property<PropertyType> const& p ) #else template<typename CharT1, typename Tr,class PropertyType> inline std::basic_ostream<CharT1,Tr>& operator<<( std::basic_ostream<CharT1,Tr>& os, class_property<PropertyType> const& p ) #endif { return os << p.get(); } //____________________________________________________________________________// #define DEFINE_PROPERTY_FREE_BINARY_OPERATOR( op ) \ template<class PropertyType> \ inline bool \ operator op( PropertyType const& lhs, class_property<PropertyType> const& rhs ) \ { \ return lhs op rhs.get(); \ } \ template<class PropertyType> \ inline bool \ operator op( class_property<PropertyType> const& lhs, PropertyType const& rhs ) \ { \ return lhs.get() op rhs; \ } \ template<class PropertyType> \ inline bool \ operator op( class_property<PropertyType> const& lhs, \ class_property<PropertyType> const& rhs ) \ { \ return lhs.get() op rhs.get(); \ } \ /**/ DEFINE_PROPERTY_FREE_BINARY_OPERATOR( == ) DEFINE_PROPERTY_FREE_BINARY_OPERATOR( != ) #undef DEFINE_PROPERTY_FREE_BINARY_OPERATOR #if BOOST_WORKAROUND(BOOST_MSVC, < 1300) #define DEFINE_PROPERTY_LOGICAL_OPERATOR( op ) \ template<class PropertyType> \ inline bool \ operator op( bool b, class_property<PropertyType> const& p ) \ { \ return b op p.get(); \ } \ template<class PropertyType> \ inline bool \ operator op( class_property<PropertyType> const& p, bool b ) \ { \ return b op p.get(); \ } \ /**/ DEFINE_PROPERTY_LOGICAL_OPERATOR( && ) DEFINE_PROPERTY_LOGICAL_OPERATOR( || ) #endif // ************************************************************************** // // ************** readonly_property ************** // // ************************************************************************** // template<class PropertyType> class readonly_property : public class_property<PropertyType> { typedef class_property<PropertyType> base_prop; typedef typename base_prop::address_res_t arrow_res_t; protected: typedef typename base_prop::write_param_t write_param_t; public: // Constructor readonly_property() {} explicit readonly_property( write_param_t init_value ) : base_prop( init_value ) {} // access methods arrow_res_t operator->() const { return riakboost::addressof( base_prop::value ); } }; //____________________________________________________________________________// #if BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) #define BOOST_READONLY_PROPERTY( property_type, friends ) riakboost::unit_test::readwrite_property<property_type > #else #define BOOST_READONLY_PROPERTY_DECLARE_FRIEND(r, data, elem) friend class elem; #define BOOST_READONLY_PROPERTY( property_type, friends ) \ class BOOST_JOIN( readonly_property, __LINE__ ) \ : public riakboost::unit_test::readonly_property<property_type > { \ typedef riakboost::unit_test::readonly_property<property_type > base_prop; \ BOOST_PP_SEQ_FOR_EACH( BOOST_READONLY_PROPERTY_DECLARE_FRIEND, ' ', friends ) \ typedef base_prop::write_param_t write_param_t; \ public: \ BOOST_JOIN( readonly_property, __LINE__ )() {} \ explicit BOOST_JOIN( readonly_property, __LINE__ )( write_param_t init_v ) \ : base_prop( init_v ) {} \ } \ /**/ #endif // ************************************************************************** // // ************** readwrite_property ************** // // ************************************************************************** // template<class PropertyType> class readwrite_property : public class_property<PropertyType> { typedef class_property<PropertyType> base_prop; typedef typename add_pointer<PropertyType>::type arrow_res_t; typedef typename base_prop::address_res_t const_arrow_res_t; typedef typename base_prop::write_param_t write_param_t; public: readwrite_property() : base_prop() {} explicit readwrite_property( write_param_t init_value ) : base_prop( init_value ) {} // access methods void set( write_param_t v ) { base_prop::value = v; } arrow_res_t operator->() { return riakboost::addressof( base_prop::value ); } const_arrow_res_t operator->() const { return riakboost::addressof( base_prop::value ); } #ifndef BOOST_TEST_NO_PROTECTED_USING using base_prop::value; #endif }; //____________________________________________________________________________// } // unit_test } // namespace riakboost //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> #undef BOOST_TEST_NO_PROTECTED_USING #endif // BOOST_TEST_CLASS_PROPERTIES_HPP_071894GER
[ "andy@andygross.org" ]
andy@andygross.org
bb9452ef2cbfc3192180e1e5d5952f983fdd4b5f
7b74a2a391d7f810b3e06c0a44d7fbb957a0d5e7
/function/passArguments.cc
954a452eb07ca538210b15b68f23a3ab81d009c6
[]
no_license
vambow/sololearn
a5f424208d730b59b329a947d6176497596d06ac
3b23ff91e5506433d2620d8c43e8f880998545d5
refs/heads/master
2020-09-20T15:00:29.268208
2019-11-30T02:32:39
2019-11-30T02:39:56
224,516,607
0
0
null
null
null
null
UTF-8
C++
false
false
228
cc
#include <iostream> using namespace std; void myFunc(int x) { x = 100; } void myFuncRefe(int *y){ *y=100; } int main() { int var = 20; int vari =20; myFunc(var); cout << var; myFuncRefe(&vari); cout<<vari; }
[ "vambow@icloud.com" ]
vambow@icloud.com
9079962a6c83d6eacfcca282c12987b53afeaa99
743dcee2eb0a2f97b60bfc0dc7939d63681f1fa8
/tag/demo_nov-13/Server/mongodb/mongo/client/syncclusterconnection.h
10baba9fdedb5a512df8c7df2a2ef0f060c9e9cd
[]
no_license
l0gicpath/scribble-websocket-server
e3e5f035055a8534e48853dc550e516b977b37c6
c86955abc71e4f9c856924a93ddb510a463eed95
refs/heads/master
2021-01-21T00:25:20.570140
2013-04-29T18:18:43
2013-04-29T18:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,347
h
// @file syncclusterconnection.h /* * Copyright 2010 10gen Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "mongo/bson/bsonelement.h" #include "mongo/bson/bsonobj.h" #include "mongo/client/dbclientinterface.h" namespace mongo { /** * This is a connection to a cluster of servers that operate as one * for super high durability. * * Write operations are two-phase. First, all nodes are asked to fsync. If successful * everywhere, the write is sent everywhere and then followed by an fsync. There is no * rollback if a problem occurs during the second phase. Naturally, with all these fsyncs, * these operations will be quite slow -- use sparingly. * * Read operations are sent to a single random node. * * The class checks if a command is read or write style, and sends to a single * node if a read lock command and to all in two phases with a write style command. */ class SyncClusterConnection : public DBClientBase { public: using DBClientBase::query; using DBClientBase::update; using DBClientBase::remove; /** * @param commaSeparated should be 3 hosts comma separated */ SyncClusterConnection( const list<HostAndPort> &, double socketTimeout = 0); SyncClusterConnection( string commaSeparated, double socketTimeout = 0); SyncClusterConnection( const std::string& a, const std::string& b, const std::string& c, double socketTimeout = 0 ); ~SyncClusterConnection(); /** * @return true if all servers are up and ready for writes */ bool prepare( string& errmsg ); /** * runs fsync on all servers */ bool fsync( string& errmsg ); // --- from DBClientInterface virtual BSONObj findOne(const string &ns, const Query& query, const BSONObj *fieldsToReturn, int queryOptions); virtual auto_ptr<DBClientCursor> query(const string &ns, Query query, int nToReturn, int nToSkip, const BSONObj *fieldsToReturn, int queryOptions, int batchSize ); virtual auto_ptr<DBClientCursor> getMore( const string &ns, long long cursorId, int nToReturn, int options ); virtual void insert( const string &ns, BSONObj obj, int flags=0); virtual void insert( const string &ns, const vector< BSONObj >& v, int flags=0); virtual void remove( const string &ns , Query query, int flags ); virtual void update( const string &ns , Query query , BSONObj obj , int flags ); virtual bool call( Message &toSend, Message &response, bool assertOk , string * actualServer ); virtual void say( Message &toSend, bool isRetry = false , string * actualServer = 0 ); virtual void sayPiggyBack( Message &toSend ); virtual void killCursor( long long cursorID ); virtual string getServerAddress() const { return _address; } virtual bool isFailed() const { return false; } virtual string toString() { return _toString(); } virtual BSONObj getLastErrorDetailed(const std::string& db, bool fsync=false, bool j=false, int w=0, int wtimeout=0); virtual BSONObj getLastErrorDetailed(bool fsync=false, bool j=false, int w=0, int wtimeout=0); virtual bool callRead( Message& toSend , Message& response ); virtual ConnectionString::ConnectionType type() const { return ConnectionString::SYNC; } void setAllSoTimeouts( double socketTimeout ); double getSoTimeout() const { return _socketTimeout; } virtual bool auth(const string &dbname, const string &username, const string &password_text, string& errmsg, bool digestPassword, Auth::Level* level=NULL); virtual void setAuthenticationTable( const AuthenticationTable& auth ); virtual void clearAuthenticationTable(); virtual bool lazySupported() const { return false; } private: SyncClusterConnection( SyncClusterConnection& prev, double socketTimeout = 0 ); string _toString() const; bool _commandOnActive(const string &dbname, const BSONObj& cmd, BSONObj &info, int options=0); auto_ptr<DBClientCursor> _queryOnActive(const string &ns, Query query, int nToReturn, int nToSkip, const BSONObj *fieldsToReturn, int queryOptions, int batchSize ); int _lockType( const string& name ); void _checkLast(); void _connect( const std::string& host ); string _address; vector<string> _connAddresses; vector<DBClientConnection*> _conns; map<string,int> _lockTypes; mongo::mutex _mutex; vector<BSONObj> _lastErrors; double _socketTimeout; }; class UpdateNotTheSame : public UserException { public: UpdateNotTheSame( int code , const string& msg , const vector<string>& addrs , const vector<BSONObj>& lastErrors ) : UserException( code , msg ) , _addrs( addrs ) , _lastErrors( lastErrors ) { verify( _addrs.size() == _lastErrors.size() ); } virtual ~UpdateNotTheSame() throw() { } unsigned size() const { return _addrs.size(); } pair<string,BSONObj> operator[](unsigned i) const { return make_pair( _addrs[i] , _lastErrors[i] ); } private: vector<string> _addrs; vector<BSONObj> _lastErrors; }; };
[ "frankyn@ubuntu.(none)" ]
frankyn@ubuntu.(none)
125743f2ce14578c228ca37f75df57e3b504768b
4b8776cbbd7289e19d1eb841a9469456a0cb826e
/src/qt/guiutil.cpp
935d48806e826770fa43b57e8bc698ce79a12d0e
[ "MIT" ]
permissive
kryptobytes/Xcoin
0923aca4e40d8ee9abbafb066c2eba8cbc8e6315
ac9556084d569a260ce8afe9616c81606c8a545f
refs/heads/master
2021-01-25T10:44:09.766700
2014-04-01T21:32:36
2014-04-01T21:32:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,449
cpp
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include "base58.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { if(uri.scheme() != QString("xcoin")) return false; // check if the address is valid CBitcoinAddress addressFromUri(uri.path().toStdString()); if (!addressFromUri.IsValid()) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert XCoin:// to XCoin: // // Cannot handle this later, because xcoin:// will cause Qt to see the part after // as host, // which will lowercase it (and thus invalidate the address). if(uri.startsWith("xcoin://")) { uri.replace(0, 11, "xcoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "XCoin.lnk"; } bool GetStartOnSystemStartup() { // check for XCoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "xcoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a xcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=XCoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("xcoin-qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " xcoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("xcoin-qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stderr, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
[ "peter@illustrate-archaeology.com" ]
peter@illustrate-archaeology.com
d945d64c8e3f4285b19db24d22ee64b45f85ebb0
d659cbbe56b50cb0079055963497a5d330441fc9
/src/HW7_0.cpp
727e166e4a0e2046e3354b0d473df2fe2087da69
[]
no_license
icnuemono/EE292
2427917e190ae32a6e36f90898d5143199d40574
12d3e6abfaab1c1b3b5e59b85b2209d42b16a7ee
refs/heads/master
2021-01-13T08:47:22.891782
2016-10-26T21:37:01
2016-10-26T21:37:01
71,935,168
0
0
null
null
null
null
UTF-8
C++
false
false
742
cpp
/* HW7_0 Jake Hill hillj7@unlv.nevada.edu Leslie T Rose rosel5@unlv.nevada.edu TEAM 17 Test the serial port */ #include <Arduino.h> #include "selector.h" //if assignment variable is equal to 0, complile this code #if ASSIGNMENT == 0 void Toggle_LED(int pressed); void setup() { Serial.begin(9600); pinMode(13,OUTPUT); } void loop(){ if (Serial.available() > 0){ int pressed; pressed = Serial.read() - 48; Toggle_LED(pressed); } } void Toggle_LED(int pressed) { if (pressed == 1){ digitalWrite(13,HIGH); } } /* void setup() { //call setupSerial variable, defined in selector.cpp setupSerial(); //print sting Hello World; Serial.println("Hello World"); } void loop() { } */ #endif
[ "rosel5@unlv.nevada.edu" ]
rosel5@unlv.nevada.edu
008d4cfc720bc2c2f9e3ce4008ef92bb6e67bee1
cf9343270a166edaa7c7a1cc63fc0b4b10c17f02
/trunk/MicroWXStation/ButtonHandlers.ino
373a9ed8ec79845731e8fd37928a9e148fc87dcc
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
tylerhuntjones/MicroWXStation
74c9b3f72719c4fd7ea79b1332256bee0e313f98
81f70665614f8f1dbc09d4da18275553d8e014a8
refs/heads/master
2021-01-24T06:04:47.322135
2015-05-31T14:54:22
2015-05-31T14:54:22
7,173,656
0
0
null
null
null
null
UTF-8
C++
false
false
2,150
ino
/* * * MicroWXStation for Arduino Mega 2560 r3 - Version 0.3.0 * Copyright (C) 2014, Tyler H. Jones (me@tylerjones.me) * http://tylerjones.me/ * * 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. * * Filename: ButtonHandler.ino * * Description: Sketch file for button input handlings * */ void MenuBtnHandler() { if(CurrentView != MainMenu) { CurrentView = MainMenu; lcd.clear(); showMainMenu(); } } void SelectBtnHandler() { if(CurrentView == MainMenu) { switch(MainMenu_CursorPos) { case 0: CurrentView = CurrentWXData; lcd.clear(); showCurrentWXData(); break; case 1: CurrentView = NonWXData; lcd.clear(); showNonWXData(); break; case 2: CurrentView = MinMaxValues; lcd.clear(); showMinMaxValues(); break; case 3: CurrentView = AboutInfo; lcd.clear(); showAboutInfo(); break; } } if(CurrentView == MinMaxValues) { if(MinMaxToggle == 0) { MinMaxToggle = 1; } else { MinMaxToggle = 0; } } } void UpBtnHandler() { if(CurrentView == MainMenu) { if(MainMenu_CursorPos == 0) { MainMenu_CursorPos = 3; } else { MainMenu_CursorPos--; } } if(CurrentView == MinMaxValues) { if(MinMax_ListShift == 1) MinMax_ListShift--; } } void DownBtnHandler() { if(CurrentView == MainMenu) { if(MainMenu_CursorPos == 3) { MainMenu_CursorPos = 0; } else { MainMenu_CursorPos++; } } if(CurrentView == MinMaxValues) { if(MinMax_ListShift < 1) MinMax_ListShift++; } }
[ "inquirewue@gmail.com" ]
inquirewue@gmail.com
5252ef4340c13693cf47c83f88a99c68d39fa097
ea6aa18a2e9b1b5b9e745991adeee4f86e5096d8
/stl/vector_equal/main.cpp
5554f6ba792db8635b37df460449fe89eb032fc0
[]
no_license
ybdesire/CppPractice
3c67fb333e4d702824c3cd8e0d041987c8edd181
ba13356c1e93e4c6a12a0a41a42cd9afa1b3794c
refs/heads/master
2023-02-08T10:47:17.656051
2023-01-30T09:21:15
2023-01-30T09:21:15
35,354,477
0
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
#include <iostream> #include <vector> using namespace std; int main(int argc, char** argv) { vector<int> v1; vector<int> v2; vector<int> v3; vector<int> v4; v1.push_back(7); v1.push_back(8); v1.push_back(9); v2.push_back(7); v2.push_back(9); v2.push_back(8); v3.push_back(7); v3.push_back(8); v3.push_back(9); v3.push_back(1); v4.push_back(7); v4.push_back(8); v4.push_back(9); if(v1==v2) { cout<<"v1==v2"<<endl; } if(v1==v3) { cout<<"v1==v3"<<endl; } if(v1==v4) { cout<<"v1==v4"<<endl; } return 0; }
[ "ybdesire@gmail.com" ]
ybdesire@gmail.com
8fc27c5c31b1fd1274b06ccb8319eb0dc814da6c
f849befe38a35f08e05985caa412b1338027b58a
/src/lib.h
ba7ae674b00dd2b562ac96287f8e1aef104c54a6
[]
no_license
ilya-otus/join_server
117032c07e3329fca93e39c343a9417e55c51cb5
976e4cfee24b26736cc24bbbe3c772d8fddc6c52
refs/heads/master
2020-06-04T23:01:58.109065
2019-06-16T18:50:34
2019-06-16T18:50:34
192,224,871
0
0
null
null
null
null
UTF-8
C++
false
false
114
h
#pragma once #include <string> std::string version(); int versionMajor(); int versionMinor(); int versionPatch();
[ "podshivalov.ilya@ya.ru" ]
podshivalov.ilya@ya.ru
10278a8e5c7cecde6bd9d50ae70321ce0a735712
7176c5c2d3471bfae3666985b63ee528a88ce884
/src/base58.h
6261f828a7fa23f8c1e44560a4c8a23c41fad50c
[ "MIT" ]
permissive
motocurrency/motocoin
1833753e90150a507ff3e84bb29f8c0b49016f8d
616c12fe26697795b64b1f3d2c4b7c2a5c0421c1
refs/heads/master
2020-03-13T13:46:04.738141
2018-05-13T14:08:06
2018-05-13T14:08:06
131,145,444
0
0
MIT
2018-04-26T11:40:22
2018-04-26T11:25:36
C++
UTF-8
C++
false
false
12,795
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Why base-58 instead of standard base-64 encoding? // - Don't want 0OIl characters that look the same in some fonts and // could be used to create visually identical looking account numbers. // - A string with non-alphanumeric characters is not as easily accepted as an account number. // - E-mail usually won't line-break if there's no punctuation to break at. // - Double-clicking selects the whole number as one word if it's all alphanumeric. // #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H #include <string> #include <vector> #include "bignum.h" #include "key.h" #include "script.h" #include "allocators.h" static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // Encode a byte sequence as a base58-encoded string inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { CAutoBN_CTX pctx; CBigNum bn58 = 58; CBigNum bn0 = 0; // Convert big endian data to little endian // Extra zero at the end make sure bignum will interpret as a positive number std::vector<unsigned char> vchTmp(pend-pbegin+1, 0); reverse_copy(pbegin, pend, vchTmp.begin()); // Convert little endian data to bignum CBigNum bn; bn.setvch(vchTmp); // Convert bignum to std::string std::string str; // Expected size increase from base58 conversion is approximately 137% // use 138% to be safe str.reserve((pend - pbegin) * 138 / 100 + 1); CBigNum dv; CBigNum rem; while (bn > bn0) { if (!BN_div(&dv, &rem, &bn, &bn58, pctx)) throw bignum_error("EncodeBase58 : BN_div failed"); bn = dv; unsigned int c = rem.getulong(); str += pszBase58[c]; } // Leading zeroes encoded as base58 zeros for (const unsigned char* p = pbegin; p < pend && *p == 0; p++) str += pszBase58[0]; // Convert little endian std::string to big endian reverse(str.begin(), str.end()); return str; } // Encode a byte vector as a base58-encoded string inline std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } // Decode a base58-encoded string psz into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet) { CAutoBN_CTX pctx; vchRet.clear(); CBigNum bn58 = 58; CBigNum bn = 0; CBigNum bnChar; while (isspace(*psz)) psz++; // Convert big endian string to bignum for (const char* p = psz; *p; p++) { const char* p1 = strchr(pszBase58, *p); if (p1 == NULL) { while (isspace(*p)) p++; if (*p != '\0') return false; break; } bnChar.setulong(p1 - pszBase58); if (!BN_mul(&bn, &bn, &bn58, pctx)) throw bignum_error("DecodeBase58 : BN_mul failed"); bn += bnChar; } // Get bignum as little endian data std::vector<unsigned char> vchTmp = bn.getvch(); // Trim off sign byte if present if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) vchTmp.erase(vchTmp.end()-1); // Restore leading zeros int nLeadingZeros = 0; for (const char* p = psz; *p == pszBase58[0]; p++) nLeadingZeros++; vchRet.assign(nLeadingZeros + vchTmp.size(), 0); // Convert little endian data to big endian reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size()); return true; } // Decode a base58-encoded string str into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } // Encode a byte vector to a base58-encoded string, including checksum inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet)) return false; if (vchRet.size() < 4) { vchRet.clear(); return false; } uint256 hash = Hash(vchRet.begin(), vchRet.end()-4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size()-4); return true; } // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } inline std::vector<unsigned char> getPubkeyAddressPrefix() { std::vector<unsigned char> Prefix(2); Prefix[0] = fTestNet ? 12 : 11; Prefix[1] = 182; return Prefix; } inline std::vector<unsigned char> getScriptAddressPrefix() { return std::vector<unsigned char>(1, fTestNet ? 196 : 5); } inline std::vector<unsigned char> getSecretPrefix() { std::vector<unsigned char> Prefix = getPubkeyAddressPrefix(); Prefix[0] += 128; return Prefix; } /** Base class for all base58-encoded data */ class CBase58Data { protected: // the version byte(s) std::vector<unsigned char> vchVersion; // the actually encoded data typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar; vector_uchar vchData; CBase58Data() { vchVersion.clear(); vchData.clear(); } void SetData(const std::vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize) { vchVersion = vchVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void SetData(const std::vector<unsigned char> &vchVersionIn, const unsigned char *pbegin, const unsigned char *pend) { SetData(vchVersionIn, (void*)pbegin, pend - pbegin); } public: bool SetString(const char* psz) { std::vector<unsigned char> vchTemp; DecodeBase58Check(psz, vchTemp); if (vchTemp.empty()) { vchData.clear(); vchVersion.clear(); return false; } // hack to determine number of version bytes std::vector<unsigned char> PubkeyPrefix = getPubkeyAddressPrefix(); std::vector<unsigned char> ScriptPrefix = getScriptAddressPrefix(); std::vector<unsigned char> SecretPrefix = getSecretPrefix(); unsigned int nVersionBytes = 1; if (vchTemp[0] == PubkeyPrefix[0]) nVersionBytes = PubkeyPrefix.size(); else if (vchTemp[0] == ScriptPrefix[0]) nVersionBytes = ScriptPrefix.size(); else if (vchTemp[0] == SecretPrefix[0]) nVersionBytes = SecretPrefix.size(); if (vchTemp.size() < nVersionBytes) { vchData.clear(); vchVersion.clear(); return false; } vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes); vchData.resize(vchTemp.size() - nVersionBytes); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size()); OPENSSL_cleanse(&vchTemp[0], vchData.size()); return true; } bool SetString(const std::string& str) { return SetString(str.c_str()); } std::string ToString() const { std::vector<unsigned char> vch = vchVersion; vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CompareTo(const CBase58Data& b58) const { if (vchVersion < b58.vchVersion) return -1; if (vchVersion > b58.vchVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded Bitcoin addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress; class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress *addr; public: CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const; bool operator()(const CScriptID &id) const; bool operator()(const CNoDestination &no) const; }; class CBitcoinAddress : public CBase58Data { public: bool Set(const CKeyID &id) { SetData(getPubkeyAddressPrefix(), &id, 20); return true; } bool Set(const CScriptID &id) { SetData(getScriptAddressPrefix(), &id, 20); return true; } bool Set(const CTxDestination &dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool IsValid() const { bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == getPubkeyAddressPrefix() || vchVersion == getScriptAddressPrefix(); return fCorrectSize && fKnownVersion; } CBitcoinAddress() { } CBitcoinAddress(const CTxDestination &dest) { Set(dest); } CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); } CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == getPubkeyAddressPrefix()) return CKeyID(id); else if (vchVersion == getScriptAddressPrefix()) return CScriptID(id); else return CNoDestination(); } bool GetKeyID(CKeyID &keyID) const { if (!IsValid() || vchVersion != getPubkeyAddressPrefix()) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool IsScript() const { return IsValid() && vchVersion == getScriptAddressPrefix(); } }; bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; } /** A base58-encoded secret key */ class CBitcoinSecret : public CBase58Data { public: void SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(getSecretPrefix(), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey GetKey() { CKey ret; ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1); return ret; } bool IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == getSecretPrefix(); return fExpectedFormat && fCorrectVersion; } bool SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } CBitcoinSecret(const CKey& vchSecret) { SetKey(vchSecret); } CBitcoinSecret() { } }; #endif // BITCOIN_BASE58_H
[ "noname@noname.no" ]
noname@noname.no
ed900bab1dcf31fab6f8f83cede702b39552669a
5ac3c5c61165f0b31ac3183f557b53f0cee7a95d
/Old/IRSENSOR/IRSENSOR.ino
e60aacbd296665796cb885af3575db2926c4ab98
[]
no_license
danavoll/micromouse_2013-2014
c7366cb7c25429c1fc4b19021e0e5e8d74f00a44
08e87a1d73e8e477f2700902368d8e6684407981
refs/heads/master
2020-12-14T09:02:41.150814
2013-10-18T14:20:00
2013-10-18T14:48:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,293
ino
// Simple Proximity Sensor using Infrared // Description: Measure the distance to an obstacle using infrared light emitted by IR LED and // read the value with a IR photodiode. The accuracy is not perfect, but works great // with minor projects. // Author: Ricardo Ouvina // Date: 01/10/2012 // Version: 1.0 #define IR_PIN_LEFT A1 #define IR_PIN_RIGHT A0 #define IREMITTER 3 // Digital Pin 3 for output void setup(){ Serial.begin(9600); // initializing Serial monitor pinMode(IREMITTER,OUTPUT); // IR emitter LED on digital pin 2 digitalWrite(IREMITTER,LOW);// setup IR LED as off } void loop(){ float irL = readIR(true, 15); // true for left float irR = readIR(false, 15); // false for left delay(250); Serial.print("IR - L: "); // Prints the IR values Serial.print(irL); Serial.print(" R: "); Serial.println(irR); } float readIR(boolean leftIR, int times){ ////////////////////////// READ IR ///////////////////////////////////// int value[times];//This was 10 in the original code....? for(int x = 0; x < times; x++){ digitalWrite(IREMITTER,LOW); // turning the IR LEDs off to read the IR coming from the ambient delay(1); // minimum delay necessary to read values float ambientIR; // THE TYPE OF THIS WAS INT, I CHANGED IT TO FLOAT if(leftIR){// If we're reading the left IR ambientIR = analogRead(IR_PIN_LEFT); // storing IR coming from the ambient } else{ ambientIR = analogRead(IR_PIN_RIGHT); } digitalWrite(IREMITTER, HIGH); // turning the IR LEDs on to read the IR coming from the obstacle delay(1); // minimum delay necessary to read values float obstacleIR; // THE TYPE OF THIS WAS INT, I CHANGED IT TO FLOAT if(leftIR){//If we're reading the left IR obstacleIR = analogRead(IR_PIN_LEFT); // storing IR coming from the obstacle } else{ obstacleIR = analogRead(IR_PIN_RIGHT); } value[x] = obstacleIR-ambientIR; // calculating changes in IR values and storing it for future average } float distance; for(int x=0; x < times; x++){ // calculating the average based on the "accuracy" distance += value[x]; } return(float)(distance/times); // return the final value }
[ "jamaters@buffalo.edu" ]
jamaters@buffalo.edu
2088a164f7e0fb2d29222df3243831eb4aecbbf5
39c3bea3237ab2a6628ac15a07beb08a4048df8e
/src/qt/walletmodel.cpp
310f70c5f95318202e35852a966e86c093dcd4e8
[ "MIT" ]
permissive
readyalid/Tellion
37b00a84f7fd2b3cba4ffdf6d5955ca78f497820
3b1e98dd7a798d9a7186fc045e59325f456f981e
refs/heads/master
2020-03-25T07:52:51.474104
2018-05-02T17:18:32
2018-05-02T17:18:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,377
cpp
#include "walletmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" #include "spork.h" #include "smessage.h" #include <QSet> #include <QTimer> #include <QDebug> WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } qint64 WalletModel::getBalance(const CCoinControl *coinControl) const { if (coinControl) { qint64 nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) if(out.fSpendable) nBalance += out.tx->vout[out.i].nValue; return nBalance; } return wallet->GetBalance(); } qint64 WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } qint64 WalletModel::getStake() const { return wallet->GetStake(); } qint64 WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } qint64 WalletModel::getAnonymizedBalance() const { qint64 ret = wallet->GetAnonymizedBalance(); return ret; } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { // Get required locks upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if(!lockMain) return; TRY_LOCK(wallet->cs_wallet, lockWallet); if(!lockWallet) return; if(nBestHeight != cachedNumBlocks) { // Balance and number of transactions might have changed cachedNumBlocks = nBestHeight; checkBalanceChanged(); if(transactionTableModel) transactionTableModel->updateConfirmations(); } } void WalletModel::checkBalanceChanged() { qint64 newBalance = getBalance(); qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); qint64 newAnonymizedBalance = getAnonymizedBalance(); if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance || cachedAnonymizedBalance != newAnonymizedBalance || cachedTxLocks != nCompleteTXLocks) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; cachedAnonymizedBalance = newAnonymizedBalance; cachedTxLocks = nCompleteTXLocks; emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance, newAnonymizedBalance); } } void WalletModel::updateTransaction(const QString &hash, int status) { if(transactionTableModel) transactionTableModel->updateTransaction(hash, status); // Balance and number of transactions might have changed checkBalanceChanged(); } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, status); } bool WalletModel::validateAddress(const QString &address) { std::string sAddr = address.toStdString(); if (sAddr.length() > 75) { if (IsStealthAddress(sAddr)) return true; }; CBitcoinAddress addressParsed(sAddr); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } if(isAnonymizeOnlyUnlocked()) { return AnonymizeOnlyUnlocked; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } qint64 nBalance = getBalance(coinControl); if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } std::map<int, std::string> mapStealthNarr; { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64_t> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { std::string sAddr = rcp.address.toStdString(); if (rcp.typeInd == AddressTableModel::AT_Stealth) { CStealthAddress sxAddr; if (sxAddr.SetEncoded(sAddr)) { ec_secret ephem_secret; ec_secret secretShared; ec_point pkSendTo; ec_point ephem_pubkey; if (GenerateRandomSecret(ephem_secret) != 0) { printf("GenerateRandomSecret failed.\n"); return Aborted; }; if (StealthSecret(ephem_secret, sxAddr.scan_pubkey, sxAddr.spend_pubkey, secretShared, pkSendTo) != 0) { printf("Could not generate receiving public key.\n"); return Aborted; }; CPubKey cpkTo(pkSendTo); if (!cpkTo.IsValid()) { printf("Invalid public key generated.\n"); return Aborted; }; CKeyID ckidTo = cpkTo.GetID(); CBitcoinAddress addrTo(ckidTo); if (SecretToPublicKey(ephem_secret, ephem_pubkey) != 0) { printf("Could not generate ephem public key.\n"); return Aborted; }; if (fDebug) { printf("Stealth send to generated pubkey %"PRIszu": %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str()); printf("hash %s\n", addrTo.ToString().c_str()); printf("ephem_pubkey %"PRIszu": %s\n", ephem_pubkey.size(), HexStr(ephem_pubkey).c_str()); }; CScript scriptPubKey; scriptPubKey.SetDestination(addrTo.Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); CScript scriptP = CScript() << OP_RETURN << ephem_pubkey; if (rcp.narration.length() > 0) { std::string sNarr = rcp.narration.toStdString(); if (sNarr.length() > 24) { printf("Narration is too long.\n"); return NarrationTooLong; }; std::vector<unsigned char> vchNarr; SecMsgCrypter crypter; crypter.SetKey(&secretShared.e[0], &ephem_pubkey[0]); if (!crypter.Encrypt((uint8_t*)&sNarr[0], sNarr.length(), vchNarr)) { printf("Narration encryption failed.\n"); return Aborted; }; if (vchNarr.size() > 48) { printf("Encrypted narration is too long.\n"); return Aborted; }; if (vchNarr.size() > 0) scriptP = scriptP << OP_RETURN << vchNarr; int pos = vecSend.size()-1; mapStealthNarr[pos] = sNarr; }; vecSend.push_back(make_pair(scriptP, 1)); continue; } else { printf("Couldn't parse stealth address!\n"); return Aborted; } // else drop through to normal } CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(sAddr).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); if (rcp.narration.length() > 0) { std::string sNarr = rcp.narration.toStdString(); if (sNarr.length() > 24) { printf("Narration is too long.\n"); return NarrationTooLong; }; std::vector<uint8_t> vNarr(sNarr.c_str(), sNarr.c_str() + sNarr.length()); std::vector<uint8_t> vNDesc; vNDesc.resize(2); vNDesc[0] = 'n'; vNDesc[1] = 'p'; CScript scriptN = CScript() << OP_RETURN << vNDesc << OP_RETURN << vNarr; vecSend.push_back(make_pair(scriptN, 1)); } } CWalletTx wtx; CReserveKey keyChange(wallet); int64_t nFeeRequired = 0; int nChangePos = -1; std::string strFailReason; /*if(recipients[0].useInstantX && total > GetSporkValue(SPORK_2_MAX_VALUE)*COIN){ emit message(tr("Send Coins"), tr("InstantX doesn't support sending values that high yet. Transactions are currently limited to %n TLL.", "", GetSporkValue(SPORK_2_MAX_VALUE)),true, CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; }*/ bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePos, strFailReason, coinControl); std::map<int, std::string>::iterator it; for (it = mapStealthNarr.begin(); it != mapStealthNarr.end(); ++it) { int pos = it->first; if (nChangePos > -1 && it->first >= nChangePos) pos++; char key[64]; if (snprintf(key, sizeof(key), "n_%u", pos) < 1) { printf("CreateStealthTransaction(): Error creating narration key."); continue; }; wtx.mapValue[key] = it->second; }; if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); if (rcp.typeInd == AddressTableModel::AT_Stealth) { wallet->UpdateStealthAddress(strAddress, strLabel, true); } else { std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); }; }; } } return SendCoinsReturn(OK, 0, hex); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!wallet->IsCrypted()) { return Unencrypted; } else if(wallet->IsLocked()) { return Locked; } else if(fWalletUnlockStakingOnly) { return Locked; } else if (wallet->fWalletUnlockAnonymizeOnly) { return UnlockedForAnonymizationOnly; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if(encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase, bool anonymizeOnly) { if(locked) { // Lock return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase, anonymizeOnly); } } bool WalletModel::isAnonymizeOnlyUnlocked() { return wallet->fWalletUnlockAnonymizeOnly; } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) { qDebug() << "NotifyKeyStoreStatusChanged"; QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { if (address.type() == typeid(CStealthAddress)) { CStealthAddress sxAddr = boost::get<CStealthAddress>(address); std::string enc = sxAddr.Encoded(); LogPrintf("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", enc.c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(enc)), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } else { LogPrintf("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, strHash), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if ((!was_locked) && fWalletUnlockStakingOnly && isAnonymizeOnlyUnlocked()) { setWalletLocked(true); was_locked = getEncryptionStatus() == Locked; } if(was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked && !fWalletUnlockStakingOnly); } WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock): wallet(wallet), valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Tellion context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { LOCK2(cs_main, wallet->cs_wallet); BOOST_FOREACH(const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); vOutputs.push_back(out); } } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { LOCK2(cs_main, wallet->cs_wallet); // ListLockedCoins, mapWallet std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); std::vector<COutPoint> vLockedCoins; // add locked coins BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); vCoins.push_back(out); } BOOST_FOREACH(const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true); } CTxDestination address; if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { LOCK2(cs_main, wallet->cs_wallet); return wallet->IsLockedCoin(hash, n); } void WalletModel::lockCoin(COutPoint& output) { LOCK2(cs_main, wallet->cs_wallet); wallet->LockCoin(output); } void WalletModel::unlockCoin(COutPoint& output) { LOCK2(cs_main, wallet->cs_wallet); wallet->UnlockCoin(output); } void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts) { LOCK2(cs_main, wallet->cs_wallet); wallet->ListLockedCoins(vOutpts); }
[ "38584095+TellionTLL@users.noreply.github.com" ]
38584095+TellionTLL@users.noreply.github.com
21c5b8491aaddae87a1b21f866f6eefd463131f1
e11ac9338021787861bd5b6c721a04c00ff4228a
/Final Project/Final Project/ERSimulator/ERSimulator/Hospital.h
7831584856d1e740ce9c67973f11e2db971db029
[]
no_license
iblack20/DataStructuresFinalProject
4993afccbe2c35625403ca85c1e45de8e263bf77
2eebc9a9efd96242def27cb6f94450dc2689c90b
refs/heads/master
2020-04-09T11:10:18.908316
2018-12-09T06:07:16
2018-12-09T06:07:16
160,298,271
0
1
null
2018-12-09T06:07:17
2018-12-04T04:44:38
C++
UTF-8
C++
false
false
611
h
////////////////////////////// // Defines Hospital class ////////////////////////////// #include "Resident.h" #include "WaitingRoomQueue.h" #include "DoctorQueue.h" #include "NurseQueue.h" #include <iterator> #include <set> #include <vector> #include <queue> class Hospital { private: std::vector <TreatmentQueue *> h_queues; int DoctorsWorking; int NursesWorking; public: Hospital() { DoctorsWorking = 0; NursesWorking = 0; } Hospital(int Doctors, int Nurses) { DoctorsWorking = Doctors; NursesWorking = Nurses; } void Simulate(); void Report(); };
[ "noreply@github.com" ]
noreply@github.com
593fac1c900b4d7a63aac4045e57665baf7b5df9
7edba864c3503a5e6226cd72a753aed37f4c18c6
/1.Class_Code/2.Class_Test2/S.cpp
c8f983499e74196f58d7ed843173695c5d385a0f
[]
no_license
Zip000000/CPractice
49bd6255e64ba4a1e9c981afb8964c68f0220da0
f594a6cfd45cf2214221efeda22d9f241fa41da3
refs/heads/master
2020-05-09T13:48:13.825411
2019-08-29T10:37:29
2019-08-29T10:37:29
181,167,950
0
0
null
null
null
null
UTF-8
C++
false
false
741
cpp
/************************************************************************* > File Name: 0.test.cpp > Author: Zip > Mail: 307110017@qq.com > Created Time: 2019年07月19日 星期五 19时50分05秒 ************************************************************************/ #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<vector> #include<map> #include<cmath> using namespace std; int main() { long long a; cin >> a; long long min = 2147483647, max = -2147483647; for(int i = 0; i < a; i++) { long long tmp; cin >> tmp; if(max < tmp) max = tmp; if(min > tmp) min = tmp; } printf("%lld\n", max - min); return 0; }
[ "307110017@qq.com" ]
307110017@qq.com
47d02482345dad031dc1819da7ff042f353fbcf3
47a0d457c251d58b436c7af498261ba99eb4657d
/VectorworksSDK/SDK2021/WindowsSDK/SDKLib/Source/VWSDK/VWFC/VWObjects/VWMeshObj.cpp
dbd8cd7f76e120f7c6c7c8a7fa6526f666e3627a
[]
no_license
jacob-ditkoff/VW_2021SDK_Example
591cbc1e5e38dddda69420be6bc0ab6f322b5cf1
a429f3c402716f1fc4a067e0aacf08a67c5285c5
refs/heads/main
2023-03-21T18:04:22.305924
2021-03-04T14:48:50
2021-03-04T14:48:50
339,420,316
0
0
null
null
null
null
UTF-8
C++
false
false
15,793
cpp
// // Copyright Nemetschek Vectorworks, Inc. // Use of this file is governed by the Nemetschek Vectorworks SDK License Agreement // http://developer.vectorworks.net/index.php?title=Vectorworks_SDK_License // #include "StdHeaders.h" #include "VectorworksSDK.h" using namespace VWFC::Math; using namespace VWFC::VWObjects; // -------------------------------------------------------------------------- VWMeshObj::VWMeshObj() { fhObject = gSDK->CreateMesh( & fMeshData ); VWFC_ASSERT( fhObject ); if ( fhObject == NULL ) THROW_VWFC_EXCEPTION( VWCannotCreateObjectException, 0, "cannot create mesh" ); } VWMeshObj::VWMeshObj(MCObjectHandle hMesh) { VWFC_ASSERT( VWMeshObj::IsMeshObject( hMesh ) ); if ( ! VWMeshObj::IsMeshObject( hMesh ) ) THROW_VWFC_EXCEPTION( VWBadObjectTypeException, 0, "bad handle type when creating" ); fhObject = hMesh; VWFC_ASSERT( fhObject != nil ); gSDK->GetMesh( fhObject, & fMeshData ); } VWMeshObj::VWMeshObj(const VWMeshObj& src) { fhObject = src.fhObject; } VWMeshObj::~VWMeshObj() { fhObject = nil; } VWMeshObj& VWMeshObj::operator=(const VWMeshObj& src) { fhObject = src.fhObject; return *this; } /*static*/ bool VWMeshObj::IsMeshObject(MCObjectHandle hObj) { short type = gSDK->GetObjectTypeN( hObj ); return type == kMeshNode; } VectorWorks::IMeshDataPtr VWMeshObj::GetMesh() { return fMeshData; } // -------------------------------------------------------------------------- VWMeshCreator::SFaceDef::SFaceDef() { fHasColor = false; fPartIndex = kTexturePart_Overall; } // -------------------------------------------------------------------------- VWMeshCreator::SPartDef::SPartDef() { fTextureRef = 0L; } // -------------------------------------------------------------------------- VWMeshCreator::VWMeshCreator() : fIsImported( false ) { fMeshSmoothing = MeshSmoothing::EMeshSmoothing::eUseDocumentPreference; fMeshCreaseAngle = 50.0; // Add primary, secondary, tertiary , and overall parts to part array so that first added mesh part is actually overall + 1. // Overall is used for untextured faces. -DLD 3/11/2014 SPartDef partDef; partDef.fTextureRef = 0L; farrParts.push_back(partDef); farrParts.push_back(partDef); farrParts.push_back(partDef); farrParts.push_back(partDef); fmapInternalIndex2PartDef.insert( TInternalIndex2PartDef::value_type( 0L, kTexturePart_Overall ) ); } VWMeshCreator::~VWMeshCreator() { } size_t VWMeshCreator::AddPart(InternalIndex textureRef) { size_t newPartIndex = kTexturePart_Overall; ASSERTN(kDaveD, farrParts.size() >= 4L); SPartDef partDef; partDef.fTextureRef = textureRef; farrParts.push_back( partDef ); newPartIndex = farrParts.size() - 1; fmapInternalIndex2PartDef.insert( TInternalIndex2PartDef::value_type( textureRef, newPartIndex ) ); ASSERTN(kDaveD, newPartIndex >= kTexturePart_Overall); return newPartIndex; } size_t VWMeshCreator::AddPartUnique(InternalIndex textureRef) { size_t newPartIndex = kTexturePart_Overall; if (textureRef > 0L) { TInternalIndex2PartDef::const_iterator it = fmapInternalIndex2PartDef.find( textureRef ); if ( it != fmapInternalIndex2PartDef.end() ) { newPartIndex = it->second; } else { newPartIndex = this->AddPart( textureRef ); } } return newPartIndex; } size_t VWMeshCreator::AddVertex(const WorldPt3& position, const WorldPt& uvCoord, const WorldPt3& normal) { SVertexDef vertex; vertex.fPosition = position; vertex.fUVCoord = uvCoord; vertex.fNormal = normal; // VWMeshCreator is generating duplicate vertices which which is unnecessary // So a modules like OBJImport which usually don't have duplicate vertices will // add them using AddVertes multiple times because they iterate over faces not the vertices.- FatemehA 3/2017 // setting this to false right now static bool avoidDuplicateVertices = false; if (avoidDuplicateVertices){ auto it = fVertexMap.find(vertex); if( it == fVertexMap.end() ) { it = fVertexMap.insert(std::make_pair(vertex, farrVertices.size())).first; farrVertices.push_back( vertex ); } return it->second; } else{ farrVertices.push_back( vertex ); return farrVertices.size() - 1; } } void VWMeshCreator::AddFace(size_t vertex1, size_t vertex2, size_t vertex3, size_t partIndex) { SFaceDef faceDef; faceDef.farrVertices.Append( vertex1 ); faceDef.farrVertices.Append( vertex2 ); faceDef.farrVertices.Append( vertex3 ); faceDef.fPartIndex = partIndex; farrFaces.push_back( faceDef ); ASSERTN(kDaveD, partIndex >= kTexturePart_Overall); } void VWMeshCreator::AddFace(size_t vertex1, size_t vertex2, size_t vertex3, size_t partIndex, const ObjectColorType& color) { SFaceDef faceDef; faceDef.farrVertices.Append( vertex1 ); faceDef.farrVertices.Append( vertex2 ); faceDef.farrVertices.Append( vertex3 ); faceDef.fPartIndex = partIndex; faceDef.fHasColor = true; faceDef.fColor = color; farrFaces.push_back( faceDef ); ASSERTN(kDaveD, partIndex >= kTexturePart_Overall); } void VWMeshCreator::AddFace_Begin() { fCurrentFaceWhenAdding = SFaceDef(); } void VWMeshCreator::AddFace_Add(size_t vertex) { fCurrentFaceWhenAdding.farrVertices.Append( vertex ); } void VWMeshCreator::AddFace_SetColor(const ObjectColorType& color) { fCurrentFaceWhenAdding.fHasColor = true; fCurrentFaceWhenAdding.fColor = color; } void VWMeshCreator::AddFace_End() { farrFaces.push_back( fCurrentFaceWhenAdding ); fCurrentFaceWhenAdding = SFaceDef(); } void VWMeshCreator::AddFace_End(size_t partIndex) { fCurrentFaceWhenAdding.fPartIndex = partIndex; farrFaces.push_back( fCurrentFaceWhenAdding ); fCurrentFaceWhenAdding = SFaceDef(); } void VWMeshCreator::SetIsImported(bool isImported) { fIsImported = isImported; } void VWMeshCreator::GenerateSmoothNormals() { // not implemented } void VWMeshCreator::GenerateMeshes(bool useUndo/*=true*/) { if( farrFaces.size() > 0 ) { VectorWorks::IMeshDataPtr meshData; MCObjectHandle hMesh = gSDK->CreateMesh( & meshData ); if ( useUndo ) { gSDK->AddAfterSwapObject( hMesh ); } bool bSingleMesh = true; bool bLastMeshPart = false; //Charlene: question here //const size_t maxVerticesLimit = 30000; const size_t maxVerticesLimit = 0x000FFFFF; size_t maxVertices = maxVerticesLimit - 1000;//for splitting meshes limit = maxVerticesLimit - maxFaceLimit bSingleMesh = farrVertices.size() < maxVerticesLimit; // Don't set vertex UVs if they are all 0,0 (default parameter value), and don't set // vertex normals if the data is bad or nonsensical. -DLD 2/28/2014 bool badNormals = false; bool allUVsDefault = true; for (size_t iVertex = 0, n = farrVertices.size(); iVertex < n; ++iVertex ) { const SVertexDef& vertex = farrVertices[ iVertex ]; if (!DoublesAreNearlyEqual(vertex.fUVCoord.x, 0.0, kNearlyEqualEpsilonForNormalizedValues) || !DoublesAreNearlyEqual(vertex.fUVCoord.y, 0.0, kNearlyEqualEpsilonForNormalizedValues)) { allUVsDefault = false; } // If vertex normal is not normalized then don't use them, this can happen with all zeroes or default // WorldCoord of 1E+100 or just bad file data. -DLD 3/18/2014 if (!DoublesAreNearlyEqual(vertex.fNormal.Magnitude(), 1.0, kNearlyEqualEpsilonForNormalizedValues)) badNormals = true; } // set mesh smoothing eUseDocumentPreference is by default if ( !badNormals && fIsImported == true ) meshData->SetMeshSmoothing( VectorWorks::MeshSmoothing::eImported ); if ( fMeshSmoothing == VectorWorks::MeshSmoothing::eCustomCrease ) { meshData->SetMeshSmoothing( fMeshSmoothing ); meshData->SetCreaseAngle( fMeshCreaseAngle ); } else if ( fMeshSmoothing == VectorWorks::MeshSmoothing::eUseDocumentPreference ) { meshData->SetMeshSmoothing( VectorWorks::MeshSmoothing::eUseDocumentPreference); } else if ( fMeshSmoothing == VectorWorks::MeshSmoothing::eNone ) { meshData->SetMeshSmoothing( VectorWorks::MeshSmoothing::eNone ); } meshData->ClearVertex(); meshData->ClearVertexNormalsAndUVCoords(); typedef std::map<size_t, size_t> TInternalPartIndex2MeshPartIndex; TInternalPartIndex2MeshPartIndex mapInternalPartIndex2MeshPartIndex; for(size_t iPart=0, n=farrParts.size(); iPart < n; ++iPart) { const SPartDef& part = farrParts[ iPart ]; size_t meshPartIndex = meshData->AddPart( part.fTextureRef ); mapInternalPartIndex2MeshPartIndex.insert( TInternalPartIndex2MeshPartIndex::value_type( iPart, meshPartIndex ) ); } size_t nFaces = farrFaces.size(); size_t nFaceBreak = 0; typedef std::map<size_t, size_t> TInternalVertexIDPart2MeshOriginalIndex; // old index , new index in the split mesh TInternalVertexIDPart2MeshOriginalIndex mapInternalSplitMeshVertex; for(size_t iFace=0; iFace < nFaces; ++iFace ) { SFaceDef& face = farrFaces[ iFace ]; size_t nVertexCountFace = face.farrVertices.GetSize(); // add Vertices from faces for( size_t iVertex = 0; iVertex < nVertexCountFace; ++iVertex ) { size_t nCurrentFaceVertexIndex = face.farrVertices.GetAt( iVertex ); const SVertexDef& vertex = farrVertices[ nCurrentFaceVertexIndex ]; auto itIndex = mapInternalSplitMeshVertex.find( nCurrentFaceVertexIndex ); if ( itIndex == mapInternalSplitMeshVertex.end() ) { size_t mapSize = mapInternalSplitMeshVertex.size(); mapInternalSplitMeshVertex.insert( TInternalVertexIDPart2MeshOriginalIndex::value_type( nCurrentFaceVertexIndex, mapSize ) ); face.farrVertices.SetAt( iVertex, mapSize ); } else { face.farrVertices.SetAt( iVertex, itIndex->second ); } itIndex = mapInternalSplitMeshVertex.find( nCurrentFaceVertexIndex ); meshData->SetVertexPosition( itIndex->second, vertex.fPosition ); if (!allUVsDefault) meshData->SetVertexUVCoord( itIndex->second, vertex.fUVCoord ); if (!badNormals) meshData->SetVertexNormal( itIndex->second, vertex.fNormal ); } // Add Faces MCObjectHandle hMeshFace = gSDK->AddMeshFace( hMesh, face.farrVertices ); if ( hMeshFace && face.fHasColor ) { gSDK->SetColor( hMeshFace, face.fColor ); } TInternalPartIndex2MeshPartIndex::const_iterator it = mapInternalPartIndex2MeshPartIndex.find( face.fPartIndex ); if ( it != mapInternalPartIndex2MeshPartIndex.end() ) { size_t meshPartIndex = it->second; meshData->SetFacePart( iFace - nFaceBreak, meshPartIndex ); } else { meshData->SetFacePart( iFace - nFaceBreak, kTexturePart_Overall ); } // split the mesh if neccessary bool bNextFaceSplit = ( mapInternalSplitMeshVertex.size() > maxVertices ); bLastMeshPart = ( iFace + 1 == nFaces ); if( !bSingleMesh && bNextFaceSplit && !bLastMeshPart ) { if ( meshData->Save() ) { farrGeneratedMeshes.push_back( hMesh ); meshData->ClearFaces(); meshData->ClearVertex(); meshData->ClearVertexNormalsAndUVCoords(); meshData->ClearParts(); mapInternalSplitMeshVertex.clear(); hMesh = NULL; hMesh = gSDK->CreateMesh( & meshData ); if ( hMesh && useUndo ) { gSDK->AddAfterSwapObject( hMesh ); } if ( !badNormals && fIsImported == true ) { meshData->SetMeshSmoothing( VectorWorks::MeshSmoothing::eImported ); } if ( fMeshSmoothing == VectorWorks::MeshSmoothing::eCustomCrease ) { meshData->SetMeshSmoothing( fMeshSmoothing ); meshData->SetCreaseAngle( fMeshCreaseAngle ); } else if ( fMeshSmoothing == VectorWorks::MeshSmoothing::eUseDocumentPreference ) { meshData->SetMeshSmoothing( VectorWorks::MeshSmoothing::eUseDocumentPreference ); } else if ( fMeshSmoothing == VectorWorks::MeshSmoothing::eNone ) { meshData->SetMeshSmoothing( VectorWorks::MeshSmoothing::eNone ); } mapInternalPartIndex2MeshPartIndex.clear(); for(size_t iPart=0, n=farrParts.size(); iPart < n; ++iPart) { const SPartDef& part = farrParts[ iPart ]; size_t meshPartIndex = meshData->AddPart( part.fTextureRef ); mapInternalPartIndex2MeshPartIndex.insert( TInternalPartIndex2MeshPartIndex::value_type( iPart, meshPartIndex ) ); } nFaceBreak = iFace + 1; } else if ( hMesh ) { if( useUndo ) { gSDK->AddBeforeSwapObject( hMesh ); } gSDK->DeleteObject( hMesh, useUndo ); } } } if( bSingleMesh || bLastMeshPart ) { //all vertices are saved if it is Single mesh if ( meshData->Save() ) { farrGeneratedMeshes.push_back( hMesh ); meshData->ClearFaces(); meshData->ClearVertex(); meshData->ClearVertexNormalsAndUVCoords(); meshData->ClearParts(); } else if ( hMesh ) { if ( useUndo ) { gSDK->AddBeforeSwapObject( hMesh ); } gSDK->DeleteObject( hMesh, useUndo ); } } } } const TMCObjectHandlesSTLArray& VWMeshCreator::GetGeneratedMeshes() const { return farrGeneratedMeshes; } size_t VWMeshCreator::GetVerticesCount() const { return farrVertices.size(); } const WorldPt3& VWMeshCreator::GetVertexPosition(size_t index) const { return farrVertices[index].fPosition; } void VWMeshCreator::SetVertexPositionZ(size_t index, double z) { farrVertices[index].fPosition.z = z; } void VWMeshCreator::SetVertexNormal( size_t index, const WorldPt3& normal ) { farrVertices[index].fNormal = normal; } void VWMeshCreator::SetVertexUVCoord( size_t index, const WorldPt& ptUV ) { farrVertices[index].fUVCoord = ptUV; } const WorldPt& VWMeshCreator::GetVertexUVCoord(size_t index) const { return farrVertices[index].fUVCoord; } const WorldPt3& VWMeshCreator::GetVertexNormal(size_t index) const { return farrVertices[index].fNormal; } size_t VWMeshCreator::GetPartsCount() const { return farrParts.size(); } const InternalIndex& VWMeshCreator::GetPartTextureRef( size_t index) const { return farrParts[index].fTextureRef; } size_t VWMeshCreator::GetFacesCount() const { return farrFaces.size(); } const bool& VWMeshCreator::IsFaceHaveColor(size_t index) const { return farrFaces[index].fHasColor; } const ObjectColorType& VWMeshCreator::GetFaceColor(size_t index) const { return farrFaces[index].fColor; } const size_t& VWMeshCreator::GetFacePartIndex(size_t index) const { return farrFaces[index].fPartIndex; } size_t VWMeshCreator::GetFaceVertexCount(size_t index) const { return farrFaces[index].farrVertices.GetSize(); } const size_t& VWMeshCreator::GetFaceVertexIndexAt(size_t faceIndex, size_t vertexIndexAt) const { return farrFaces[faceIndex].farrVertices.GetAt( vertexIndexAt ); } void VWMeshCreator::SetMeshSmoothing( short meshSmoothingType, double creaseAngle ) { switch( meshSmoothingType ) { case 0: fMeshSmoothing = MeshSmoothing::EMeshSmoothing::eNone; break; case 1: fMeshSmoothing = MeshSmoothing::EMeshSmoothing::eUseDocumentPreference; break; case 2: fMeshSmoothing = MeshSmoothing::EMeshSmoothing::eCustomCrease; fMeshCreaseAngle = creaseAngle; break; case 3: fMeshSmoothing = MeshSmoothing::EMeshSmoothing::eImported; break; default: fMeshSmoothing = MeshSmoothing::EMeshSmoothing::eUseDocumentPreference; break; } }
[ "78505922+jacob-ditkoff@users.noreply.github.com" ]
78505922+jacob-ditkoff@users.noreply.github.com
0225ca404b40ee9bff55b901886d0249549760b4
6fe0923f7dc68dcbfc565daaa48b63a5febfdcc1
/Fusion/src/sensors/mesh_types.cpp
9482013de769fe81b758953914e676b83fa4a86a
[]
no_license
alexeyden/Robot-Stuff
bce37764faee7e026fed0251e6d8669b5acd8224
368c49687a4ad07d8c0474f0af6ec8477c6bd146
refs/heads/master
2021-01-17T06:50:00.084975
2017-06-16T06:07:26
2017-06-16T06:07:26
50,364,409
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
#include "pch.h" //force instantiation to cut down build times template class pcl::PointCloud<pcl::PointNormal>; template class pcl::search::KdTree<pcl::PointNormal>; template class pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal>; template class pcl::GreedyProjectionTriangulation<pcl::PointNormal>; template class pcl::MarchingCubesHoppe<pcl::PointNormal>;
[ "rtgbnm@gmail.com" ]
rtgbnm@gmail.com
7554c3c3391e2567b0e8c0ce7ace86e1bb9ceef6
54642bb4178d2c0d45fdbf017511cd6a9f52ed01
/GameTemplate_4/YTEngine/graphics/SkinModel.cpp
6a1aafc668390cf3aebd168ff12887417403ac21
[]
no_license
RiderRogue/Game-Proto
8367509617ccaf8e1881abcffd383ec99b2deb8b
c38c6ef091de48c89f2c6a3d29fa9df26d484c61
refs/heads/master
2020-04-22T14:24:16.924213
2019-07-10T06:04:36
2019-07-10T06:04:36
170,442,281
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
13,456
cpp
#include "stdafx.h" #include "SkinModel.h" #include "SkinModelDataManager.h" #include "graphics/SkinModelEffect.h" namespace YTEngine { class ModelEffect; SkinModel::~SkinModel() { //定数バッファを解放。 if (m_cb != nullptr) { m_cb->Release(); } //ライト用の定数バッファの解放。 if (m_lightCb != nullptr) { m_lightCb->Release(); } if (m_samplerState != nullptr) { //サンプラステートを解放。 m_samplerState->Release(); } } void SkinModel::Init(const wchar_t* filePath, EnFbxUpAxis enFbxUpAxis)//インスタンシングする場合はここに引数 { //スケルトンのデータを読み込む。 InitSkeleton(filePath); //定数バッファの作成。 InitConstantBuffer(); //サンプラステートの初期化。 InitSamplerState(); InitDirectionLight(); //SkinModelDataManagerを使用してCMOファイルのロード。 m_modelDx = g_skinModelDataManager.Load(filePath, m_skeleton); //m_enFbxUpAxis = enFbxUpAxis; } void SkinModel::InitSkeleton(const wchar_t* filePath) { //スケルトンのデータを読み込む。 //cmoファイルの拡張子をtksに変更する。 std::wstring skeletonFilePath = filePath; //文字列から.cmoファイル始まる場所を検索。 int pos = (int)skeletonFilePath.find(L".cmo"); //.cmoファイルを.tksに置き換える。 skeletonFilePath.replace(pos, 4, L".tks"); //tksファイルをロードする。 bool result = m_skeleton.Load(skeletonFilePath.c_str()); if (result == false) { //スケルトンが読み込みに失敗した。 //アニメーションしないモデルは、スケルトンが不要なので //読み込みに失敗することはあるので、ログ出力だけにしておく。 #ifdef _DEBUG char message[256]; sprintf(message, "tksファイルの読み込みに失敗しました。%ls\n", skeletonFilePath.c_str()); OutputDebugStringA(message); #endif } } //定数バッファの初期化。 void SkinModel::InitConstantBuffer() { //作成するバッファのサイズをsizeof演算子で求める。 int bufferSize = sizeof(SVSConstantBuffer); //どんなバッファを作成するのかをせてbufferDescに設定する。 D3D11_BUFFER_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(bufferDesc)); //0でクリア。 bufferDesc.Usage = D3D11_USAGE_DEFAULT; //バッファで想定されている、読み込みおよび書き込み方法。 bufferDesc.ByteWidth = (((bufferSize - 1) / 16) + 1) * 16; //バッファは16バイトアライメントになっている必要がある。 //アライメントって→バッファのサイズが16の倍数ということです。 bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; //バッファをどのようなパイプラインにバインドするかを指定する。 //定数バッファにバインドするので、D3D11_BIND_CONSTANT_BUFFERを指定する。 bufferDesc.CPUAccessFlags = 0; //CPU アクセスのフラグです。 //CPUアクセスが不要な場合は0。 //定数バッファをVRAM上に作成。 g_graphicsEngine->GetD3DDevice()->CreateBuffer(&bufferDesc, NULL, &m_cb); //続いて、ライト用の定数バッファを作成。 //作成するバッファのサイズを変更するだけ。 bufferDesc.ByteWidth = (((sizeof(SLight) - 1) / 16) + 1) * 16;//Raundup16(sizeof(SLight)); //SDirectionLightは16byteの倍数になっているので、切り上げはやらない。 g_graphicsEngine->GetD3DDevice()->CreateBuffer(&bufferDesc, NULL, &m_lightCb); } //ディレクションライトの初期化。 void SkinModel::InitDirectionLight() { float right = 0.7f; m_light.directionLight.direction[0] = { 1.0f, 0.0f, 0.0f, 0.0f }; m_light.directionLight.color[0] = { right, right, right, 1.0f }; m_light.directionLight.direction[1] = { -1.0f, 0.0f, 0.0f, 0.0f }; m_light.directionLight.color[1] = { right, right, right, 1.0f }; m_light.directionLight.direction[2] = { 0.0f, 0.0f, 1.0f, 0.0f }; m_light.directionLight.color[2] = { right, right, right, 1.0f }; //地面の色に反映される。 m_light.directionLight.direction[3] = { 0.0f, 0.0f, -1.0f, 0.0f }; m_light.directionLight.color[3] = { right, right, right, 1.0f }; m_light.specPow = 100.0f; } void SkinModel::SetDirectionLight(float x, float y, float z) { m_light.directionLight.color[0] = { x, y, z, 1.0f }; m_light.directionLight.color[1] = { x, y, z, 1.0f }; m_light.directionLight.color[2] = { x, y, z, 1.0f }; m_light.directionLight.color[3] = { x, y, z, 1.0f }; } void SkinModel::SetDirectionDamage(){ m_light.directionLight.color[0].x *= 6.0f; m_light.directionLight.color[1].x *= 6.0f; m_light.directionLight.color[2].x *= 6.0f; m_light.directionLight.color[3].x *= 6.0f; } void SkinModel::ReturnDirectionDamage() { m_light.directionLight.color[0].x /= 6.0f; m_light.directionLight.color[1].x /= 6.0f; m_light.directionLight.color[2].x /= 6.0f; m_light.directionLight.color[3].x /= 6.0f; } void SkinModel::DirectionLight_Red01(float a) { for (int i = 0; i < 4; i++) { if (m_light.directionLight.color[i].x < a) { m_light.directionLight.color[i].x += 0.4f; } else { m_light.directionLight.color[i].x = a; } if (m_light.directionLight.color[i].y > 0.6f) { m_light.directionLight.color[i].y -= 0.1f; } else { m_light.directionLight.color[i].y = 0.6f; } if (m_light.directionLight.color[i].z > 0.6f) { m_light.directionLight.color[i].z -= 0.1f; } else { m_light.directionLight.color[i].z = 0.6f; } } } void SkinModel::DirectionLight_ReturnRed(float a) { for (int i = 0; i < 4; i++) { if (m_light.directionLight.color[i].x > 1.0f) { m_light.directionLight.color[i].x -= a/10; } else { m_light.directionLight.color[i].x = 1.0f; } if (m_light.directionLight.color[i].y < 1.0f) { m_light.directionLight.color[i].y += a/30; } else { m_light.directionLight.color[i].y = 1.0f; } if (m_light.directionLight.color[i].z < 1.0f) { m_light.directionLight.color[i].z += a/30; } else { m_light.directionLight.color[i].z = 1.0f; } } } void SkinModel::InitSamplerState() { //テクスチャのサンプリング方法を指定するためのサンプラステートを作成。 D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; //テクスチャフィルタはバイリニアフィルタ //サンプラステートを作成。 g_graphicsEngine->GetD3DDevice()->CreateSamplerState(&desc, &m_samplerState); //インスタンシング } void SkinModel::UpdateWorldMatrix(CVector3 position, CQuaternion rotation, CVector3 scale, EnFbxUpAxis enUpdateAxis) { //3dsMaxと軸を合わせるためのバイアス。 CMatrix mBias = CMatrix::Identity(); if (enUpdateAxis == enFbxUpAxisZ) { //Z-up mBias.MakeRotationX(CMath::PI * -0.5f); } CMatrix transMatrix, rotMatrix, scaleMatrix; //平行移動行列を作成する。 transMatrix.MakeTranslation(position); //回転行列を作成する。 rotMatrix.MakeRotationFromQuaternion(rotation); rotMatrix.Mul(mBias, rotMatrix); //拡大行列を作成する。 scaleMatrix.MakeScaling(scale); //ワールド行列を作成する。 //拡大×回転×平行移動の順番で乗算するように! //順番を間違えたら結果が変わるよ。 m_worldMatrix.Mul(scaleMatrix, rotMatrix); m_worldMatrix.Mul(m_worldMatrix, transMatrix); //スケルトンの更新。 m_skeleton.Update(m_worldMatrix); } //void SkinModel::Update(const CVector3& trans, const CQuaternion& rot, const CVector3& scale, EnFbxUpAxis enUpdateAxis) //{ // UpdateWorldMatrix(trans, rot, scale, enUpdateAxis); // if (isZPrePass) // { // GraphicsEngine().GetZPrepass().AddSkinModel(this); // } // if (isGBuffer) // { // GraphicsEngine().GetGBufferRender().AddSkinModel(this); // } // if (m_isShadowCaster) { // GraphicsEngine().GetShadowMap().Entry(&m_shadowCaster); // } // m_numInstance = 1; // //スケルトンの更新。 // m_skeleton.Update(m_worldMatrix); //} void SkinModel::Draw(CMatrix viewMatrix, CMatrix projMatrix) { DirectX::CommonStates state(g_graphicsEngine->GetD3DDevice()); ID3D11DeviceContext* d3dDeviceContext = g_graphicsEngine->GetD3DDeviceContext(); //定数バッファの内容を更新。 SVSConstantBuffer vsCb; //InitDirectionLight();//ここ vsCb.mWorld = m_worldMatrix; vsCb.mProj = projMatrix; vsCb.mView = viewMatrix; //todo ライトカメラのビュー、プロジェクション行列を送る。 vsCb.mLightProj = Shadow_map().GetLightProjMatrix(); vsCb.mLightView = Shadow_map().GetLighViewMatrix(); if (m_isShadowReciever == true) { vsCb.isShadowReciever = 1; } else { vsCb.isShadowReciever = 0; } //法線マップを使用するかどうかのフラグを送る。 if (m_normalMapSRV != nullptr) { vsCb.isHasNormalMap = true; } else { vsCb.isHasNormalMap = false; } //メインメモリの内容をVRAMに転送する。 //m_cb=転送先のバッファ。vsCb=転送元のメモリ。 d3dDeviceContext->UpdateSubresource(m_cb, 0, nullptr, &vsCb, 0, 0); //視点を設定。 m_light.eyePos = g_camera3D.GetPosition(); //ライト用の定数バッファを更新。 d3dDeviceContext->UpdateSubresource(m_lightCb, 0, nullptr, &m_light, 0, 0); //定数バッファをGPUに転送。 d3dDeviceContext->VSSetConstantBuffers(0, 1, &m_cb); //ピクセルシェーダーで使用する、ライト用の定数バッファを設定。 d3dDeviceContext->PSSetConstantBuffers(1, 1, &m_lightCb); //ピクセルシェーダーで使用する、定数バッファを設定。 d3dDeviceContext->PSSetConstantBuffers( 0, //定数バッファをバインドするスロット番号。 1, //設定するバッファの数。 &m_cb //設定する定数バッファ配列。 ); //サンプラステートを設定。 d3dDeviceContext->PSSetSamplers(0, 1, &m_samplerState); //ボーン行列をGPUに転送。 m_skeleton.SendBoneMatrixArrayToGPU(); if (m_normalMapSRV != nullptr) { //法線マップが設定されていたらをレジスタt4に設定する。 d3dDeviceContext->PSSetShaderResources(4, 1, &m_normalMapSRV); } //描画。 m_modelDx->Draw( d3dDeviceContext, state, m_worldMatrix, viewMatrix, projMatrix ); } void SkinModel::Draw(EnRenderMode renderMode, CMatrix viewMatrix, CMatrix projMatrix) { DirectX::CommonStates state(g_graphicsEngine->GetD3DDevice()); ID3D11DeviceContext* d3dDeviceContext = g_graphicsEngine->GetD3DDeviceContext(); //定数バッファの内容を更新。 SVSConstantBuffer vsCb; //InitDirectionLight(); vsCb.mWorld = m_worldMatrix; vsCb.mProj = projMatrix; vsCb.mView = viewMatrix; //todo ライトカメラのビュー、プロジェクション行列を送る。 vsCb.mLightProj = Shadow_map().GetLightProjMatrix(); vsCb.mLightView = Shadow_map().GetLighViewMatrix(); if (m_isShadowReciever == true) { vsCb.isShadowReciever = 1; } else { vsCb.isShadowReciever = 0; } //法線マップを使用するかどうかのフラグを送る。 if (m_normalMapSRV != nullptr) { vsCb.isHasNormalMap = true; } else { vsCb.isHasNormalMap = false; } //メインメモリの内容をVRAMに転送する。 //m_cb=転送先のバッファ。vsCb=転送元のメモリ。 d3dDeviceContext->UpdateSubresource(m_cb, 0, nullptr, &vsCb, 0, 0); //視点を設定。 m_light.eyePos = g_camera3D.GetPosition(); //ライト用の定数バッファを更新。 d3dDeviceContext->UpdateSubresource(m_lightCb, 0, nullptr, &m_light, 0, 0); //定数バッファをGPUに転送。 d3dDeviceContext->VSSetConstantBuffers(0, 1, &m_cb); //ピクセルシェーダーで使用する、ライト用の定数バッファを設定。 d3dDeviceContext->PSSetConstantBuffers(1, 1, &m_lightCb); //ピクセルシェーダーで使用する、定数バッファを設定。 d3dDeviceContext->PSSetConstantBuffers( 0, //定数バッファをバインドするスロット番号。 1, //設定するバッファの数。 &m_cb //設定する定数バッファ配列。 ); //サンプラステートを設定。 d3dDeviceContext->PSSetSamplers(0, 1, &m_samplerState); //ボーン行列をGPUに転送。 m_skeleton.SendBoneMatrixArrayToGPU(); //エフェクトにクエリを行う。 m_modelDx->UpdateEffects([&](DirectX::IEffect* material) { auto modelMaterial = reinterpret_cast<YTEngine::ModelEffect*>(material); modelMaterial->SetRenderMode(renderMode); }); if (m_normalMapSRV != nullptr) { //法線マップが設定されていたらをレジスタt2に設定する。 d3dDeviceContext->PSSetShaderResources(2, 1, &m_normalMapSRV); } //描画。 m_modelDx->Draw( d3dDeviceContext, state, m_worldMatrix, viewMatrix, projMatrix ); } }
[ "kbc17b24@stu.kawahara.ac.jp" ]
kbc17b24@stu.kawahara.ac.jp
7a5e5069579d61bab221cb2ce85a3eb23a88ddcd
81ea71bd0cd9eba88abccfa1b112d7bd7dba661e
/sources/wordgrid/WordWriterImpl.h
b55bfe7d429e25f71076e85a32f489fbd5ae3d76
[]
no_license
Mokona/La-Grille
83751b5a25a21d3dc71b02f9a36e3038f159ab15
6a1d1d15601e04eed8b62fce287e16be16dd5157
refs/heads/master
2016-08-03T12:42:11.787930
2010-02-12T22:25:09
2010-02-12T22:25:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,322
h
#ifndef WORDGRID_SIMPLEWORDWRITER #define WORDGRID_SIMPLEWORDWRITER #include "wordgrid/CommonTypes.h" #include "wordgrid/WordWriter.h" #include <string> namespace Wordgrid { class Vector2; /** A WordWriter simple implementation * * TODO : at now, WordWriter is kept by solver. If we had an instance * by loop, the undoing would be easier and less parameters would be * needed. * * But to have access to implementation, solver needs a factory to * obtain WordWriterImpl */ class WordWriterImpl : public WordWriter { public: WordWriterImpl(Grid & grid); PartialWord Write(const Vector2 & position, EDirection direction, const std::string & word); void UndoWrite(const Vector2 & position, EDirection chosenDirection, const PartialWord & writtenWord); private: void CheckIfCanWrite(const std::string & word); void CheckWordFittingOnGrid(const Vector2 & endPosition); Vector2 ComputeEndPosition(const std::string & word, const Vector2 & position, EDirection chosenDirection) const; void FillWrittenWord(const Vector2 & position, char character); PartialWord writtenWord; }; } // namespace #endif // guard
[ "mokona@puupuu.org" ]
mokona@puupuu.org
d4d9db5a70ceee8f981778411683db766faa1fb6
957bf6619d2d5edd789bfdf0bb147197a962fdf8
/plugin/samples/HelloPlugins/Classes/TestShare/TestShareScene.cpp
cf2a308f2c91e6f681c6b0adbe973a942e2c57ee
[ "MIT" ]
permissive
gibtang/CCNSCoding
f03bf4bf7ae0cb6239141b73ac54106d61e90804
2c308c67752c8d5137a81ed4df316cc137015886
refs/heads/master
2021-04-09T16:59:49.425508
2014-04-14T02:21:53
2014-04-14T02:21:53
18,506,094
1
1
null
null
null
null
UTF-8
C++
false
false
4,739
cpp
/**************************************************************************** Copyright (c) 2012-2013 cocos2d-x.org http://www.cocos2d-x.org 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 "TestShareScene.h" #include "PluginManager.h" #include "AppDelegate.h" #include "MyShareManager.h" #include "HelloWorldScene.h" using namespace cocos2d; using namespace cocos2d::plugin; enum { TAG_SHARE_BY_TWWITER = 100, TAG_SHARE_BY_WEIBO = 101, }; typedef struct tagEventMenuItem { std::string id; int tag; }EventMenuItem; static EventMenuItem s_EventMenuItem[] = { {"twitter.jpeg", TAG_SHARE_BY_TWWITER}, {"weibo.png", TAG_SHARE_BY_WEIBO} }; Scene* TestShare::scene() { // 'scene' is an autorelease object Scene *scene = Scene::create(); // 'layer' is an autorelease object TestShare *layer = TestShare::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool TestShare::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } MyShareManager::getInstance()->loadSharePlugin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. EGLView* pEGLView = EGLView::getInstance(); Point posBR = Point(pEGLView->getVisibleOrigin().x + pEGLView->getVisibleSize().width, pEGLView->getVisibleOrigin().y); Point posTL = Point(pEGLView->getVisibleOrigin().x, pEGLView->getVisibleOrigin().y + pEGLView->getVisibleSize().height); // add a "close" icon to exit the progress. it's an autorelease object MenuItemFont *pBackItem = MenuItemFont::create("Back", CC_CALLBACK_1(TestShare::menuBackCallback, this)); Size backSize = pBackItem->getContentSize(); pBackItem->setPosition(posBR + Point(- backSize.width / 2, backSize.height / 2)); // create menu, it's an autorelease object Menu* pMenu = Menu::create(pBackItem, NULL); pMenu->setPosition( Point::ZERO ); this->addChild(pMenu, 1); Point posStep = Point(150, -150); Point beginPos = posTL + (posStep * 0.5f); int line = 0; int row = 0; for (int i = 0; i < sizeof(s_EventMenuItem)/sizeof(s_EventMenuItem[0]); i++) { MenuItemImage* pMenuItem = MenuItemImage::create(s_EventMenuItem[i].id.c_str(), s_EventMenuItem[i].id.c_str(), CC_CALLBACK_1(TestShare::eventMenuCallback, this)); pMenu->addChild(pMenuItem, 0, s_EventMenuItem[i].tag); Point pos = beginPos + Point(posStep.x * row, posStep.y * line); Size itemSize = pMenuItem->getContentSize(); if ((pos.x + itemSize.width / 2) > posBR.x) { line += 1; row = 0; pos = beginPos + Point(posStep.x * row, posStep.y * line); } row += 1; pMenuItem->setPosition(pos); } return true; } void TestShare::eventMenuCallback(Object* pSender) { MenuItemLabel* pMenuItem = (MenuItemLabel*)pSender; TShareInfo pInfo; pInfo["SharedText"] = "Share message : HelloShare!"; // pInfo["SharedImagePath"] = "Full/path/to/image"; MyShareManager::MyShareMode mode = (MyShareManager::MyShareMode) (pMenuItem->getTag() - TAG_SHARE_BY_TWWITER + 1); MyShareManager::getInstance()->shareByMode(pInfo, mode); } void TestShare::menuBackCallback(Object* pSender) { MyShareManager::purgeManager(); Scene* newScene = HelloWorld::scene(); Director::getInstance()->replaceScene(newScene); }
[ "gibtang@gmail.com" ]
gibtang@gmail.com
533d9b27d9fff5127510b6769000dd7421ad712a
f9ca0e466af1ef6aa186225455382d8ee8689b07
/Biblioteca/frmConsultaLivro.h
497733155046a34708a7748bb178035d5e465077
[]
no_license
YugoVtr/Sibi_Biblioteca
ea56478396f0598708d6030f0cb29f08a95c100e
91401fe8fb670ef8625f5c43db054f472268b32a
refs/heads/master
2020-12-02T22:36:35.575633
2017-07-03T22:51:19
2017-07-03T22:51:19
96,155,971
0
1
null
2017-07-04T13:06:59
2017-07-03T22:49:54
C++
UTF-8
C++
false
false
718
h
#ifndef FRMCONSULTALIVRO_H #define FRMCONSULTALIVRO_H #include <QDialog> #include "PersistenciaLivroAutor.h" #include "PersistenciaLivroEditora.h" #include "PersistenciaLivro.h" #include "PersistenciaAutor.h" #include "PersistenciaEditora.h" #include <QDesktopWidget> #include <QStyle> namespace Ui { class frmConsultaLivro; } class frmConsultaLivro : public QDialog { Q_OBJECT public: explicit frmConsultaLivro(QWidget *parent = 0); ~frmConsultaLivro(); void inicializar()const; void limparGrid()const; private slots: void on_tableWidget_cellClicked(int row, int column); private: Ui::frmConsultaLivro *ui; QList<Biblioteca::Livro> *listaLivro; }; #endif // FRMCONSULTALIVRO_H
[ "vtrhg69@hotmail.com" ]
vtrhg69@hotmail.com
66b2eeeb10e0213c3a32932b1b28c969fc4f6c08
a22c7c60a73c75801085ca9eb9d017e7486c1e0a
/photobook/PaperMosaic/cpp/TornEffect.cpp
d785d14a1d58b0d6fcd938823e7ff5c7f0ea1179
[]
no_license
rino0601/CGLapSeoulCityProject
264346cfb5a67ae30f21e9427b793b5206c13a9b
0da4490a554abd7cf237ca04bfd8c641516def84
refs/heads/master
2020-06-02T03:48:52.093049
2013-09-06T06:58:13
2013-09-06T06:58:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,551
cpp
#import "TornEffect.h" #import "ActiveXDialog.h" TornEffect::TornEffect(void) //ª˝º∫¿⁄ { m_pNodedata = NULL; } TornEffect::~TornEffect(void) // º“∏Í¿⁄ { Destroy(); } void TornEffect::Destroy() { if(m_pNodedata){ m_pNodedata->Destroy(); delete m_pNodedata; m_pNodedata = NULL; } } //ªˆ¡æ¿Ã øµø™¿« TornEffect(ªˆ¡æ¿Ã ¡∂∞¢¿« TornEffect(∏¬¥›¥¬ ∫Œ∫–)¿« Invers«œø© »ø∞˙ ¿˚øÎ) TornEffect* TornEffect::GetInvers() { TornEffect * ret = new TornEffect(); if(!m_pNodedata ){ return ret; } ret->m_pNodedata = getInversNode(m_pNodedata); return ret; } MNode* TornEffect::getInversNode(MNode* node) { if(!node) return NULL; MNode* ret; ret = new MNode(); MFRACTAL* retval = new MFRACTAL; retval->mid = 1 - ((MFRACTAL *)node->data)->mid ; // ¡fl¡° retval->distance = ((MFRACTAL *)node->data)->distance * -1; // ≥Ù¿Ã ret->data = retval; int n = node->child.size(); if(n != 0){ ret->child.resize(n); for(int i = 0; i < n ; i++){ ret->child[i] = getInversNode( node->child[ roundRoutine(i+1, n) ] ); } } return ret; } //«¡∑∫≈ª ≥ε ª˝º∫ void TornEffect::InitEffect(float ratio, int depth) { if( m_pNodedata ) m_pNodedata->Destroy(); m_pNodedata = getFractal(ratio, depth, 1.0f); } MNode* TornEffect::getFractal(float ratio, int depth, float length) { if(length <= 0.05) return NULL; MNode* ret; // srand(time(NULL)); int randmid = random( 41 ) + 30; int randdis = random( int((ratio*200) +1) ) - ratio*100; MFRACTAL* retval = new MFRACTAL; retval->mid = randmid/100.0; retval->distance = randdis/100.0; ret = new MNode(); ret->data = retval; if(depth > 1){ ret->child.resize(2); ret->child[0] = getFractal(ratio, depth-1, length*retval->mid); ret->child[1] = getFractal(ratio, depth-1, length*(1-retval->mid)); } return ret; } // ¥Ÿ∞¢«¸ ø°¡ˆ¿« µŒ ∫§≈Õ ªÁ¿Ã¿« «¡∑∫≈ª ∆˜¿Œ∆Æ ∏Æ≈œ vector< MPoint > TornEffect::GetTornEffectPoint(MPoint a, MPoint b, int minDis, float ratio) { vector< MPoint > ret; ret = getFractalPoint(a, b, m_pNodedata, minDis, ratio); return ret; } vector< MPoint > TornEffect::getFractalPoint(MPoint a, MPoint b, MNode* info, int minDis, float ratio) { vector< MPoint > ret; if(!info){ ret.push_back(a); }else{ double dis = sqrt( double((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)) ); if(dis <= minDis) ret.push_back(a); else{ // calculate rand fractal applied mid point double randmid, randdis; randmid = ((MFRACTAL *)info->data)->mid; randdis = ((MFRACTAL *)info->data)->distance * dis; MPoint mid; mid.x = a.x*randmid + b.x*(1-randmid); mid.y = a.y*randmid + b.y*(1-randmid); double gx, gy; double temp; gx = b.y - a.y; gy = -(b.x - a.x); temp = gx*gx + gy*gy; temp =sqrt(temp); gx = gx/temp; gy = gy/temp; mid.x = mid.x + gx*randdis*ratio; mid.y = mid.y + gy*randdis*ratio; // process next depth, and summate result if(info->child.size() == 0){ ret.push_back(a); ret.push_back(mid); }else{ vector< MPoint > retb; ret = getFractalPoint(a,mid,info->child[0],minDis,ratio); retb = getFractalPoint(mid,b,info->child[1],minDis,ratio); for( int i = 0; i < (int)retb.size(); i++){ ret.push_back(retb[i]); } retb.clear(); } } } return ret; } // «¡∑∫≈ª ≥ε ¿Øπ´ ∆«¥‹ bool TornEffect::hasEffect() { if(m_pNodedata) return true; else return false; }
[ "chictiger@gmail.com" ]
chictiger@gmail.com
5b7ef0a140f5c9e48bf888873bf7a1b760de55d1
fa65788c707ca1e78e5abda5102f1627c2eed395
/kursovayaSerkova/DrawPlane.cpp
80f2ee9dc2391fae2f78168f995f631f78b3e544
[]
no_license
S-Leslie/first-course-work
242c42f5336bef5552aec1002241a8da34c9f4d9
75805f00900a3bad606c128369c1137959eaf894
refs/heads/master
2021-05-24T13:57:30.264444
2020-04-06T19:17:31
2020-04-06T19:17:31
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
5,857
cpp
#include "stdafx.h" void DrawPlane(HDC hDC, RECT rect, POINT beg, int palitra_pic) { //const int yCl=247; //const int xCl=567; const int yCl = (rect.bottom - rect.top); // const int xCl = (rect.right - rect.left); // const double dXPix = xCl / 16; const double dYPix = yCl / 13; SetMapMode(hDC, MM_ISOTROPIC); SetWindowExtEx(hDC, xCl, yCl, NULL); SetViewportExtEx(hDC, xCl, -yCl, NULL); SetViewportOrgEx(hDC, beg.x, yCl - beg.y, NULL); COLORREF myCol[3][6] = { { RGB(0,0,255), RGB(0,0,0), RGB(0,191,255), RGB(30,144, 255), RGB(70,70,70), RGB(200,180,70) }, { RGB(255, 20, 147), RGB(0,0,0), RGB(255, 99, 71), RGB(205, 92, 92), RGB(70,70,70), RGB(200,180,70) }, { RGB(0, 128, 0), RGB(0,0,0), RGB(0, 255,127), RGB(60, 179, 113), RGB(70,70,70), RGB(200,180,70) } }; //Создаем кисть LOGBRUSH lb; lb.lbColor = myCol[palitra_pic][0]; lb.lbStyle = BS_SOLID; lb.lbHatch = 5; HBRUSH hBrush = CreateBrushIndirect(&lb); HBRUSH hOldBrush = (HBRUSH)SelectObject(hDC, hBrush); //Турбина POINT pl4[] = { { 2 * dXPix, 4.75*dYPix }, // 0 { 2.25 * dXPix, 7 * dYPix }, // 1 { 3.25 * dXPix, 7 * dYPix }, //2 { 3.5 * dXPix, 4.75*dYPix },//3 { 2 * dXPix, 4.75 * dYPix } }; //0 Polyline(hDC, pl4, sizeof(pl4) / sizeof(POINT)); FloodFill(hDC, 2.5 * dXPix, 5 * dYPix, myCol[palitra_pic][1]); //Турбина 2 POINT pl5[] = { { 12.5 * dXPix, 4.75*dYPix }, // 0 { 12.75 * dXPix, 7 * dYPix }, // 1 { 13.75 * dXPix, 7 * dYPix }, //2 { 14 * dXPix, 4.75*dYPix },//3 { 12.5 * dXPix, 4.75 * dYPix } }; //0 Polyline(hDC, pl5, sizeof(pl5) / sizeof(POINT)); FloodFill(hDC, 13 * dXPix, 5 * dYPix, myCol[palitra_pic][1]); //Меняем цвет кисти lb.lbColor = myCol[palitra_pic][2]; hBrush = CreateBrushIndirect(&lb); DeleteObject(SelectObject(hDC, hBrush)); // Большие крылья POINT pl[] = { { 8 * dXPix, 3.5*dYPix }, // 0 { 0 , 7.5*dYPix }, // 1 { 16 * dXPix, 7.5*dYPix }, //2 { 8 * dXPix, 3.5*dYPix } }; // 3 Polyline(hDC, pl, sizeof(pl) / sizeof(POINT)); HRGN kr = CreatePolygonRgn(pl, 4, ALTERNATE); PaintRgn(hDC, kr); DeleteObject(kr); // Маленькие крылья POINT pl2[] = { { 8 * dXPix, 8 * dYPix }, // 0 { 6 * dXPix , 10.5*dYPix }, // 1 { 8 * dXPix, 10 * dYPix }, //2 { 10 * dXPix, 10.5*dYPix }, //3 { 8 * dXPix, 8 * dYPix } }; // 4 Polyline(hDC, pl2, sizeof(pl2) / sizeof(POINT)); //Зарисовываем крылья FloodFill(hDC, pl2[0].x , pl2[0].y + 1 * dYPix, myCol[palitra_pic][1]); //Меняем цвет кисти lb.lbColor = myCol[palitra_pic][0]; hBrush = CreateBrushIndirect(&lb); DeleteObject(SelectObject(hDC, hBrush)); //Корпус (большая часть) POINT po2[] = { { 6 * dXPix, 10 * dYPix }, // 0 { 10 * dXPix, 0 }, // 1 { 10 * dXPix, 5 * dYPix } }; // 2 int dCentr1X = (10 * dXPix - 6 * dXPix) / 2; int dCentr1Y = (10 * dYPix - 5 * dYPix) / 2; HRGN el = CreateEllipticRgn(6 * dXPix, 10 * dYPix, 10 * dXPix, 0); FillRgn(hDC, el, hBrush); DeleteObject(el); //Меняем цвет кисти lb.lbColor = myCol[palitra_pic][3]; hBrush = CreateBrushIndirect(&lb); DeleteObject(SelectObject(hDC, hBrush)); //Корпус (маленькая часть) POINT po3[] = { { 6.5 * dXPix, 6 * dYPix }, // 0 { 9.5 * dXPix, 0 }, // 1 { 9.5 * dXPix, 3 * dYPix } }; // 2 int dCentr2X = (9.5 * dXPix - 6.5 * dXPix) / 2; int dCentr2Y = (6 * dYPix - 0) / 2; for (int i = 0, dL = 14 * dXPix; i < 1; i++) { Arc(hDC, po3[0].x + i * dL, po3[0].y, po3[1].x + i * dL, po3[1].y, po3[2].x + i * dL, po3[2].y, po3[2].x + i * dL, po3[2].y); } FloodFill(hDC, 8 * dXPix, 5 * dYPix, myCol[palitra_pic][1]); FloodFill(hDC, 8 * dXPix, 2 * dYPix, myCol[palitra_pic][1]); //Меняем цвет кисти lb.lbColor = myCol[palitra_pic][0]; hBrush = CreateBrushIndirect(&lb); DeleteObject(SelectObject(hDC, hBrush)); //Носик POINT po4[] = { { 7.25 * dXPix, 1.5 * dYPix }, // 0 { 8.75 * dXPix, 0 }, // 1 { 8.75 * dXPix, 1.5 * dYPix } }; // 2 int dCentr4X = (8.75 * dXPix - 7.25 * dXPix) / 2; int dCentr4Y = (1.5 * dYPix - 0) / 2; for (int i = 0, dL = 14 * dXPix; i < 1; i++) { Arc(hDC, po4[0].x + i * dL, po4[0].y, po4[1].x + i * dL, po4[1].y, po4[2].x + i * dL, po4[2].y, po4[2].x + i * dL, po4[2].y); } FloodFill(hDC, 8 * dXPix, 1 * dYPix, myCol[palitra_pic][1]); //Меняем цвет кисти lb.lbColor = myCol[palitra_pic][5]; hBrush = CreateBrushIndirect(&lb); DeleteObject(SelectObject(hDC, hBrush)); //Окно POINT pl3[] = { { 8 * dXPix, 2.5*dYPix }, // 0 { 7 * dXPix, 3 * dYPix }, // 1 { 7 * dXPix, 4 * dYPix }, //2 { 8 * dXPix, 3.5*dYPix }, //3 { 9 * dXPix, 4 * dYPix }, //4 { 9 * dXPix, 3 * dYPix }, //5 { 8 * dXPix, 2.5*dYPix } }; //6 Polyline(hDC, pl3, sizeof(pl3) / sizeof(POINT)); FloodFill(hDC, pl3[0].x , pl3[0].y + 0.5 * dYPix, myCol[palitra_pic][1]); //Меняем цвет кисти lb.lbColor = myCol[palitra_pic][4]; hBrush = CreateBrushIndirect(&lb); DeleteObject(SelectObject(hDC, hBrush)); //Турбины (овальчики) POINT po[] = { { 2 * dXPix, 5.5 * dYPix }, // 0 { 3.5 * dXPix, 4 * dYPix }, // 1 { 3.5 * dXPix, 4.75*dYPix } }; // 2 int dCentrX = (3.5 * dXPix - 2 * dXPix) / 2; int dCentrY = (5.5 * dYPix - 4 * dYPix) / 2; HRGN el1 = CreateEllipticRgn(2 * dXPix, 5.5 * dYPix, 3.5 * dXPix, 4 * dYPix); FillRgn(hDC, el1, hBrush); DeleteObject(el1); POINT po0[] = { { 12.5 * dXPix, 5.5 * dYPix }, // 0 { 14 * dXPix, 4 * dYPix }, // 1 { 13.25 * dXPix, 4.75*dYPix } }; // 2 int dCentr0X = (14 * dXPix - 12.5 * dXPix) / 2; int dCentr0Y = (5.5 * dYPix - 4 * dYPix) / 2; HRGN el0 = CreateEllipticRgn(12.5 * dXPix, 5.5 * dYPix, 14 * dXPix, 4 * dYPix); FillRgn(hDC, el0, hBrush); DeleteObject(el0); }
[ "serkovaleslie@gmail.com" ]
serkovaleslie@gmail.com
c315c84bcf58ea33efcaeab8db49c4ae916f0696
8d9eed7eb8163ba64c49835c04db140f73821b56
/eowu-gl/src/Attribute.cpp
ad56c3b0125bbd4db750397397d13b531743180d
[]
no_license
nfagan/eowu
96dba654495e26ab3e39cd20ca489acf55de6a5d
5116f3306a3f7e813502ba00427fdc418850d28f
refs/heads/master
2020-03-27T14:18:11.835137
2019-01-02T18:08:19
2019-01-02T18:08:19
146,655,600
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
cpp
// // Attribute.cpp // eowu-gl // // Created by Nick Fagan on 8/27/18. // #include "Attribute.hpp" eowu::Attribute::Attribute(const std::string &kind_, const eowu::AttributeAggregateType &components_) : kind(kind_), components(components_) { // } eowu::Attribute::Attribute(const std::string &kind_, const eowu::AttributeComponentType *components, std::size_t n_components) : kind(kind_) { eowu::AttributeAggregateType vec_components; for (std::size_t i = 0; i < n_components; i++) { vec_components.push_back(components[i]); } this->components = std::move(vec_components); } bool eowu::Attribute::Matches(const eowu::Attribute& other) const { if (other.Size() != Size()) { return false; } return other.GetKind() == GetKind(); } const std::string& eowu::Attribute::GetKind() const { return kind; } const eowu::AttributeAggregateType& eowu::Attribute::GetComponents() const { return components; } std::size_t eowu::Attribute::Size() const { return components.size(); }
[ "nick@fagan.org" ]
nick@fagan.org
2b5fe165513d04462a6b7710e4db05b3943f2683
979dd87f54ad368da321925e5b8354bd4689429f
/src/draw/plot1D.h
827ff75f914ae555c11c757bccb9395071bf4093
[]
no_license
ku3i/framework
a0e51c73cabe941668451e5fe7659cf11cc3459f
9cb7c485181bba77a0049687f00db317ffc1ed0e
refs/heads/master
2021-11-23T01:10:24.213485
2021-11-19T14:51:09
2021-11-19T14:51:09
69,607,145
0
0
null
null
null
null
UTF-8
C++
false
false
1,886
h
/* plot1D.h */ #ifndef plot1D_H #define plot1D_H #include <vector> #include <algorithm> #include <draw/axes.h> #include <draw/draw.h> #include <draw/color_table.h> #include <common/modules.h> #include <common/log_messages.h> #include <draw/color.h> class plot1D { public: plot1D(unsigned int number_of_samples, axes& a, const Color4& c = colors::white0, const char* name = "") : number_of_samples(number_of_samples) , pointer(number_of_samples-1) , axis(a) , axis_id(axis.countNum++) , signal(number_of_samples) , color(c) , decrement(0.99) , name(name) { } virtual ~plot1D() = default; void draw(void) const; void add_sample(const float s); void reset(void) { std::fill(signal.begin(), signal.end(), .0); pointer = number_of_samples-1; } protected: void increment_pointer(void) { ++pointer; pointer %= number_of_samples; } void auto_scale (void) const; void draw_statistics(void) const; void draw_line_strip(void) const; const unsigned int number_of_samples; unsigned int pointer; axes& axis; unsigned int axis_id; std::vector<float> signal; Color4 color; const float decrement; const std::string name; }; class colored_plot1D : public plot1D { public: colored_plot1D( unsigned int number_of_samples , axes& a , ColorTable const& colortable , const char* name = "") : plot1D(number_of_samples, a, colors::white0, name) , colors(number_of_samples) , colortable(colortable) {} void add_colored_sample(float s, unsigned color_index) { add_sample(s), colors.at(pointer) = color_index; } void draw_colored(void) const; private: void draw_colored_line_strip(void) const; std::vector<unsigned> colors; ColorTable const& colortable; }; #endif /*plot1D_H*/
[ "kubisch@informatik.hu-berlin.de" ]
kubisch@informatik.hu-berlin.de
df53002c13c12a451e406c6bc63116476b6f12a8
ae33344a3ef74613c440bc5df0c585102d403b3b
/SDK/SOT_BP_ipg_eyepatch_10_v03_Desc_classes.hpp
5f19747229902fd5c5d2ea98424e0b502e5d4dac
[]
no_license
ThePotato97/SoT-SDK
bd2d253e811359a429bd8cf0f5dfff73b25cecd9
d1ff6182a2d09ca20e9e02476e5cb618e57726d3
refs/heads/master
2020-03-08T00:48:37.178980
2018-03-30T12:23:36
2018-03-30T12:23:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
728
hpp
#pragma once // SOT: Sea of Thieves (1.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x4) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_ipg_eyepatch_10_v03_Desc.BP_ipg_eyepatch_10_v03_Desc_C // 0x0000 (0x00C0 - 0x00C0) class UBP_ipg_eyepatch_10_v03_Desc_C : public UClothingDesc { public: static UClass* StaticClass() { static UClass* ptr = 0; if(ptr == 0) { ptr = UObject::FindClass(_xor_("BlueprintGeneratedClass BP_ipg_eyepatch_10_v03_Desc.BP_ipg_eyepatch_10_v03_Desc_C")); } return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "antoniohermano@gmail.com" ]
antoniohermano@gmail.com
0669501a6035000e8faaca3611b9bcd1ee9a8e79
a8822501e1a017273abb4638328d7b2be1088baf
/shared/gcnWidgets/wLabel.cpp
8c97132f9505445325c063e905c6829dd68028dd
[]
no_license
pejti/WapMap
b05748cda08d0c76603bbe28dc2f4f2f3d3e5209
19a5d56ff24cae1279e414568bd564ae661b3a44
refs/heads/master
2020-12-23T09:50:09.173873
2020-01-31T21:15:34
2020-01-31T21:15:34
237,115,263
0
0
null
2020-01-30T01:12:31
2020-01-30T01:12:31
null
UTF-8
C++
false
false
2,437
cpp
#include "wLabel.h" #include "guichan/exception.hpp" #include "guichan/font.hpp" #include "guichan/graphics.hpp" #include <hgeFont.h> #include "guichan/hge/hgeimagefont.hpp" #include "../shared/commonFunc.h" namespace SHR { Lab::Lab() { mAlignment = Graphics::LEFT; mColor = 0xFFa1a1a1; } Lab::Lab(const std::string &caption) { if (strchr(caption.c_str(), '~') == NULL) { mCaption = caption; } else { char *val = SHR::Replace(caption.c_str(), "~n~", "\n"); mCaption = std::string(val); delete[] val; } mAlignment = Graphics::LEFT; setWidth(getFont()->getWidth(caption)); setHeight(getFont()->getHeight() + 2); mColor = 0xFFa1a1a1; } const std::string &Lab::getCaption() const { return mCaption; } void Lab::setCaption(const std::string &caption) { mCaption = caption; } void Lab::setAlignment(Graphics::Alignment alignment) { mAlignment = alignment; } Graphics::Alignment Lab::getAlignment() const { return mAlignment; } void Lab::draw(Graphics *graphics) { int textX; //int textY = getHeight() / 2 - getFont()->getHeight() / 2; int textY = 0; int align; switch (getAlignment()) { case Graphics::LEFT: textX = 0; align = HGETEXT_LEFT; break; case Graphics::CENTER: textX = getWidth() / 2; align = HGETEXT_CENTER; break; case Graphics::RIGHT: textX = getWidth(); align = HGETEXT_RIGHT; break; default: throw GCN_EXCEPTION("Unknown alignment."); } int totalx, totaly; getAbsolutePosition(totalx, totaly); hgeFont *fnt = ((HGEImageFont *) getFont())->getHandleHGE(); fnt->SetColor(SETA(mColor, getAlpha())); fnt->printfb(totalx, totaly, getWidth(), getHeight(), align | HGETEXT_TOP, 0, "%s", getCaption().c_str()); //graphics->setFont(getFont()); //graphics->setColor(getForegroundColor()); //graphics->drawText(getCaption(), textX, textY, getAlignment()); } void Lab::adjustSize() { setWidth(getFont()->getWidth(getCaption())); setHeight(getFont()->getHeight() + 2); } }
[ "c37zax@gmail.com" ]
c37zax@gmail.com
35fe1db26f78c89d1e7c24f58453983f96d49450
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/56/cd397e9571a4c6/main.cpp
2273f18d0b85365ecc8603504f278fd529d9e7ad
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
#include <iostream> struct SomeInfo { int someDetail; int mapSize; int *map; }; SomeInfo DoThing(unsigned int resolution, SomeInfo result) { for(unsigned int i = 0; i < resolution; i++) { result.map[i] = i; } result.someDetail = 200; return result; } int main() { SomeInfo myInfo = {}; myInfo.mapSize = 5; int myMap[5]; myInfo.map = myMap; SomeInfo myResult = DoThing(5, myInfo); std::cout << myResult.someDetail << std::endl; std::cout << myResult.mapSize << std::endl; std::cout << myResult.map[3] << std::endl; return 0; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
443fb1590ea2b591dc1c149db5dc42cf618da51a
90d2461379f3af02c47317a3bf52729ffbfc7f54
/Cheyette/.svn/pristine/c5/c544bc436cc6abf1765805a770ba91da9906a937.svn-base
100bf7ba009704be7ed3fbe63bc776f9ab8d72df
[]
no_license
FinancialEngineerLab/LunaLibrary
c47ae96a5bdd50a26fb4631c7ee3b028eb1ae8eb
42acea0dbde826c0d2bb124e83866de2fd8888ea
refs/heads/master
2023-03-15T20:39:09.180517
2015-09-30T16:02:04
2015-09-30T16:02:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,771
#pragma once #include <iostream> #include <cassert> #include <string.h> #include <cmath> #include <fstream> #include <ql/types.hpp> #include <ql/math/array.hpp> #include <ql/math/optimization/costfunction.hpp> #include <ql/math/optimization/endcriteria.hpp> #include <ql/math/optimization/constraint.hpp> #include <ql/math/optimization/problem.hpp> #include <ql/math/optimization/simplex.hpp> #include <ql/math/optimization/bfgs.hpp> #include <ql/math/optimization/conjugategradient.hpp> #include <ql/math/optimization/levenbergmarquardt.hpp> #include <ql/termstructures/volatility/abcd.hpp> /*! \class LmmABCDFinder * * a small calibrator to find abcd coherent with the market quotation black vol * */ QuantLib::Disposable<QuantLib::Array> comp_blackVol(const std::vector<double>& timeline, const QuantLib::Array& abcd) ; class ABCDSimpleCostFunction : public QuantLib::CostFunction { public: //! constructor ABCDSimpleCostFunction( const std::vector<double>& time_line, const std::vector<double>& vol_values); virtual QuantLib::Real value(const QuantLib::Array & x) const ; virtual QuantLib::Disposable<QuantLib::Array> values(const QuantLib::Array& x) const ; //! getters std::vector<double> get_mkt_timeline() const { std::vector<double> timeline(mkt_timeline_.size() ); for(size_t i=0;i<timeline.size();++i) timeline[i]=mkt_timeline_[i]; return timeline ; } std::vector<double> get_mkt_vol_values() const { std::vector<double> vols(mkt_vol_values_.size() ); for(size_t i=0;i<vols.size();++i) vols[i]=mkt_vol_values_[i]; return vols ; } protected : std::vector<double> mkt_timeline_; QuantLib::Array mkt_vol_values_; }; class ABCDCumulativeCostFunction : public ABCDSimpleCostFunction { public: //! constructor ABCDCumulativeCostFunction( const std::vector<double>& time_line, const std::vector<double>& vol_values) : ABCDSimpleCostFunction(time_line,vol_values){} virtual QuantLib::Disposable<QuantLib::Array> values(const QuantLib::Array& x) const ; private : }; class LmmABCDFinder { public: static void print( const QuantLib::Array & abcd , const std::vector<double>& time_line , const std::vector<double>& black_vol , const std::string & filename); //! constructor LmmABCDFinder(const std::vector<double>& time_line, const std::vector<double>& vol_values) : abdcCostFunc_(time_line,vol_values) , stopCriteria_(1000, 4 , 1e-12, 1e-12, 0.) , found_abcd(4,-100000) { } void solve(); void print(const std::string& filename); private: //ABCDSimpleCostFunction abdcCostFunc_; ABCDCumulativeCostFunction abdcCostFunc_; QuantLib::EndCriteria stopCriteria_; QuantLib::EndCriteria::Type endConvergenceType_; QuantLib::Array found_abcd; };
[ "ljb8901@163.com" ]
ljb8901@163.com
69720816e4735fa562b6097ea90ef7f86f700a27
ec80c341817ea3ef219b4c93539513fcce49942f
/transformations/detector/HistNonlinearityC.hh
dbd80f84f477ae3c03ace30ca34f49156cf60544
[ "MIT" ]
permissive
gnafit/gna
b24182b12693dfe191aa182daed0a13cfbecf764
03063f66a1e51b0392562d4b9afac31f956a3c3d
refs/heads/master
2023-09-01T22:04:34.550178
2023-08-18T11:24:45
2023-08-18T11:24:45
174,980,356
5
0
null
null
null
null
UTF-8
C++
false
false
1,601
hh
#pragma once #include <vector> #include "HistSmearSparse.hh" #include "Eigen/Sparse" /** * @brief A class to smear the 1d histogram due to rescaling of the X axis * * HistNonlinearityC projects the shifted bins on the original binning. * The output histogram contains more bins: a distinct bin for each overlap * of smeared binning. * The output histogram is shared as two arrays: data and edges as the edges * are defined during the runtime. */ class HistNonlinearityC: public HistSmearSparse, public TransformationBind<HistNonlinearityC> { public: using TransformationBind<HistNonlinearityC>::transformation_; HistNonlinearityC(float nbins_factor, size_t nbins_extra, GNA::DataPropagation propagate_matrix=GNA::DataPropagation::Ignore); HistNonlinearityC(GNA::DataPropagation propagate_matrix=GNA::DataPropagation::Ignore) : HistNonlinearityC(2.2, 1, propagate_matrix) {}; void set(SingleOutput& orig, SingleOutput& orig_proj, SingleOutput& mod_proj); void set_range( double min, double max ) { m_range_min=min; m_range_max=max; } double get_range_min() { return m_range_min; } double get_range_max() { return m_range_max; } private: void calcSmear(FunctionArgs& fargs); void calcMatrix(FunctionArgs& fargs); void types(TypesFunctionArgs& fargs); bool m_initialized{false}; double m_range_min{-1.e+100}; double m_range_max{+1.e+100}; double const* m_edges=nullptr; const float m_nbins_factor = 2.2; const size_t m_nbins_extra = 1; const double m_overflow_step = 10.0; // Eigen::SparseMatrix<double> m_sparse_rebin; };
[ "maxim.mg.gonchar@gmail.com" ]
maxim.mg.gonchar@gmail.com
2c4f709d472bfb516bc1a6617f65880190a61dd6
adaf72cf718777d3d50aefe3153a40e0c8e372a5
/rx_pbf(PositionBaseFluid)/shared/inc/rx_trackball.cpp
9735390d00a352c5e2f3d35a5c8f6e0d04cb3344
[]
no_license
isliulin/OpenGL_projects
28d82f399713a2f22938b4f3ce0aae21b9dceba9
31d21853210d0da5b6ea16b18d3a4f252f1bfbdd
refs/heads/master
2021-06-22T03:53:03.701382
2017-08-23T04:32:27
2017-08-23T04:32:27
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
24,668
cpp
/*! @file rx_trackball.cpp @brief 簡易トラックボール処理 @author Makoto Fujisawa @date 2008 */ // FILE --rx_trackball.cpp-- //----------------------------------------------------------------------------- // インクルードファイル //----------------------------------------------------------------------------- #include <math.h> #include "rx_trackball.h" #include "GL/glut.h" //----------------------------------------------------------------------------- // 定義 //----------------------------------------------------------------------------- template<class T> inline bool RX_FEQ2(const T &a, const T &b, const T &eps){ return (fabs(a-b) < eps); } const double TB_PI = 3.14159265358979323846; const double TB_ROT_SCALE = 2.0*TB_PI; //!< マウスの相対位置→回転角の換算係数 const double RX_FEQ_EPS = 1.0e-10; // deg->rad の変換(pi/180.0) const double RX_DEGREES_TO_RADIANS = 0.0174532925199432957692369076848; // rad->deg の変換(180.0/pi) const double RX_RADIANS_TO_DEGREES = 57.295779513082320876798154814114; template<class T> inline T RX_TO_RADIANS(const T &x){ return static_cast<T>((x)*RX_DEGREES_TO_RADIANS); } template<class T> inline T RX_TO_DEGREES(const T &x){ return static_cast<T>((x)*RX_RADIANS_TO_DEGREES); } inline int IDX(int row, int col){ return (row | (col<<2)); } //inline int IDX(int row, int col){ return (4*row+col); } //----------------------------------------------------------------------------- // MARK:グローバル変数 //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // MARK:行列関数 //----------------------------------------------------------------------------- /*! * 行列とベクトルのかけ算(d = m x v) * @param[out] d 結果のベクトル * @param[in] m 4x4行列 * @param[in] v 4次元ベクトル */ static void MulMatVec(double d[4], const double m[16], const double v[4]) { d[0] = (v[0]*m[IDX(0,0)]+v[1]*m[IDX(0,1)]+v[2]*m[IDX(0,2)]+v[3]*m[IDX(0,3)]); d[1] = (v[0]*m[IDX(1,0)]+v[1]*m[IDX(1,1)]+v[2]*m[IDX(1,2)]+v[3]*m[IDX(1,3)]); d[2] = (v[0]*m[IDX(2,0)]+v[1]*m[IDX(2,1)]+v[2]*m[IDX(2,2)]+v[3]*m[IDX(2,3)]); d[3] = (v[0]*m[IDX(3,0)]+v[1]*m[IDX(3,1)]+v[2]*m[IDX(3,2)]+v[3]*m[IDX(3,3)]); } /*! * ベクトルと行列のかけ算(d = v x m) * @param[out] d 結果のベクトル * @param[in] v 4次元ベクトル * @param[in] m 4x4行列 */ static void MulVecMat(double d[4], const double v[4], const double m[16]) { d[0] = (v[0]*m[IDX(0,0)]+v[1]*m[IDX(1,0)]+v[2]*m[IDX(2,0)]+v[3]*m[IDX(3,0)]); d[1] = (v[0]*m[IDX(0,1)]+v[1]*m[IDX(1,1)]+v[2]*m[IDX(2,1)]+v[3]*m[IDX(3,1)]); d[2] = (v[0]*m[IDX(0,2)]+v[1]*m[IDX(1,2)]+v[2]*m[IDX(2,2)]+v[3]*m[IDX(3,2)]); d[3] = (v[0]*m[IDX(0,3)]+v[1]*m[IDX(1,3)]+v[2]*m[IDX(2,3)]+v[3]*m[IDX(3,3)]); } /*! * 単位行列生成 * @param[out] m 単位行列 */ static void Identity(double m[16]) { for(int i = 0; i < 4; ++i){ for(int j = 0; j < 4; ++j){ if(i == j){ m[IDX(i,j)] = 1.0; } else{ m[IDX(i,j)] = 0.0; } } } } /*! * 行列コピー * @param[out] src コピー元行列 * @param[out] dst コピー先行列 */ static void CopyMat(const double src[16], double dst[16]) { for(int i = 0; i < 4; ++i){ for(int j = 0; j < 4; ++j){ dst[IDX(i,j)] = src[IDX(i,j)]; } } } /*! * 逆行列(4x4)計算 * @param[out] inv_m 逆行列 * @param[in] m 元の行列 */ static void Inverse(double inv_m[16], const double m[16]) { Identity(inv_m); double r1[8], r2[8], r3[8], r4[8]; double *s[4], *tmprow; s[0] = &r1[0]; s[1] = &r2[0]; s[2] = &r3[0]; s[3] = &r4[0]; register int i,j,p,jj; for(i = 0; i < 4; ++i){ for(j = 0; j < 4; ++j){ s[i][j] = m[IDX(i, j)]; if(i==j){ s[i][j+4] = 1.0; } else{ s[i][j+4] = 0.0; } } } double scp[4]; for(i = 0; i < 4; ++i){ scp[i] = double(fabs(s[i][0])); for(j=1; j < 4; ++j) if(double(fabs(s[i][j])) > scp[i]) scp[i] = double(fabs(s[i][j])); if(scp[i] == 0.0) return; // singular matrix! } int pivot_to; double scp_max; for(i = 0; i < 4; ++i){ // select pivot row pivot_to = i; scp_max = double(fabs(s[i][i]/scp[i])); // find out which row should be on top for(p = i+1; p < 4; ++p) if(double(fabs(s[p][i]/scp[p])) > scp_max){ scp_max = double(fabs(s[p][i]/scp[p])); pivot_to = p; } // Pivot if necessary if(pivot_to != i) { tmprow = s[i]; s[i] = s[pivot_to]; s[pivot_to] = tmprow; double tmpscp; tmpscp = scp[i]; scp[i] = scp[pivot_to]; scp[pivot_to] = tmpscp; } double mji; // perform gaussian elimination for(j = i+1; j < 4; ++j) { mji = s[j][i]/s[i][i]; s[j][i] = 0.0; for(jj=i+1; jj<8; jj++) s[j][jj] -= mji*s[i][jj]; } } if(s[3][3] == 0.0) return; // singular matrix! // // Now we have an upper triangular matrix. // // x x x x | y y y y // 0 x x x | y y y y // 0 0 x x | y y y y // 0 0 0 x | y y y y // // we'll back substitute to get the inverse // // 1 0 0 0 | z z z z // 0 1 0 0 | z z z z // 0 0 1 0 | z z z z // 0 0 0 1 | z z z z // double mij; for(i = 3; i > 0; --i){ for(j = i-1; j > -1; --j){ mij = s[j][i]/s[i][i]; for(jj = j+1; jj < 8; ++jj){ s[j][jj] -= mij*s[i][jj]; } } } for(i = 0; i < 4; ++i){ for(j = 0; j < 4; ++j){ inv_m[IDX(i,j)] = s[i][j+4]/s[i][i]; } } } //----------------------------------------------------------------------------- // MARK:四元数関数 //----------------------------------------------------------------------------- /*! * 四元数のかけ算(r = p x q)の計算 * @param[out] r 積の結果 * @param[in] p,q 元の四元数 */ static void MulQuat(double r[], const double p[], const double q[]) { r[0] = p[0]*q[0] - p[1]*q[1] - p[2]*q[2] - p[3]*q[3]; r[1] = p[0]*q[1] + p[1]*q[0] + p[2]*q[3] - p[3]*q[2]; r[2] = p[0]*q[2] - p[1]*q[3] + p[2]*q[0] + p[3]*q[1]; r[3] = p[0]*q[3] + p[1]*q[2] - p[2]*q[1] + p[3]*q[0]; } /*! * 四元数の初期化 * @param[inout] r 初期化する四元数 */ static void InitQuat(double r[]) { r[0] = 1.0; r[1] = 0.0; r[2] = 0.0; r[3] = 0.0; } /*! * 四元数のコピー(r = p) * @param[out] r コピー先の四元数 * @param[in] p コピー元の四元数 */ static void CopyQuat(double r[], const double p[]) { r[0] = p[0]; r[1] = p[1]; r[2] = p[2]; r[3] = p[3]; } /* * 四元数 -> 回転変換行列 * @param[out] r 回転変換行列 * @param[in] q 四元数 */ static void RotQuat(double r[], const double q[]) { double x2 = q[1]*q[1]*2.0; double y2 = q[2]*q[2]*2.0; double z2 = q[3]*q[3]*2.0; double xy = q[1]*q[2]*2.0; double yz = q[2]*q[3]*2.0; double zx = q[3]*q[1]*2.0; double xw = q[1]*q[0]*2.0; double yw = q[2]*q[0]*2.0; double zw = q[3]*q[0]*2.0; r[ 0] = 1.0 - y2 - z2; r[ 1] = xy + zw; r[ 2] = zx - yw; r[ 4] = xy - zw; r[ 5] = 1.0 - z2 - x2; r[ 6] = yz + xw; r[ 8] = zx + yw; r[ 9] = yz - xw; r[10] = 1.0 - x2 - y2; r[ 3] = r[ 7] = r[11] = r[12] = r[13] = r[14] = 0.0; r[15] = 1.0; } /* * 回転変換行列 -> 四元数 * @param[in] q 四元数 * @param[out] r 回転変換行列(4x4) */ static void QuatRot(double q[], double r[]) { double tr, s; const int nxt[3] = { 1, 2, 0 }; tr = r[0]+r[5]+r[10]; if(tr > 0.0){ s = sqrt(tr+r[15]); q[3] = s*0.5; s = 0.5/s; q[0] = (r[6]-r[9])*s; q[1] = (r[8]-r[2])*s; q[2] = (r[1]-r[4])*s; } else{ int i, j, k; i = 0; if(r[5] > r[0]) i = 1; if(r[10] > r[IDX(i, i)]) i = 2; j = nxt[i]; k = nxt[j]; s = sqrt((r[IDX(i, j)]-(r[IDX(j, j)]+r[IDX(k, k)]))+1.0); q[i] = s*0.5; s = 0.5/s; q[3] = (r[IDX(j, k)]-r[IDX(k, j)])*s; q[j] = (r[IDX(i, j)]+r[IDX(j, i)])*s; q[k] = (r[IDX(i, k)]+r[IDX(k, i)])*s; } } /* * 球面線形補間 * @param[out] p 補間結果の四元数 * @param[in] q0,q1 補間対象2ベクトル * @param[in] t パラメータ */ void QuatLerp(double p[], const double q0[], const double q1[], const double t) { double qr = q0[0]*q1[0]+q0[1]*q1[1]+q0[2]*q1[2]+q0[3]*q1[3]; double ss = 1.0-qr*qr; if(ss == 0.0){ p[0] = q0[0]; p[1] = q0[1]; p[2] = q0[2]; p[3] = q0[3]; } else{ double sp = sqrt(ss); double ph = acos(qr); // ベクトル間の角度θ double pt = ph*t; // θt double t1 = sin(pt)/sp; double t0 = sin(ph-pt)/sp; p[0] = q0[0]*t0+q1[0]*t1; p[1] = q0[1]*t0+q1[1]*t1; p[2] = q0[2]*t0+q1[2]*t1; p[3] = q0[3]*t0+q1[3]*t1; } } /* * 複数のクォータニオン間の球面線形補間(折れ線) * p ← t[i] におけるクォータニオン q[i], 0 <= i < n に対する * u における補間値 */ void QuatMultiLerp(double p[], const double t[], const double q[][4], const int n, const double u) { int i = 0, j = n-1; // u を含む t の区間 [t[i], t[i+1]) を二分法で求める while(i < j){ int k = (i+j)/2; if(t[k] < u){ i = k+1; } else{ j = k; } } if(i > 0){ --i; } QuatLerp(p, q[i], q[i+1], (u-t[i])/(t[i+1]-t[i])); } void SetQuat(double q[], const double ang, const double ax, const double ay, const double az) { double as = ax*ax+ay*ay+az*az; if(as < RX_FEQ_EPS){ q[0] = 1.0; q[1] = 0.0; q[2] = 0.0; q[3] = 0.0; } else{ as = sqrt(as); double rd = 0.5*RX_TO_RADIANS(ang); double st = sin(rd); q[0] = cos(rd); q[1] = ax*st/as; q[2] = ay*st/as; q[3] = az*st/as; } } /*! * 四元数によるベクトルの回転 * @param[out] dst 回転後のベクトル * @param[in] q 四元数 * @param[in] src ベクトル */ inline void QuatVec(double dst[], const double q[], const double src[]) { double v_coef = q[0]*q[0]-q[1]*q[1]-q[2]*q[2]-q[3]*q[3]; double u_coef = 2.0*(src[0]*q[1]+src[1]*q[2]+src[2]*q[3]); double c_coef = 2.0*q[0]; dst[0] = v_coef*src[0]+u_coef*q[1]+c_coef*(q[2]*src[2]-q[3]*src[1]); dst[1] = v_coef*src[1]+u_coef*q[2]+c_coef*(q[3]*src[0]-q[1]*src[2]); dst[2] = v_coef*src[2]+u_coef*q[3]+c_coef*(q[1]*src[1]-q[2]*src[0]); } /*! * 共役四元数 * @param[in] q 元の四元数 * @param[out] qc 共役四元数 */ inline void QuatInv(const double q[], double qc[]) { qc[0] = q[0]; qc[1] = -q[1]; qc[2] = -q[2]; qc[3] = -q[3]; } //----------------------------------------------------------------------------- // MARK:トラックボール //----------------------------------------------------------------------------- /*! * コンストラクタ */ rxTrackball::rxTrackball() { m_fTransScale = 10.0; m_iVeloc[0] = 0; m_iVeloc[1] = 0; // 回転(クォータニオン) InitQuat(m_fQuatRot); // ドラッグ中の回転増分量(クォータニオン) InitQuat(m_fQuatIncRot); // 回転の変換行列 Identity(m_fMatRot); // カメラパン m_fTransDist[0] = 0.0; m_fTransDist[1] = 0.0; // スケーリング m_fScaleDist = 0.0; // ドラッグ中か否か(1:左ドラッグ, 2:右ドラッグ, 3:ミドルドラッグ) m_iDrag = 0; } /*! * デストラクタ */ rxTrackball::~rxTrackball() { } /* * トラックボール処理の初期化 * - プログラムの初期化処理のところで実行する */ void rxTrackball::Init(void) { // ドラッグ中ではない m_iDrag = 0; // 単位クォーターニオン InitQuat(m_fQuatIncRot); // 回転行列の初期化 RotQuat(m_fMatRot, m_fQuatRot); // カーソル速度 m_iVeloc[0] = 0; m_iVeloc[1] = 0; } /* * トラックボールする領域 * - Reshape コールバック (resize) の中で実行する * @param[in] w,h ビューポートの大きさ */ void rxTrackball::SetRegion(int w, int h) { // マウスポインタ位置のウィンドウ内の相対的位置への換算用 m_fW = (double)w; m_fH = (double)h; } /* * 3D空間領域の設定 * - * @param[in] l 代表長さ */ void rxTrackball::SetSpace(double l) { m_fTransScale = 10.0*l; } //----------------------------------------------------------------------------- // MARK:マウスドラッグ //----------------------------------------------------------------------------- /* * ドラッグ開始 * - マウスボタンを押したときに実行する * @param[in] x,y マウス位置 */ void rxTrackball::Start(int x, int y, int button) { if(x < 0 || y < 0 || x > (int)m_fW || y > (int)m_fH) return; //RXCOUT << "Start " << x << " x " << y << " - " << button << endl; // ドラッグ開始 m_iDrag = button; // ドラッグ開始点を記録 m_iSx = x; m_iSy = y; m_iPx = x; m_iPy = y; } void rxTrackball::TrackballLastRot(void) { double dq[4]; CopyQuat(dq, m_fQuatRot); // クォータニオンを掛けて回転を合成 MulQuat(m_fQuatRot, m_fQuatIncRot, dq); // クォータニオンから回転の変換行列を求める RotQuat(m_fMatRot, m_fQuatRot); } void rxTrackball::TrackballRot(double vx, double vy) { if(m_fW < RX_FEQ_EPS || m_fH < RX_FEQ_EPS) return; double dx = vx/m_fW; double dy = vy/m_fH; double a = sqrt(dx*dx+dy*dy); // 回転処理 if(a != 0.0){ double ar = a*TB_ROT_SCALE*0.5; double as = sin(ar)/a; double dq[4] = { cos(ar), dy*as, dx*as, 0.0 }; m_fLastRot[0] = cos(ar); m_fLastRot[1] = dy*as; m_fLastRot[2] = dx*as; m_fLastRot[3] = 0.0; CopyQuat(m_fQuatIncRot, dq); CopyQuat(dq, m_fQuatRot); // クォータニオンを掛けて回転を合成 MulQuat(m_fQuatRot, m_fQuatIncRot, dq); // クォータニオンから回転の変換行列を求める RotQuat(m_fMatRot, m_fQuatRot); } else{ InitQuat(m_fQuatIncRot); } } /* * ドラッグ中 * - マウスのドラッグ中に実行する * @param[in] x,y マウス位置 */ void rxTrackball::Motion(int x, int y, bool last) { if(x < 0 || y < 0 || x > (int)m_fW || y > (int)m_fH) return; //RXCOUT << "Motion " << x << " x " << y << endl; if(m_iDrag){ if(m_iDrag == 1){ // 回転 // マウスポインタの位置のドラッグ開始位置からの変位 TrackballRot((double)(x-m_iPx), (double)(y-m_iPy)); } else if(m_iDrag == 2){ // パン // マウスポインタの位置の前回位置からの変位 double dx = (x-m_iPx)/m_fW; double dy = (y-m_iPy)/m_fH; m_fTransDist[0] += m_fTransScale*dx; m_fTransDist[1] -= m_fTransScale*dy; } else if(m_iDrag == 3){ // スケーリング // マウスポインタの位置の前回位置からの変位 double dx = (x-m_iPx)/m_fW; double dy = (y-m_iPy)/m_fH; m_fScaleDist += m_fTransScale*dy; } if(!last){ m_iVeloc[0] = x-m_iPx; m_iVeloc[1] = y-m_iPy; } m_iPx = x; m_iPy = y; } } /* * 停止 * - マウスボタンを離したときに実行する * @param[in] x,y マウス位置 */ void rxTrackball::Stop(int x, int y) { if(x < 0 || y < 0 || x > (int)m_fW || y > (int)m_fH || !m_iDrag) return; //RXCOUT << "Stop " << x << " x " << y << endl; // ドラッグ終了点における回転を求める TrackballRot(x-m_iPx, y-m_iPy); //Motion(x, y, true); // ドラッグ終了 m_iDrag = 0; } //----------------------------------------------------------------------------- // MARK:パラメータ取得 //----------------------------------------------------------------------------- /* * 回転の変換行列を返す * - 返値を glMultMatrixd() などで使用してオブジェクトを回転する */ double *rxTrackball::GetRotation(void) { return m_fMatRot; } void rxTrackball::GetQuaternion(double q[4]) const { CopyQuat(q, m_fQuatRot); } /* * スケーリング量を返す * - 返値を glTranslatef() などで使用して視点移動 */ double rxTrackball::GetScaling(void) const { return m_fScaleDist; } void rxTrackball::GetScaling(double &s) const { s = m_fScaleDist; } /* * 平行移動量を返す * - 返値を glTranslatef() などで使用して視点移動 * @param[in] i 0:x,1:y */ double rxTrackball::GetTranslation(int i) const { return m_fTransDist[i]; } void rxTrackball::GetTranslation(double t[2]) const { t[0] = m_fTransDist[0]; t[1] = m_fTransDist[1]; } double* rxTrackball::GetQuaternionR(void) { return m_fQuatRot; } double* rxTrackball::GetTranslationR(void) { return m_fTransDist; } double* rxTrackball::GetScalingR(void) { return &m_fScaleDist; } /*! * 全変換行列 * @param[out] m[16] */ void rxTrackball::GetTransform(double m[16]) { Identity(m); for(int i = 0; i < 3; ++i){ for(int j = 0; j < 3; ++j){ m[IDX(i, j)] = m_fMatRot[IDX(i, j)]; } } m[IDX(0, 3)] = m_fTransDist[0]; m[IDX(1, 3)] = m_fTransDist[1]; m[IDX(2, 3)] = m_fScaleDist; } /* * トラックボール速度 * @param[out] vx,vy 速度(ピクセル/フレーム) */ void rxTrackball::GetLastVeloc(int &vx, int &vy) { vx = m_iVeloc[0]; vy = m_iVeloc[1]; } /*! * グローバル座標からオブジェクトローカル座標への変換 * @param[out] dst ローカル座標 * @param[in] src グローバル座標 */ void rxTrackball::CalLocalPos(double dst[4], const double src[4]) { // 平行移動 double pos[4]; pos[0] = src[0]-m_fTransDist[0]; pos[1] = src[1]-m_fTransDist[1]; // スケーリング pos[2] = src[2]-m_fScaleDist; pos[3] = 0.0; // 回転 double qc[4]; QuatInv(m_fQuatRot, qc); QuatVec(dst, qc, pos); } /*! * オブジェクトローカル座標からグローバル座標への変換 * @param[out] dst グローバル座標 * @param[in] src ローカル座標 */ void rxTrackball::CalGlobalPos(double dst[4], const double src[4]) { // 回転 QuatVec(dst, m_fQuatRot, src); // 平行移動 dst[0] += m_fTransDist[0]; dst[1] += m_fTransDist[1]; // スケーリング dst[2] += m_fScaleDist; } /*! * 視点位置を算出 * @param[out] pos 視点位置 */ void rxTrackball::GetViewPosition(double pos[3]) { double src[4] = {0, 0, 0, 0}; double dst[4]; CalLocalPos(dst, src); pos[0] = dst[0]; pos[1] = dst[1]; pos[2] = dst[2]; } /*! * グローバル座標からオブジェクトローカル座標への変換(回転のみ) * @param[out] dst ローカル座標 * @param[in] src グローバル座標 */ void rxTrackball::CalLocalRot(double dst[4], const double src[4]) { // 回転 double qc[4]; QuatInv(m_fQuatRot, qc); QuatVec(dst, qc, src); } /*! * オブジェクトローカル座標からグローバル座標への変換(回転のみ) * @param[out] dst グローバル座標 * @param[in] src ローカル座標 */ void rxTrackball::CalGlobalRot(double dst[4], const double src[4]) { QuatVec(dst, m_fQuatRot, src); } /*! * 視線方向を算出 * @param[out] dir 視線方向 */ void rxTrackball::GetViewDirection(double dir[3]) { double src[4] = {0, 0, -1, 0}; double dst[4]; CalLocalRot(dst, src); dir[0] = dst[0]; dir[1] = dst[1]; dir[2] = dst[2]; } /* * OpenGLに回転の変換行列を設定 */ void rxTrackball::ApplyRotation(void) { glMultMatrixd(m_fMatRot); } /* * OpenGLにスケーリングを設定 */ void rxTrackball::ApplyScaling(void) { glTranslated(0.0, 0.0, m_fScaleDist); } /* * OpenGLに平行移動を設定 */ void rxTrackball::ApplyTranslation(void) { glTranslated(m_fTransDist[0], m_fTransDist[1], 0.0); } /* * OpenGLに回転の変換行列を設定 */ void rxTrackball::ApplyQuaternion(const double q[4]) { double m[16]; RotQuat(m, q); glMultMatrixd(m); } /*! * OpenGLのオブジェクト変換 */ void rxTrackball::Apply(void) { ApplyScaling(); ApplyTranslation(); ApplyRotation(); } //----------------------------------------------------------------------------- // MARK:パラメータ設定 //----------------------------------------------------------------------------- /* * スケーリング量を設定 * @param[in] z 移動量 */ void rxTrackball::SetScaling(double z) { m_fScaleDist = z; } /* * 平行移動量を設定 * @param[in] x,y 移動量 */ void rxTrackball::SetTranslation(double x, double y) { m_fTransDist[0] = x; m_fTransDist[1] = y; } /* * 回転量を設定 * @param[in] rot 4x4行列 */ void rxTrackball::SetRotation(double rot[16]) { for(int i = 0; i < 16; ++i){ m_fMatRot[i] = rot[i]; // 回転の変換行列からクォータニオンを求める QuatRot(m_fQuatRot, m_fMatRot); } } /* * 回転量を設定 * @param[in] q 四元数 */ void rxTrackball::SetQuaternion(double q[4]) { // クォータニオンから回転の変換行列を求める RotQuat(m_fMatRot, q); // 回転の保存 CopyQuat(m_fQuatRot, q); } /* * 回転量を設定 * @param[in] ang 回転量[deg] * @param[in] x,y,z 回転軸 */ void rxTrackball::SetRotation(double ang, double x, double y, double z) { double a = sqrt(x*x+y*y+z*z); if(!RX_FEQ2(a, 0.0, RX_FEQ_EPS)){ double ar = 0.5*RX_TO_RADIANS(ang); double as = sin(ar)/a; double dq[4] = { cos(ar), x*as, y*as, z*as }; // クォータニオンから回転の変換行列を求める RotQuat(m_fMatRot, dq); // 回転の保存 CopyQuat(m_fQuatRot, dq); } } /* * 回転を追加 * @param[in] ang 回転量[deg] * @param[in] x,y,z 回転軸 */ void rxTrackball::AddRotation(double ang, double x, double y, double z) { double a = sqrt(x*x+y*y+z*z); if(!RX_FEQ2(a, 0.0, RX_FEQ_EPS)){ double ar = 0.5*RX_TO_RADIANS(ang); double as = sin(ar)/a; double dq[4] = { cos(ar), x*as, y*as, z*as }; m_fLastRot[0] = cos(ar); m_fLastRot[1] = x*as; m_fLastRot[2] = y*as; m_fLastRot[3] = 0.0; CopyQuat(m_fQuatIncRot, dq); CopyQuat(dq, m_fQuatRot); // クォータニオンを掛けて回転を合成 MulQuat(m_fQuatRot, m_fQuatIncRot, dq); // クォータニオンから回転の変換行列を求める RotQuat(m_fMatRot, m_fQuatRot); } } void rxTrackball::GetLastRotation(double &ang, double &x, double &y, double &z) { ang = m_fLastRot[0]; x = m_fLastRot[1]; y = m_fLastRot[2]; z = m_fLastRot[3]; } inline double dot(const double a[3], const double b[3]) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; } inline void cross(const double a[3], const double b[3], double c[3]) { c[0] = a[1]*b[2]-a[2]*b[1]; c[1] = a[2]*b[0]-a[0]*b[2]; c[2] = a[0]*b[1]-a[1]*b[0]; } inline double normalize(double a[3]) { double d = dot(a, a); if(d > 0.0){ double l = sqrt(1.0/d); a[0] *= l; a[1] *= l; a[2] *= l; } return d; } /*! * マウスクリックした位置への方向ベクトルを返す * @param[in] * @param[out] * @return */ void rxTrackball::GetRayTo(int x, int y, double fov, double ray_to[3]) { double eye_pos[3], eye_dir[3], up_dir[3] = {0, 1, 0}; double init_pos[3] = {0, 0, 0}; double init_dir[3] = {0, 0, -1}; double init_up[3] = {0, 1, 0}; CalLocalPos(eye_pos, init_pos); CalLocalRot(eye_dir, init_dir); CalLocalRot(up_dir, init_up); normalize(eye_dir); double far_d = 10.0; eye_dir[0] *= far_d; eye_dir[1] *= far_d; eye_dir[2] *= far_d; normalize(up_dir); // 視線に垂直な平面の左右,上下方向 double hor[3], ver[3]; cross(eye_dir, up_dir, hor); normalize(hor); cross(hor, eye_dir, ver); normalize(ver); double tanfov = tan(0.5*RX_TO_RADIANS(fov)); double d = 2.0*far_d*tanfov; double aspect = m_fW/m_fH; hor[0] *= d*aspect; hor[1] *= d*aspect; hor[2] *= d*aspect; ver[0] *= d; ver[1] *= d; ver[2] *= d; // 描画平面の中心 ray_to[0] = eye_pos[0]+eye_dir[0]; ray_to[1] = eye_pos[1]+eye_dir[1]; ray_to[2] = eye_pos[2]+eye_dir[2]; // 中心から視点に垂直な平面の左右,上下方向にマウスの座標分移動させる double dx = (x-0.5*m_fW)/m_fW, dy = (0.5*m_fH-y)/m_fH; ray_to[0] += dx*hor[0]; ray_to[1] += dx*hor[1]; ray_to[2] += dx*hor[2]; ray_to[0] += dy*ver[0]; ray_to[1] += dy*ver[1]; ray_to[2] += dy*ver[2]; }
[ "noreply@github.com" ]
noreply@github.com
44c883dcc132c4d133816b36648ea933a7507a1a
0b189a6f7913d5d3f06d17fc3add1d990d8b7828
/CryptoLite/Registry.h
475709913446951c7b46db58ffc282ac74d0a28d
[]
no_license
yuhisern7/CryptoLite
276bc7b677f71b93419ce910b5fe2c19c285517d
32e105ba6ce11c3283a901be8cf759e93af7acbb
refs/heads/master
2020-06-28T18:56:57.818758
2018-02-02T13:58:57
2018-02-02T13:58:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
282
h
#pragma once #include "stdafx.h" class Registry { public: static void RegisterProgram(); static void RemoveProgram(); private: static BOOL RegisterForStartup(PCWSTR pszAppName, PCWSTR pathToExe); static BOOL RemoveFromStartup(PCWSTR pszAppName, PCWSTR pathToExe); };
[ "wdstott@hotmail.co.uk" ]
wdstott@hotmail.co.uk
cb179e0bd3251858e8b1e24284686ad60607eedf
660acb77fc12d21367716779bc8884390dd3c93b
/mainwindow.cpp
736a65647fbfdffc40c7644bf2cbd884c3048429
[]
no_license
bragov4ik/DE_Assignment
694965e9f753b914e7aec8ea5cfbb093c94796da
c6b913ab1a71f97087244d604962986bebc8199a
refs/heads/master
2023-01-02T14:11:49.600199
2020-10-24T20:04:45
2020-10-24T20:04:45
303,496,990
0
0
null
null
null
null
UTF-8
C++
false
false
4,396
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , model() { ui->setupUi(this); QObject::connect(ui->checkBox_exact, &QAbstractButton::toggled, this, &MainWindow::on_show_exact_toggled); QObject::connect(ui->checkBox_euler, &QAbstractButton::toggled, this, &MainWindow::on_show_euler_toggled); QObject::connect(ui->checkBox_improved_euler, &QAbstractButton::toggled, this, &MainWindow::on_show_improved_euler_toggled); QObject::connect(ui->checkBox_runge_kutta, &QAbstractButton::toggled, this, &MainWindow::on_show_runge_kutta_toggled); QObject::connect(ui->autoupd_checkbox_1, &QAbstractButton::toggled, this, &MainWindow::on_autoupd_checkbox_1_toggled); QObject::connect(ui->ivalue_spinBox_6, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::on_n_0_value_changed); QObject::connect(ui->ivalue_spinBox_5, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::on_N_value_changed); QObject::connect(ui->ivalue_doubleSpinBox_1, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::on_x_0_value_changed); QObject::connect(ui->ivalue_doubleSpinBox_3, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::on_y_0_value_changed); QObject::connect(ui->ivalue_doubleSpinBox_2, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MainWindow::on_X_value_changed); QObject::connect(ui->plot_pushButton, &QAbstractButton::clicked, this, &MainWindow::on_plot_pushButton_clicked); QObject::connect(ui->plot_pushButton_2, &QAbstractButton::clicked, this, &MainWindow::on_plot_pushButton_clicked); QChartView* methods_view = ui->graphicsView_approx; methods_view->setChart(model.get_methods_chart()); methods_view->setRenderHint(QPainter::HighQualityAntialiasing); QChartView* lte_view = ui->graphicsView_lte; lte_view->setChart(model.get_lte_chart()); lte_view->setRenderHint(QPainter::HighQualityAntialiasing); QChartView* gte_view = ui->graphicsView_gte; gte_view->setChart(model.get_gte_chart()); gte_view->setRenderHint(QPainter::HighQualityAntialiasing); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_show_exact_toggled(bool checked) { model.set_show_exact(checked); } void MainWindow::on_show_euler_toggled(bool checked) { model.set_show_euler(checked); } void MainWindow::on_show_improved_euler_toggled(bool checked) { model.set_show_improved_euler(checked); } void MainWindow::on_show_runge_kutta_toggled(bool checked) { model.set_show_runge_kutta(checked); } void MainWindow::on_autoupd_checkbox_1_toggled(bool checked) { model.set_auto_update_graph(checked); } void MainWindow::on_n_0_value_changed(unsigned int value) { model.set_n_0(value); // we want to keep the n_0 value <= N unsigned int N = ui->ivalue_spinBox_5->value(); if (value > N) { ui->ivalue_spinBox_5->setValue(value); } } void MainWindow::on_N_value_changed(unsigned int value) { model.set_N(value); // we want to keep the n_0 value <= N unsigned int n_0 = ui->ivalue_spinBox_6->value(); if (n_0 > value) { ui->ivalue_spinBox_6->setValue(value); } } void MainWindow::on_x_0_value_changed(double value) { if (value == 0) { QMessageBox::critical( this, "Error!", "Division by 0: x_0 cannot be 0!"); } else { model.set_x_0(value); // we want to keep the x_0 value <= X double X = ui->ivalue_doubleSpinBox_2->value(); if (value > X) { ui->ivalue_doubleSpinBox_2->setValue(value); } } } void MainWindow::on_y_0_value_changed(double value) { model.set_y_0(value); } void MainWindow::on_X_value_changed(double value) { if (value == 0) { QMessageBox::critical( this, "Error!", "Division by 0: X cannot be 0!"); } else { model.set_X(value); // we want to keep the x_0 value <= X double x_0 = ui->ivalue_doubleSpinBox_1->value(); if (x_0 > value) { ui->ivalue_doubleSpinBox_1->setValue(value); } } } void MainWindow::on_plot_pushButton_clicked() { model.update_all_graphs(); }
[ "bragov4ik@hotmail.com" ]
bragov4ik@hotmail.com
6f5349b207ca617c63b42a8efb1092780572577f
1b608693ff8693b246287f4b7b98cfb4ad690c84
/fon9/io/FileIO.cpp
cba31be9fb7a9ba3b4e6aaafc7a25f9a0d3c0a52
[ "Apache-2.0" ]
permissive
tidesq/libfon9
7a804bcb883ed2e96271277e0cd63647b275b376
7a050db7678c54c275b80d32a057d654344ea18a
refs/heads/master
2020-04-18T23:16:58.330908
2019-01-27T03:56:45
2019-01-27T03:56:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,926
cpp
/// \file fon9/io/FileIO.cpp /// \author fonwinz@gmail.com #include "fon9/io/FileIO.hpp" #include "fon9/io/DeviceRecvEvent.hpp" #include "fon9/io/DeviceStartSend.hpp" #include "fon9/TimedFileName.hpp" namespace fon9 { namespace io { #define fon9_FileIO_TAG_OutMode "OutMode" #define fon9_FileIO_TAG_InMode "InMode" #define fon9_FileIO_TAG_InSpeed "InSpeed" #define fon9_FileIO_TAG_InEOF "InEOF" #define fon9_FileIO_DEFAULT_InSize 0 #define fon9_FileIO_DEFAULT_InInterval TimeInterval_Millisecond(1) FileIO::InProps::InProps() : ReadSize_{fon9_FileIO_DEFAULT_InSize} , Interval_{fon9_FileIO_DEFAULT_InInterval} { } bool FileIO::InProps::Parse(const StrView tag, StrView value) { if (tag == "InStart") { this->StartPos_ = StrTo(value, this->StartPos_); } else if (tag == "InSize") { this->ReadSize_ = StrTo(value, this->ReadSize_); } else if (tag == "InInterval") { this->Interval_ = StrTo(value, this->Interval_); } else if (tag == fon9_FileIO_TAG_InSpeed) { const char* pend; this->ReadSize_ = StrTo(value, this->ReadSize_, &pend); value.SetBegin(pend); StrTrimHead(&value); if ((pend = value.Find('*')) != nullptr) { value.SetBegin(pend + 1); this->Interval_ = StrTo(value, this->Interval_); } } else if (tag == fon9_FileIO_TAG_InEOF) { if (value == "Broken") this->WhenEOF_ = WhenEOF::Broken; else if (value == "Close") this->WhenEOF_ = WhenEOF::Close; else if (value == "Dispose") this->WhenEOF_ = WhenEOF::Dispose; else if (isdigit(static_cast<unsigned char>(value.Get1st()))) this->WhenEOF_ = static_cast<WhenEOF>(StrTo(value, 0u)); else this->WhenEOF_ = WhenEOF::Dontcare; } else return false; if (this->Interval_.GetOrigValue() == 0) this->Interval_ = TimeInterval_Millisecond(1); return true; } void FileIO::InProps::AppendInfo(std::string& msg) { NumOutBuf outbuf; // |InSpeed=n*ti msg.append("|" fon9_FileIO_TAG_InSpeed "="); msg.append(ToStrRev(outbuf.end(), this->ReadSize_), outbuf.end()); msg.push_back('*'); msg.append(ToStrRev(outbuf.end(), this->Interval_), outbuf.end()); // |InEOF= switch (this->WhenEOF_) { case WhenEOF::Dontcare: break; case WhenEOF::Broken: msg.append("|" fon9_FileIO_TAG_InEOF "=Broken"); break; case WhenEOF::Close: msg.append("|" fon9_FileIO_TAG_InEOF "=Close"); break; case WhenEOF::Dispose: msg.append("|" fon9_FileIO_TAG_InEOF "=Dispose"); break; default: if (static_cast<int>(this->WhenEOF_) > 0) { msg.append("|" fon9_FileIO_TAG_InEOF "="); msg.append(ToStrRev(outbuf.end(), static_cast<unsigned>(this->WhenEOF_)), outbuf.end()); } break; } } void FileIO::OpImpl_AppendDeviceInfo(std::string& info) { fon9_WARN_DISABLE_SWITCH; switch (this->OpImpl_GetState()) { case State::LinkReady: if (auto impl = this->ImplSP_.get()) { if (!impl->InFile_.IsOpened()) info.push_back(impl->OutFile_.IsOpened() ? 'O' : '?'); else { info.append(impl->OutFile_.IsOpened() ? "I+O" : "I"); RevPrintAppendTo(info, "|InCur=", impl->InCurPos_, "|InFileTime=", impl->InFile_.GetLastModifyTime(), "|InFileSize=", impl->InFile_.GetFileSize()); if (impl->InSt_ == InFileSt::AtEOF) info.append("|AtEOF"); else if (impl->InSt_ == InFileSt::ReadError) info.append("|ReadErr"); this->InProps_.AppendInfo(info); } } break; } fon9_WARN_POP; } //--------------------------------------------------------------------------// #ifndef fon9_HAVE_iovec struct iovec { void* iov_base; size_t iov_len; inline friend void fon9_PutIoVectorElement(struct iovec* piov, void* dat, size_t datsz) { piov->iov_base = dat; piov->iov_len = datsz; } }; #endif void FileIO::Impl::OnTimer(TimeStamp now) { (void)now; iovec blks[2]; size_t expsz = this->RecvSize_ > RecvBufferSize::Default ? static_cast<size_t>(this->RecvSize_) : 1024; size_t blkc = this->InBuffer_.GetRecvBlockVector(blks, expsz); size_t rdsz = 0; iovec* pblk = blks; expsz = this->Owner_->InProps_.ReadSize_; // 每次讀入資料量. while (blkc > 0) { if (expsz > 0 && pblk->iov_len > expsz) pblk->iov_len = expsz; auto rdres = this->InFile_.Read(this->InCurPos_, pblk->iov_base, pblk->iov_len); if (rdres.IsError()) { this->InSt_ = InFileSt::ReadError; break; } this->InCurPos_ += rdres.GetResult(); rdsz += rdres.GetResult(); if (expsz > 0 && (expsz -= pblk->iov_len) <= 0) break; if (rdres.GetResult() != pblk->iov_len) { this->InSt_ = InFileSt::AtEOF; break; } ++pblk; --blkc; } DcQueueList& rxbuf = this->InBuffer_.SetDataReceived(rdsz); if (rdsz <= 0) { // AtEOF or ReadError this->InBuffer_.SetContinueRecv(); this->CheckContinueRecv(); return; } struct Aux { bool IsRecvBufferAlive(Device& dev, RecvBuffer& rbuf) const { return static_cast<FileIO*>(&dev)->ImplSP_.get() == &ContainerOf(rbuf, &Impl::InBuffer_); } void ContinueRecv(RecvBuffer& rbuf, RecvBufferSize expectSize, bool isReEnableReadable) const { (void)isReEnableReadable; Impl& impl = ContainerOf(rbuf, &Impl::InBuffer_); impl.RecvSize_ = expectSize; impl.CheckContinueRecv(); } void DisableReadableEvent(RecvBuffer&) { // 只要不重啟 RunAfter(); 就不會有 Recv 事件, 所以這裡 do nothing. } SendDirectResult SendDirect(RecvDirectArgs& e, BufferList&& txbuf) { // SendDirect() 不考慮現在 impl.OutBuffer_ 的狀態? Impl& impl = ContainerOf(RecvBuffer::StaticCast(e.RecvBuffer_), &Impl::InBuffer_); DcQueueList buf{std::move(txbuf)}; impl.OutFile_.Append(buf); return SendDirectResult::Sent; } }; Aux aux; DeviceRecvBufferReady(*this->Owner_, rxbuf, aux); } void FileIO::Impl::CheckContinueRecv() { if (this->RecvSize_ < RecvBufferSize::Default || !this->InFile_.IsOpened()) return; auto ti = this->Owner_->InProps_.Interval_; switch (this->InSt_) { default: case InFileSt::Readable: break; case InFileSt::ReadError: ti = TimeInterval_Second(1); break; case InFileSt::AtEOF: switch (auto whenEOF = this->Owner_->InProps_.WhenEOF_) { default: if (static_cast<int>(whenEOF) > 0) ti = TimeInterval_Second(static_cast<int>(whenEOF)); break; case WhenEOF::Dontcare: break; case WhenEOF::Broken: case WhenEOF::Close: case WhenEOF::Dispose: fon9_WARN_DISABLE_PADDING; this->Owner_->OpQueue_.AddTask(DeviceAsyncOp{[this, whenEOF](Device& dev) { if (static_cast<FileIO*>(&dev)->ImplSP_.get() == this) { if (whenEOF == WhenEOF::Broken) OpThr_SetBrokenState(*this->Owner_, "Broken when EOF."); else if (whenEOF == WhenEOF::Close) OpThr_Close(*this->Owner_, "Close when EOF"); else // if (whenEOF == WhenEOF::Dispose) OpThr_Dispose(*this->Owner_, "Dispose when EOF"); } }}); fon9_WARN_POP; return; } break; } this->RunAfter(ti); } //--------------------------------------------------------------------------// void FileIO::OpImpl_StartRecv(RecvBufferSize preallocSize) { assert(this->ImplSP_); this->ImplSP_->RecvSize_ = preallocSize; this->ImplSP_->CheckContinueRecv(); } void FileIO::OpImpl_StopRunning() { if (auto impl = this->ImplSP_.get()) { impl->StopAndWait(); this->ImplSP_.reset(); } } void FileIO::OpImpl_Close(std::string cause) { this->OpImpl_StopRunning(); this->OpImpl_SetState(State::Closed, &cause); } void FileIO::OpImpl_Reopen() { this->OpImpl_StopRunning(); this->OpenImpl(); } void FileIO::OpImpl_Open(const std::string cfgstr) { this->OpImpl_StopRunning(); this->InFileCfg_.Mode_ = FileMode::CreatePath | FileMode::Read; this->OutFileCfg_.Mode_ = FileMode::CreatePath | FileMode::Append; StrView cfgpr{&cfgstr}; StrView tag, value; while (StrFetchTagValue(cfgpr, tag, value)) { if (tag == "InFN") this->InFileCfg_.FileName_ = value.ToString(); else if (tag == "OutFN") this->OutFileCfg_.FileName_ = value.ToString(); else if (tag == fon9_FileIO_TAG_InMode) this->InFileCfg_.Mode_ = StrToFileMode(value) | FileMode::Read; else if (tag == fon9_FileIO_TAG_OutMode) this->OutFileCfg_.Mode_ = StrToFileMode(value) | FileMode::Append; else if (!this->InProps_.Parse(tag, value)) { // Unknown tag. this->OpImpl_SetState(State::ConfigError, ToStrView(RevPrintTo<std::string>( "Unknown '", tag, '=', value, '\'' ))); return; } } std::string devid; if (!this->InFileCfg_.FileName_.empty()) devid = "I=" + this->InFileCfg_.FileName_; if (!this->OutFileCfg_.FileName_.empty()) { if (!devid.empty()) devid.push_back('|'); devid += "O=" + this->OutFileCfg_.FileName_; } OpThr_SetDeviceId(*this, std::move(devid)); this->OpImpl_SetState(State::Opening, &cfgstr); this->OpenImpl(); } File::Result FileIO::FileCfg::Open(File& fd, TimeStamp tm) const { TimedFileName fname(this->FileName_, TimedFileName::TimeScale::Day); fname.RebuildFileName(tm); return fd.Open(fname.GetFileName(), this->Mode_); } bool FileIO::OpenFile(StrView errMsgHead, const FileCfg& cfg, File& fd, TimeStamp tm) { if (cfg.FileName_.empty()) return true; auto res = cfg.Open(fd, tm); if (!res.IsError()) return true; this->OpImpl_SetState(State::LinkError, ToStrView(RevPrintTo<std::string>( "FileIO.Open.", errMsgHead, "|fn=", fd.GetOpenName(), '|', res ))); return false; } void FileIO::OpenImpl() { assert(this->ImplSP_.get() == nullptr); if (this->OutFileCfg_.FileName_.empty() && this->InFileCfg_.FileName_.empty()) { this->OpImpl_SetState(State::LinkError, "FileIO.Open|err=None IO file names."); return; } TimeStamp now = UtcNow(); ImplSP impl{new Impl{*this}}; if (this->OpenFile("OutFile", this->OutFileCfg_, impl->OutFile_, now) && this->OpenFile("InFile", this->InFileCfg_, impl->InFile_, now)) { this->ImplSP_ = std::move(impl); OpThr_SetLinkReady(*this, std::string{}); } } ConfigParser::Result FileIO::OpImpl_SetProperty(StrView tag, StrView& value) { // 有需要在 LinkReady 狀態下, 設定屬性嗎? // 透過設定修改, 然後重建 device 應該就足夠了, 所以暫時不實作此 mf. return base::OpImpl_SetProperty(tag, value); } //--------------------------------------------------------------------------// bool FileIO::IsSendBufferEmpty() const { bool res; this->OpQueue_.InplaceOrWait(AQueueTaskKind::Send, DeviceAsyncOp{[&res](Device& dev) { if (auto impl = static_cast<FileIO*>(&dev)->ImplSP_.get()) res = impl->OutBuffer_.empty(); else res = true; }}); return res; } FileIO::SendResult FileIO::SendASAP(const void* src, size_t size) { // 為了簡化, FileIO::SendASAP() 一律採用 SendBuffered(); // 因為一般而言使用 FileIO 不會有急迫性的寫入需求. return this->SendBuffered(src, size); } FileIO::SendResult FileIO::SendASAP(BufferList&& src) { return this->SendBuffered(std::move(src)); } FileIO::SendResult FileIO::SendBuffered(const void* src, size_t size) { StartSendChecker sc; if (fon9_LIKELY(sc.IsLinkReady(*this))) { assert(this->ImplSP_); AppendToBuffer(this->ImplSP_->OutBuffer_, src, size); this->ImplSP_->AsyncFlushOutBuffer(sc.GetALocker()); return Device::SendResult{0}; } return Device::SendResult{std::errc::no_link}; } FileIO::SendResult FileIO::SendBuffered(BufferList&& src) { StartSendChecker sc; if (fon9_LIKELY(sc.IsLinkReady(*this))) { assert(this->ImplSP_); this->ImplSP_->OutBuffer_.push_back(std::move(src)); this->ImplSP_->AsyncFlushOutBuffer(sc.GetALocker()); return Device::SendResult{0}; } DcQueueList dcq{std::move(src)}; dcq.ConsumeErr(std::errc::no_link); return Device::SendResult{std::errc::no_link}; } void FileIO::Impl::AsyncFlushOutBuffer(DeviceOpQueue::ALockerForInplace& alocker) { ImplSP impl{this}; alocker.AddAsyncTask(DeviceAsyncOp{[impl](Device&) { DcQueueList dcq{std::move(impl->OutBuffer_)}; impl->OutFile_.Append(dcq); }}); } } } // namespaces
[ "fonwinz@gmail.com" ]
fonwinz@gmail.com
d462b0657c7a8e05a3c70a0ec81bb0a29d74baf6
0f81552b5c88818a641197d002164fe14359ff81
/six.hpp
65f0f90e9d01d46efe4e232dad49d483a563933e
[]
no_license
clbb/WeekPractice
1496e90dc4e0e15cc21208e144d1e9d9c73e68c0
46449d66062b0f4405a1862a0540dd2cd919e3e8
refs/heads/master
2021-01-16T00:57:55.172076
2016-06-02T08:37:02
2016-06-02T08:37:15
null
0
0
null
null
null
null
GB18030
C++
false
false
8,642
hpp
#pragma once struct ListNode { int m_nKey; ListNode* m_pNext; ListNode(int val, ListNode* pNode) :m_nKey(val), m_pNext(pNode) {} }; /* 37:>两个链表公共节点 首先 获取两个链表长度,差值为x,长的先走x步;两个同时走,第一个公共节点即是 O(m+n) */ int GetLength(ListNode* pHead) { if (pHead == NULL) exit(1); int count = 0; ListNode* tmp = pHead; while (tmp) { ++count; tmp = tmp->m_pNext; } return count; } ListNode* FindCommNode(ListNode* pHead1, ListNode* pHead2) { int len1 = GetLength(pHead1); int len2 = GetLength(pHead2); int Dif = len1 - len2; ListNode* pLong = pHead1; ListNode* pShort = pHead2; if (len2 > len1) { Dif = len2 - len1; pLong = pHead2; pShort = pHead1; } for (int i = 0; i < Dif; ++i) pLong = pLong->m_pNext; while (pLong && pShort && pLong != pShort) { pLong = pLong->m_pNext; pShort = pShort->m_pNext; } ListNode* pComm = pLong; return pLong; } /* 38 :>数字在排序数组中出现的次数 {1,2,3,3,3,3,4,5} 3出现4次 遍历一遍O(n) 更优解: 归并查找第一个3,位置first;最后一个3,位置last 个数 last-first+1 O(lg^n) */ int GetNumFirstPos(int* ar, int len, int start, int end, int k); int GetNumlastPos(int* ar, int len, int start, int end, int k); int GetNumTimes(int* ar, int len, int k) { if (ar == NULL || k <= 0) return 0; int times = 0; int first = GetNumFirstPos(ar, len, 0, len - 1, k); int last = GetNumlastPos(ar, len, 0, len - 1, k); if (first > -1 && last > -1) times = last - first + 1; return times; } int GetNumFirstPos(int* ar, int len, int start, int end, int k) { if (start > end) return -1; int midPos = (end + start) / 2; int midData = ar[midPos]; if (midData == k) { if ((midPos>0 && ar[midPos - 1] != k) || midPos == 0) return midPos; else end = midPos - 1; } else if (midData > k) end = midPos - 1; else start = midPos + 1; return GetNumFirstPos(ar, len, start, end, k); } int GetNumlastPos(int* ar, int len, int start, int end, int k) { if (start > end) return -1; int midPos = (end + start) / 2; int midData = ar[midPos]; if (midData == k) { if ((midPos < len - 1 && ar[midPos + 1] != k) || midPos == len - 1) return midPos; else start = midPos + 1; } else if (midData < k) start = midPos + 1; else end = midPos - 1; return GetNumlastPos(ar, len, start, end, k); } /* 39:> 二叉树的深度 */ struct BinTree { int val; BinTree* m_pLeft; BinTree* m_pRight; }; int Depth(BinTree* pRoot) { if (pRoot == NULL) return 0; int nLeft = Depth(pRoot->m_pLeft); int nRight = Depth(pRoot->m_pRight); return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1); } /* 判断是不是平衡二叉树 (每个节点遍历一遍的解法) 即,遍历当前结点前,其左右子树已经遍历并确定了深度 */ bool IsBalanced(BinTree* pRoot, int *depth); bool IsBalanced(BinTree* pRoot) { int depth = 0; return IsBalanced(pRoot, &depth); } bool IsBalanced(BinTree* pRoot, int *depth) { if (pRoot == NULL) { *depth = 0; return true; } int left = 0; int right = 0; if (IsBalanced(pRoot->m_pLeft, &left) && IsBalanced(pRoot->m_pRight, &right)) { int dif = left - right; if (dif <= 1 || dif >= -1) { *depth = left > right ? (left + 1) : (right + 1); return true; } } return false; } /* 40:> 数组中只出现一次的数(2个)(其他都出现2次) 时间:O(n),空间O(1) 异或 {2,4,3,6,3,2,5,5} 第一次异或 即4^6->0010 用0010把数组分成两部分{2,3,6,2,3},{4,5,5} */ //获取两个出现一次数的异或结果 int _res(int ar[], int len) { int res = 0; for (int i = 0; i < len; ++i) res ^= ar[i]; return res; } void FindOnlyAppearOnce(int ar[], int len, int* num1, int* num2) { if (ar == NULL || len < 2) return; int res = _res(ar, len); int countBit = 0; while ((res & 0x1) == 0) { res >>= 1; ++countBit; } *num1 = 0; *num2 = 0; for (int i = 0; i < len; ++i) { int tmp = ar[i]; if (((tmp >>= countBit) & 1) == 1) *num1 ^= ar[i]; else *num2 ^= ar[i]; } cout << *num1 << endl; cout << *num2 << endl; } /* 41:和为s的两个数 ; 和为s的连续正整数序列 {1,2,4,7,11,15} 求和为15的两个数(头尾指针) */ bool FindTwoNumOfSum(int ar[], int len, int sum, int *num1, int *num2) { bool flag = false; if (ar == NULL || len <= 0 || num1 == NULL || num2 == NULL) return flag; int head = 0; int tail = len - 1; while (head < tail) { int curSum = ar[head] + ar[tail]; if (curSum == sum) { *num1 = ar[head]; *num2 = ar[tail]; flag = true; break; } else if (curSum>sum) tail--; else head++; } return flag; } /* 打印和为n的序列 1+2+3+4+5=4+5+6=7+8=15 打印 1~5,4~6,7~8 */ void printSeq(int small, int big) { for (int i = small; i <= big; ++i) cout << i << " "; cout << endl; } void FindSeqOfSum(int sum) { if (sum < 3) return; int small = 1; int big = 2; int times = (sum + 1) / 2; //small big两个数 只用增加到sum的一半 int curSum = small + big; while (small < times) { if (curSum == sum) printSeq(small, big); while (curSum > sum && small < times) { curSum -= small; small++; if (curSum == sum) printSeq(small, big); } big++; curSum += big; } } /* 42:> 翻转句子 ; 左旋字符串 i am student -> student am i (整体翻转,局部翻转) */ void Reserve(char* pBegin, char* pEnd) { if (pBegin == NULL || pEnd == NULL || pBegin + 1 == pEnd) return; while (pBegin < pEnd) { std::swap(*pBegin, *pEnd); pBegin++; pEnd--; } } void ReserveSentense(char* pData) { if (pData == NULL) return; char* pBegin = pData; char* pEnd = pBegin; while (*pEnd != '\0') pEnd++; pEnd--; //指向尾 Reserve(pBegin, pEnd);//整体翻转 pEnd = pBegin = pData; while (*pBegin != '\0') { if (*pBegin == ' ') { pBegin++; pEnd++; } else if (*pEnd == ' ' || *pEnd == '\0') { Reserve(pBegin, --pEnd); pBegin = ++pEnd; } else ++pEnd; } } /* 左旋单词 abcdefg ->2 -> cdefgab 分两部分 ab cdefg 整体翻转 部分翻转 */ void LeftRotateStr(char*pStr, int n) { if (pStr == NULL || n <= 0) return; int len = strlen(pStr); n %= len;//大于长度会指向非法内存 char* pFirstStart = pStr; char* pFirstEnd = pStr + n - 1; char* pSecondStart = pStr + n; char* pSecondEnd = pStr + len - 1; Reserve(pFirstStart, pFirstEnd); Reserve(pSecondStart, pSecondEnd); Reserve(pFirstStart, pSecondEnd); } /* 45:> 约瑟夫环 */ //数学解法 int LastLive(size_t total, size_t key) { if (total < 1 || key < 1) return -1; int last = 0; for (int i = 2; i <= total; ++i) last = (last + key) % i; return last; } /* 46. 1~n求和 不能使用 * / for while if else switch case 以及三目运算符 思路:利用虚函数的特性 让 n==0 和 n!=0时,有不同的调用 */ class A; A* Array[2]; class A { public: virtual size_t sum(size_t n) { return 0; } }; class B:public A { public: virtual size_t sum(size_t n) { return Array[!!n]->sum(n - 1) + n; } }; int SumRes(size_t n) { A a; B b; Array[0] = &a; Array[1] = &b; size_t res = Array[1]->sum(n); return res; } /* 47.不用 + - * / 做加法 位运算: */ int Add(int num1, int num2) { int sum, cur; do { if (num1 == 0) { num1 = num2; break; } sum = num1^num2; //异或 找出对应位置不同 cur = (num1&num2) << 1; //对应位置相同且为一,说明要进位 num1 = sum; num2 = cur; } while (num2 != 0); return num1; } /* 48.不能被继承的类 */ template<class T> class MakeSealed { friend T; //实例化后,友元身份,访问不会出错 private: MakeSealed() {}; ~MakeSealed() {}; }; class SealedClass :virtual public MakeSealed<SealedClass> //该类不能被继承 { public: SealedClass() {} ~SealedClass() {} }; class Try :public SealedClass { public: Try() {}; ~Try() {}; }; /********** 部分测试用例 ******************/ void TestAdd() { cout << Add(6, 2) << endl; } void TestLastLive() { cout <<"live is:> "<< LastLive(10, 3) << endl; } void TestReserveSentense() { //char ar[] = "i am a student"; char ar[] = " i am a student"; ReserveSentense(ar); cout << ar /*<< endl*/; } void TestLeftRotateStr() { char ar[] = "i am a student"; LeftRotateStr(ar,15); cout << ar << endl; } void TestFindSeqOfSum() { FindSeqOfSum(15); } void TestFindOnlyAppearOnce() { int ar[8] = { 2,4,3,6,3,2,5,5 }; int num1; int num2; FindOnlyAppearOnce(ar, 8,&num1,&num2); }
[ "isislau@yeah.net" ]
isislau@yeah.net
c9e72e16cb2b07eb7f85e3424cdea0c4f14d9665
d54bacc00ca32aff9012c31061795a880928472d
/arduino/PI.ino
ba0026e8d4dee3f48fe0e727a10d11fd4634968b
[]
no_license
khulqu15/RaspiUno
136f6c7e5e8c4888530aeb6054556bbacedd97e3
42e915083a4074a4e5bb5403ec6eca6a4ce85e69
refs/heads/main
2023-07-13T21:23:06.912444
2021-08-23T06:20:47
2021-08-23T06:20:47
398,994,771
0
0
null
null
null
null
UTF-8
C++
false
false
779
ino
String readData; String menuData; int integer1; int integer2; int statusLamp; int del1; int del2; int del3; int del4; const int ledPin = 12; void setup() { Serial.begin(115200); pinMode(ledPin, OUTPUT); } void loop() { String serialResponse; String items; if(Serial.available()) { serialResponse = "0x000001E9E0552BB0"; // serialResponse = Serial.readString(); for (int i = 0; i < serialResponse.length(); i++) { if (serialResponse.substring(i, i+1) == ",") { statusLamp = serialResponse.substring(0, i).toInt(); integer1 = serialResponse.substring(i+1).toInt(); if(statusLamp == 1) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } break; } } } }
[ "khusnul.ninno15@gmail.com" ]
khusnul.ninno15@gmail.com
7340060d22edbc71ca41466dbfe74c1c1ca123a1
997b43e4d5cf2c31388e1fd37a9b7a8b1c6f4c3a
/src/dependency_test.cpp
6e4353ad739496db12d42c9edc293334eac291dc
[]
no_license
JadeMatrix/stickers.moe-API
3d927100b295ce99872047ee7faa2e4086393738
c5ba58f6f2edd17763335fb0725036f6544c6f75
refs/heads/master
2018-07-03T04:22:28.944608
2018-05-31T00:19:41
2018-05-31T00:19:41
107,902,125
0
0
null
null
null
null
UTF-8
C++
false
false
2,539
cpp
#include <iostream> #include <memory> #include <string> #include "common/formatting.hpp" #include "common/hashing.hpp" #include "common/json.hpp" #include "common/postgres.hpp" #include "common/redis.hpp" //////////////////////////////////////////////////////////////////////////////// std::unique_ptr< pqxx::connection > connect( const std::string& dbname ) { return std::unique_ptr< pqxx::connection >( new pqxx::connection( "user=postgres dbname=" + dbname ) ); } int main( int argc, char* argv[] ) { if( argc < 2 ) { ff::writeln( std::cerr, "usage: ", argv[ 0 ], " <dbname>" ); return -1; } try { auto connection = connect( std::string( argv[ 1 ] ) ); pqxx::work transaction( *connection ); nlj::json test_json = { { "foo", true }, { "bar", { 1234123, "Hello World", true, 3.14 } } }; connection -> prepare( "test_query", PSQL( SELECT $1::JSONB->'bar' AS test_json; ) ); pqxx::result result = transaction.exec_prepared( "test_query", test_json.dump() ); transaction.commit(); redox::Redox redox; if( !redox.connect( "localhost", 6379 ) ) { ff::writeln( std::cerr, "could not connect to Redis server" ); return 1; } redox.set( "test_json", result[ 0 ][ "test_json" ].as< std::string >() ); test_json = nlj::json::parse( redox.get( "test_json" ) ); std::string message = test_json[ 1 ]; redox.disconnect(); ff::writeln( std::cout, message ); CryptoPP::SecByteBlock abDigest( CryptoPP::SHA256::DIGESTSIZE ); CryptoPP::SHA256().CalculateDigest( abDigest.begin(), ( byte* )message.c_str(), message.size() ); std::string message_hash; CryptoPP::HexEncoder( new CryptoPP::StringSink( message_hash ) ).Put( abDigest.begin(), abDigest.size() ); ff::writeln( std::cout, message_hash ); } catch( const std::exception &e ) { ff::writeln( std::cerr, e.what() ); return 1; } catch( ... ) { ff::writeln( std::cerr, "uncaught non-std::exception in main()" ); return 2; } return 0; }
[ "jadematrix.art@gmail.com" ]
jadematrix.art@gmail.com
c066b8ba6cc73935c660572ded2b8eff957fe18d
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_mpl_set_aux__preprocessed_plain_set20.hpp
e1204d661e7910308387b4c7b1fdb5dfa41f5f78
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
59
hpp
#include <boost/mpl/set/aux_/preprocessed/plain/set20.hpp>
[ "k@kekyo.net" ]
k@kekyo.net
5548bd14e0e9ebb34dc08b736602d0d935e760ef
c95aef9e165e2d71e59c06416244c8c2658c3c5d
/src/wallet/rpcdump.cpp
04c225b62869814b5098a11b7f3b94e12a9f0241
[ "MIT" ]
permissive
Dito24/MDClassic
327d7348dba7d9b4404b4141ca2332e92d13eb82
ce04695c3e310305f7fd9c035814d660f60b736f
refs/heads/master
2021-05-10T19:49:07.285686
2018-01-21T17:42:14
2018-01-21T17:42:14
118,166,933
0
0
null
null
null
null
UTF-8
C++
false
false
28,306
cpp
// Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Mrclassic Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "chain.h" #include "rpc/server.h" #include "init.h" #include "validation.h" #include "script/script.h" #include "script/standard.h" #include "sync.h" #include "util.h" #include "utiltime.h" #include "wallet.h" #include <fstream> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <univalue.h> #include <boost/foreach.hpp> using namespace std; void EnsureWalletIsUnlocked(); bool EnsureWalletIsAvailable(bool avoidException); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string &str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } UniValue importprivkey(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"mrclassicprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"mrclassicprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false") ); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); if (fRescan && fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode"); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return NullUniValue; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return NullUniValue; } void ImportAddress(const CBitcoinAddress& address, const string& strLabel); void ImportScript(const CScript& script, const string& strLabel, bool isRedeemScript) { if (!isRedeemScript && ::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); pwalletMain->MarkDirty(); if (!pwalletMain->HaveWatchOnly(script) && !pwalletMain->AddWatchOnly(script)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); if (isRedeemScript) { if (!pwalletMain->HaveCScript(script) && !pwalletMain->AddCScript(script)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet"); ImportAddress(CBitcoinAddress(CScriptID(script)), strLabel); } } void ImportAddress(const CBitcoinAddress& address, const string& strLabel) { CScript script = GetScriptForDestination(address.Get()); ImportScript(script, strLabel, false); // add to address book or update label if (address.IsValid()) pwalletMain->SetAddressBook(address.Get(), strLabel, "receive"); } UniValue importaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "importaddress \"address\" ( \"label\" rescan p2sh )\n" "\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nArguments:\n" "1. \"script\" (string, required) The hex-encoded script (or address)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "If you have the full public key, you should call importpublickey instead of this.\n" "\nExamples:\n" "\nImport a script with rescan\n" + HelpExampleCli("importaddress", "\"myscript\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myscript\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myscript\", \"testing\", false") ); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); if (fRescan && fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode"); // Whether to import a p2sh version, too bool fP2SH = false; if (params.size() > 3) fP2SH = params[3].get_bool(); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (address.IsValid()) { if (fP2SH) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead"); ImportAddress(address, strLabel); } else if (IsHex(params[0].get_str())) { std::vector<unsigned char> data(ParseHex(params[0].get_str())); ImportScript(CScript(data.begin(), data.end()), strLabel, fP2SH); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Mrclassic address or script"); } if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } return NullUniValue; } UniValue importpubkey(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "importpubkey \"pubkey\" ( \"label\" rescan )\n" "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nArguments:\n" "1. \"pubkey\" (string, required) The hex-encoded public key\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nImport a public key with rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false") ); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); if (fRescan && fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode"); if (!IsHex(params[0].get_str())) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string"); std::vector<unsigned char> data(ParseHex(params[0].get_str())); CPubKey pubKey(data.begin(), data.end()); if (!pubKey.IsFullyValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key"); LOCK2(cs_main, pwalletMain->cs_wallet); ImportAddress(CBitcoinAddress(pubKey.GetID()), strLabel); ImportScript(GetScriptForRawPubKey(pubKey), strLabel, false); if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } return NullUniValue; } UniValue importwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"") ); if (fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode"); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->GetBlockTime(); bool fGood = true; int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI while (file.good()) { pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100)))); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI CBlockIndex *pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return NullUniValue; } UniValue importelectrumwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "importelectrumwallet \"filename\" index\n" "\nImports keys from an Electrum wallet export file (.csv or .json)\n" "\nArguments:\n" "1. \"filename\" (string, required) The Electrum wallet export file, should be in csv or json format\n" "2. index (numeric, optional, default=0) Rescan the wallet for transactions starting from this block index\n" "\nExamples:\n" "\nImport the wallet\n" + HelpExampleCli("importelectrumwallet", "\"test.csv\"") + HelpExampleCli("importelectrumwallet", "\"test.json\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importelectrumwallet", "\"test.csv\"") + HelpExampleRpc("importelectrumwallet", "\"test.json\"") ); if (fPruneMode) throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode"); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ifstream file; std::string strFileName = params[0].get_str(); size_t nDotPos = strFileName.find_last_of("."); if(nDotPos == string::npos) throw JSONRPCError(RPC_INVALID_PARAMETER, "File has no extension, should be .json or .csv"); std::string strFileExt = strFileName.substr(nDotPos+1); if(strFileExt != "json" && strFileExt != "csv") throw JSONRPCError(RPC_INVALID_PARAMETER, "File has wrong extension, should be .json or .csv"); file.open(strFileName.c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open Electrum wallet export file"); bool fGood = true; int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI if(strFileExt == "csv") { while (file.good()) { pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100)))); std::string line; std::getline(file, line); if (line.empty() || line == "address,private_key") continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(",")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[1])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } } } else { // json char* buffer = new char [nFilesize]; file.read(buffer, nFilesize); UniValue data(UniValue::VOBJ); if(!data.read(buffer)) throw JSONRPCError(RPC_TYPE_ERROR, "Cannot parse Electrum wallet export file"); delete[] buffer; std::vector<std::string> vKeys = data.getKeys(); for (size_t i = 0; i < data.size(); i++) { pwalletMain->ShowProgress("", std::max(1, std::min(99, int(i*100/data.size())))); if(!data[vKeys[i]].isStr()) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(data[vKeys[i]].get_str())) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } } } file.close(); pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI // Whether to perform rescan after import int nStartHeight = 0; if (params.size() > 1) nStartHeight = params[1].get_int(); if (chainActive.Height() < nStartHeight) nStartHeight = chainActive.Height(); // Assume that electrum wallet was created at that block int nTimeBegin = chainActive[nStartHeight]->GetBlockTime(); if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning %i blocks\n", chainActive.Height() - nStartHeight + 1); pwalletMain->ScanForWalletTransactions(chainActive[nStartHeight], true); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return NullUniValue; } UniValue dumpprivkey(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"mrclassicaddress\"\n" "\nReveals the private key corresponding to 'mrclassicaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"mrclassicaddress\" (string, required) The mrclassic address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Mrclassic address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } UniValue dumphdinfo(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 0) throw runtime_error( "dumphdinfo\n" "Returns an object containing sensitive private info about this HD wallet.\n" "\nResult:\n" "{\n" " \"hdseed\": \"seed\", (string) The HD seed (bip32, in hex)\n" " \"mnemonic\": \"words\", (string) The mnemonic for this HD wallet (bip39, english words) \n" " \"mnemonicpassphrase\": \"passphrase\", (string) The mnemonic passphrase for this HD wallet (bip39)\n" "}\n" "\nExamples:\n" + HelpExampleCli("dumphdinfo", "") + HelpExampleRpc("dumphdinfo", "") ); LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); // add the base58check encoded extended master if the wallet uses HD CHDChain hdChainCurrent; if (pwalletMain->GetHDChain(hdChainCurrent)) { if (!pwalletMain->GetDecryptedHDChain(hdChainCurrent)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Cannot decrypt HD seed"); SecureString ssMnemonic; SecureString ssMnemonicPassphrase; hdChainCurrent.GetMnemonic(ssMnemonic, ssMnemonicPassphrase); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("hdseed", HexStr(hdChainCurrent.GetSeed()))); obj.push_back(Pair("mnemonic", ssMnemonic.c_str())); obj.push_back(Pair("mnemonicpassphrase", ssMnemonicPassphrase.c_str())); return obj; } return NullUniValue; } UniValue dumpwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Mrclassic Core %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime())); file << "\n"; // add the base58check encoded extended master if the wallet uses HD CHDChain hdChainCurrent; if (pwalletMain->GetHDChain(hdChainCurrent)) { if (!pwalletMain->GetDecryptedHDChain(hdChainCurrent)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Cannot decrypt HD chain"); SecureString ssMnemonic; SecureString ssMnemonicPassphrase; hdChainCurrent.GetMnemonic(ssMnemonic, ssMnemonicPassphrase); file << "# mnemonic: " << ssMnemonic << "\n"; file << "# mnemonic passphrase: " << ssMnemonicPassphrase << "\n\n"; SecureVector vchSeed = hdChainCurrent.GetSeed(); file << "# HD seed: " << HexStr(vchSeed) << "\n\n"; CExtKey masterKey; masterKey.SetMaster(&vchSeed[0], vchSeed.size()); CBitcoinExtKey b58extkey; b58extkey.SetKey(masterKey); file << "# extended private masterkey: " << b58extkey.ToString() << "\n"; CExtPubKey masterPubkey; masterPubkey = masterKey.Neuter(); CBitcoinExtPubKey b58extpubkey; b58extpubkey.SetKey(masterPubkey); file << "# extended public masterkey: " << b58extpubkey.ToString() << "\n\n"; for (size_t i = 0; i < hdChainCurrent.CountAccounts(); ++i) { CHDAccount acc; if(hdChainCurrent.GetAccount(i, acc)) { file << "# external chain counter: " << acc.nExternalChainCounter << "\n"; file << "# internal chain counter: " << acc.nInternalChainCounter << "\n\n"; } else { file << "# WARNING: ACCOUNT " << i << " IS MISSING!" << "\n\n"; } } } for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { file << strprintf("%s %s ", CBitcoinSecret(key).ToString(), strTime); if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("label=%s", EncodeDumpString(pwalletMain->mapAddressBook[keyid].name)); } else if (setKeyPool.count(keyid)) { file << "reserve=1"; } else { file << "change=1"; } file << strprintf(" # addr=%s%s\n", strAddr, (pwalletMain->mapHdPubKeys.count(keyid) ? " hdkeypath="+pwalletMain->mapHdPubKeys[keyid].GetKeyPath() : "")); } } file << "\n"; file << "# End of dump\n"; file.close(); return NullUniValue; }
[ "dito24@protonmail.com" ]
dito24@protonmail.com
2948813df8587824b15ed9b7d827f5c56480095f
2738a36bee52acae2e53b8617c38b2f886bf11d1
/rock/app/carmachine/video/middleWidget/videomiddlewidgetright.cpp
fac24a6692f7177e7a0bcfefa416c3fb8bd567c6
[ "MIT" ]
permissive
NovasomIndustries/Utils-2019.07
f5816ccbc61f57b478846874484460f9a6035e77
4a41062e0f50c1f97cb37df91457672ce386516d
refs/heads/master
2021-07-18T00:10:31.506640
2020-06-23T15:57:42
2020-06-23T15:57:42
182,413,350
2
0
null
null
null
null
UTF-8
C++
false
false
5,841
cpp
#include "videomiddlewidgetright.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QHeaderView> #include <QDir> #include <QTime> #include <QFileDialog> #include <QEventLoop> #include <QMediaPlayer> #include <QDirIterator> #include "player/videomediadatabase.h" #include "global_value.h" videoMiddleWidgetRight::videoMiddleWidgetRight(QWidget *parent):baseWidget(parent) { setObjectName("videoMiddleWidgetRight"); setStyleSheet("#videoMiddleWidgetRight{background:rgb(43,45,51)}"); m_playList = new videoList(this); m_curPlayingIndex = -1; initLayout(); initConnection(); } void videoMiddleWidgetRight::initLayout() { QVBoxLayout *vmianlyout = new QVBoxLayout; m_listHeader = new listHeader(this); m_listHeader->setVisible(false); m_listHeader->setFixedHeight(100); m_stackedWid = new QStackedWidget(this); m_localTable = new videoLocalListTable(m_stackedWid); m_netTable = new videoNetListTable(m_stackedWid); m_stackedWid->addWidget(m_localTable); m_stackedWid->addWidget(m_netTable); vmianlyout->addWidget(m_listHeader); vmianlyout->addWidget(m_stackedWid); vmianlyout->setContentsMargins(40,0,40,0); setLayout(vmianlyout); } void videoMiddleWidgetRight::initConnection() { connect(m_listHeader,SIGNAL(buttonLocalClick()),this,SLOT(slot_switchToLocalList())); connect(m_listHeader,SIGNAL(buttonNetClick()),this,SLOT(slot_switchToNetList())); // connect(m_localTable,SIGNAL(cellDoubleClicked(int,int)),this,SIGNAL(sig_localTableItemDoubleClick(int,int))); } void videoMiddleWidgetRight::setOriginState() { if(m_curPlayingIndex!=-1) { m_localTable->setRowTextColor(m_curPlayingIndex,QColor(255,255,255)); m_localTable->item(m_curPlayingIndex,1)->setText(""); m_curPlayingIndex = -1; m_localTable->setCurrentCell(-1,0); } } /** * @brief used to find all video file in path * @param path * @return */ QFileInfoList videoMiddleWidgetRight::findVideoFiles(const QString& path) { QFileInfoList videoFiles; QDirIterator it(path,QDir::Files|QDir::Dirs|QDir::NoDotAndDotDot); while (it.hasNext()) { QString name = it.next(); QFileInfo info(name); if (info.isDir()) { videoFiles.append(findVideoFiles(name)); } else { if (info.suffix() == "mp4" || info.suffix() == "avi" || info.suffix() == "rm" ||info.suffix() == "rmvb" || info.suffix() == "wmv" || info.suffix() == "mkv" ||info.suffix() == "mov" || info.suffix() == "asf" || info.suffix() == "ts") { videoFiles.append(info); } } } return videoFiles; } void videoMiddleWidgetRight::updateResUi(QFileInfoList fileList) { // clear list for(int i = m_localTable->rowCount();i > 0;i--) { m_localTable->removeRow(0); } m_playList->clearList(); for(int i=0;i<fileList.size();i++){ QFileInfo fileInfo = fileList.at(i); if(!m_playList->getUrlList().contains(QUrl::fromLocalFile(fileInfo.absoluteFilePath()))){ int rowCount = m_localTable->rowCount(); insertIntoLocalTable(rowCount,fileInfo.fileName()," "); m_playList->addToPlayList(fileInfo.absoluteFilePath()); } } m_curPlayingIndex = -1; } void videoMiddleWidgetRight::insertIntoLocalTable(int row, QString videoName, QString duration) { m_localTable->insertRow(row); m_localTable->setItem(row,0,new QTableWidgetItem(videoName)); m_localTable->setItem(row,1,new QTableWidgetItem(duration)); m_localTable->item(row,1)->setTextAlignment(Qt::AlignVCenter|Qt::AlignRight); } void videoMiddleWidgetRight::updatePlayingItemStyle(QMediaContent content) { QList<QUrl> urlList = m_playList->getUrlList(); // 还原上次选中的item if(m_curPlayingIndex!=-1) { m_localTable->setRowTextColor(m_curPlayingIndex,QColor(255,255,255)); m_localTable->item(m_curPlayingIndex,1)->setText(m_curPlayingDuration); m_curPlayingIndex = -1; m_localTable->setPlayingItemIndex(m_curPlayingIndex); m_localTable->setCurrentCell(-1,0); } int index = -1; for(int i=0;i < urlList.size();i++) { if(urlList.at(i)==content.canonicalUrl()){ index = i; break; } } if(index!=-1) { m_curPlayingIndex = index; m_curPlayingDuration = m_localTable->item(index,1)->text(); m_curPlayingVideoName = m_localTable->item(index,0)->text(); m_localTable->setRowTextColor(m_curPlayingIndex,QColor(26,158,255)); m_localTable->item(index,1)->setText(str_video_playing); m_localTable->setCurrentCell(index,0); m_localTable->setPlayingItemIndex(m_curPlayingIndex); } update(); } void videoMiddleWidgetRight::addVideo() { QFileDialog *dialog = new QFileDialog(mainwid,"selete file"); if(dialog->exec()==QFileDialog::Accepted) { QStringList files = dialog->selectedFiles(); if(files.isEmpty()) return; for(int i=0;i<files.count();i++) { QFileInfo info(files[i]); if(!m_playList->getUrlList().contains(QUrl::fromLocalFile(files.value(i)))&&info.exists()) { QString fileName=info.fileName(); QString filePath=files.value(i); int rowCount = m_localTable->rowCount(); insertIntoLocalTable(rowCount,fileName," "); m_playList->addToPlayList(filePath); } } } }
[ "novasomindustries@Deb9.Deb9" ]
novasomindustries@Deb9.Deb9
b468c4d94e2351d4c8517f71b3033cbf0bfe7105
5bdb7ae0b3b537c6ef81c29b0c7c561f01845ed5
/FecSoftwareV3_0/generic/include/FecAccessManager.h
b0ae3a1c303f9d8b94ceb16e124762802ad09a8e
[]
no_license
hexinglh/ph1_TriDAS
cfb2681f4e334690e915e7c921fbc28973dbeaa8
05155ada6e0ca2c04074197cf52df2f78bc6b113
refs/heads/master
2020-03-23T21:31:41.756877
2016-11-12T13:04:38
2016-11-12T13:04:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,786
h
/* This file is part of Fec Software project. Fec Software is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Fec Software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Fec Software; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Copyright 2002 - 2003, Frederic DROUHIN - Universite de Haute-Alsace, Mulhouse-France */ #ifndef FECACCESSMANAGER_H #define FECACCESSMANAGER_H #include "keyType.h" #include "apvDescription.h" #include "pllDescription.h" #include "laserdriverDescription.h" #include "muxDescription.h" #include "philipsDescription.h" #include "dcuDescription.h" #include "deviceType.h" #ifdef PRESHOWER // For CMS Preshower #include "deltaDescription.h" #include "paceDescription.h" #include "kchipDescription.h" #endif // PRESHOWER #ifdef TOTEM #include "vfatDescription.h" #include "totemCChipDescription.h" #include "totemBBDescription.h" #endif // TOTEM #include "FecAccess.h" #include "deviceAccess.h" #include "HashTable.h" /** * \class FecAccessManager * This class define and manage all the accesses. * It download all the values issued from vector<deviceDescription> into the hardware and upload it. * \version 1.0 * \author Frederic Drouhin * \date November 2002 * \warning All the hash table use a key defined in the file keyType.h: * \include keyType.h */ class FecAccessManager { protected: /** Concurrent access to the hardware via the FecAccess class */ FecAccess *fecAccess_ ; /** APV hash table. * <p>STL Map for each device based on a key build in keyType.h file. */ apvAccessedType apvSet_ ; /** PLL hash table. * <p>STL Map for each device based on a key build in keyType.h file. */ pllAccessedType pllSet_ ; /** Laserdriver hash table. * <p>STL Map for each device based on a key build in keyType.h file. */ laserdriverAccessedType laserdriverSet_ ; /** Doh hash table. * <p>STL Map for each device based on a key build in keyType.h file. */ dohAccessedType dohSet_ ; /** MUX hash table. * <p>STL Map for each device based on a key build in keyType.h file. */ muxAccessedType muxSet_ ; /** Philips hash table. * <p>STL Map for each device based on a key build in keyType.h file. * \warning This map is used to test the program. */ philipsAccessedType philipsSet_ ; /** DCU hash table. * <p>STL Map for each device based on a key build in keyType.h file. */ dcuAccessedType dcuSet_ ; /** PIA channel hash table * <p>STL Map for each channel based on a key build in keyType.h file. */ piaAccessedType piaSet_ ; #ifdef PRESHOWER /** DELTA hash table * <p>STL Map for each channel based on a key build in keyType.h file. */ deltaAccessedType deltaSet_ ; /** PACEAM hash table * <p>STL Map for each channel based on a key build in keyType.h file. */ paceAccessedType paceSet_ ; /** KCHIP hash table * <p>STL Map for each channel based on a key build in keyType.h file. */ kchipAccessedType kchipSet_ ; /** GOH hash table * <p>STL Map for each channel based on a key build in keyType.h file. */ gohAccessedType gohSet_ ; #endif // PRESHOWER #ifdef TOTEM /** VFAT hash table * <p>STL Map for each channel based on a key build in keyType.h file. */ vfatAccessedType vfatSet_ ; /** CCHIP hash table * <p>STL Map for each channel based on a key build in keyType.h file. */ cchipAccessedType cchipSet_ ; /** TBB hash table * <p>STL Map for each channel based on a key build in keyType.h file. */ tbbAccessedType tbbSet_ ; #endif // TOTEM /** Number of error during the last operation */ unsigned int lastOperationNumberErrors_ ; /** Max number of errors allowed before the download stopped * After this number the download stop */ unsigned int maxErrorAllowed_ ; /** To stop download or upload */ bool haltStateMachine_ ; /** Display or not the debug message */ bool displayDebugMessage_ ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseApv ( apvDescription apvDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parsePll ( pllDescription pllDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true, bool pllReset = false ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseMux ( muxDescription muxDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseLaserdriver ( laserdriverDescription laserdriverDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseDoh ( laserdriverDescription dohDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parsePhilips ( philipsDescription philipsDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseDcu ( dcuDescription dcuDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; #ifdef PRESHOWER /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseDelta ( deltaDescription deltaDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parsePace ( paceDescription paceDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseKchip ( kchipDescription kchipDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseGoh ( gohDescription gohDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; #endif // PRESHOWER #ifdef TOTEM /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseVfat ( vfatDescription vfatDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseCChip ( totemCChipDescription cchipDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; /** \brief Retreive the information from the DOM node of the database and * download the values into the hardware */ unsigned int parseTbb ( totemBBDescription tbbDevice, std::list<FecExceptionHandler *> &errorList, bool setIt = true ) ; #endif // TOTEM public: /** \brief Initialisation */ FecAccessManager ( FecAccess *fecAccess, bool displayDebugMessage = false ) ; /** \brief Remove all the accesses */ virtual ~FecAccessManager ( ) ; /** \brief Remove the connection for all the devices */ virtual void removeDevices ( ) ; /** \brief set the display debug message */ void setDisplayDebugMessage ( bool displayDebugMessage ) ; /** \brief return if the display debug message is on or off */ bool getDisplayDebugMessage ( ) ; /** \brief return the FEC access object */ FecAccess *getFecAccess ( ) ; /** \brief Remove the connection for one device type */ virtual void removeDevices ( enumDeviceType type ) ; /** \brief return an access from a hash table */ virtual deviceAccess *getAccess ( enumDeviceType deviceType, keyType index ) ; /** \brief return an access to the PIA reset */ PiaResetAccess *getPiaAccess ( keyType index ) ; /** \brief return all the accesses (map) */ dcuAccessedType &getDcuAccesses ( ) ; /** \brief return all the accesses (map) */ pllAccessedType &getPllAccesses ( ) ; /** \brief return all the accesses (map) */ apvAccessedType &getApvAccesses ( ) ; /** \brief return all the accesses (map) */ laserdriverAccessedType &getLaserdriverAccesses ( ) ; /** \brief return all the accesses (map) */ laserdriverAccessedType &getAOHAccesses ( ) ; /** \brief return all the accesses (map) */ dohAccessedType &getDOHAccesses ( ) ; /** \brief return all the accesses (map) */ muxAccessedType &getApvMuxAccesses ( ) ; /** \brief return all the accesses (map) */ philipsAccessedType &getPhilipsAccesses ( ) ; /** \brief return all the accesses (map) */ piaAccessedType &getPiaResetAccesses ( ) ; #ifdef PRESHOWER /** \brief return all the accesses (map) */ deltaAccessedType &getDeltaAccesses ( ) ; /** \brief return all the accesses (map) */ paceAccessedType &getPaceAccesses ( ) ; /** \brief return all the accesses (map) */ kchipAccessedType &getKchipAccesses ( ) ; /** \brief return all the accesses (map) */ gohAccessedType &getGohAccesses ( ) ; #endif // PRESHOWER #ifdef TOTEM /** \brief return all the accesses (map) */ vfatAccessedType &getVfatAccesses ( ) ; /** \brief return all the accesses (map) */ cchipAccessedType &getCchipAccesses ( ) ; /** \brief return all the accesses (map) */ tbbAccessedType &getTbbAccesses ( ) ; #endif // TOTEM /** \brief set an access into an hash table */ virtual void setAccess ( deviceAccess *access ) throw (FecExceptionHandler) ; /** \brief download the values */ virtual unsigned int downloadValues ( deviceVector *vDevice, std::list<FecExceptionHandler *> &errorList, bool pllReset = false, bool dohSet = true) throw (FecExceptionHandler) ; /** \brief calibrate the DOH (find for a specific gain the bias values) */ unsigned int calibrateDOH ( deviceVector &dohDevices, std::list<FecExceptionHandler *> &errorList, unsigned char gain = 1 ) ; /** \brief download the values into the hardware through block of frames */ virtual unsigned int downloadValuesMultipleFrames ( deviceVector *vDevice, std::list<FecExceptionHandler *> &errorList, bool pllReset = false, bool dohSet = true) throw (FecExceptionHandler) ; /** \brief Download the values only for certain APV registers on all APVs */ unsigned int downloadValuesMultipleFrames ( apvDescription apvValues, std::list<FecExceptionHandler *> &errorList, bool apvModeF = true, bool latencyF = true, bool muxGainF = true, bool ipreF = true, bool ipcascF = true, bool ipsfF = true, bool ishaF = true, bool issfF = true, bool ipspF = true, bool imuxinF = true, bool icalF = true, bool ispareF = false, bool vfpF = true, bool vfsF = true, bool vpspF = true, bool cdrvF = true, bool cselF = true, bool apvErrorF = false ) ; /** \brief Download the values for all the laserdrivers (AOH) */ unsigned int downloadValuesMultipleFrames ( laserdriverDescription laserdriverValues, std::list<FecExceptionHandler *> &errorList ) ; /** \brief Download the values for all the MUX */ unsigned int downloadValuesMultipleFrames ( muxDescription muxValues, std::list<FecExceptionHandler *> &errorList ) ; /** \brief Download the values for all the PLL */ unsigned int downloadValuesMultipleFrames ( pllDescription pllValues, std::list<FecExceptionHandler *> &errorList) ; /** \brief Download the values for all the PLL by adding a specific time */ unsigned int downloadValuesMultipleFrames ( tscType8 delay, std::list<FecExceptionHandler *> &errorList ) ; /** \brief upload all the values from the hardware */ virtual deviceVector *uploadValues ( std::list<FecExceptionHandler *> &errorList, bool comparison = false, bool dcuUpload = true, bool dohSet = true ) ; /** \brief upload all the values from the hardware through block of frames */ virtual deviceVector *uploadValuesMultipleFrames ( std::list<FecExceptionHandler *> &errorList, bool comparison = false, bool dcuUpload = true, bool dohSet = true ) ; /** \brief upload all the DCU values from the hardware */ unsigned int uploadValues ( deviceVector &dcuDevice, std::list<FecExceptionHandler *> &errorList, bool dcuHardIdOnly = false ) ; /** \brief upload all the DCU values from the hardware through block of frames */ unsigned int uploadValuesMultipleFrames ( deviceVector &dcuDevice, std::list<FecExceptionHandler *> &errorList, bool dcuHardIdOnly = false ) ; /** \brief to interrupt an operation */ void setHalt ( bool halt ) ; /** \brief return the halt state */ bool getHalt ( ) ; /** \brief set the maximum number of allowed error */ void setMaxErrorAllowed ( unsigned int maxErrorAllowed ) ; /** \brief get the maximum number of allowed error */ unsigned int getMaxErrorAllowed ( ) ; /** \brief return the number of errors during the lastoperation */ unsigned int getLastErrorLastOperation() ; /** \brief reset all modules by using PIA channel */ unsigned int resetPiaModules ( piaResetVector *vPiaReset, std::list<FecExceptionHandler *> &errorList ) throw (FecExceptionHandler) ; /** \brief reset all modules by using PIA channel */ unsigned int resetPiaModulesMultipleFrames ( piaResetVector *vPiaReset, std::list<FecExceptionHandler *> &errorList) throw (FecExceptionHandler) ; /** \brief cold reset for PLL */ unsigned int setColdPllReset ( std::list<FecExceptionHandler *> &errorList, bool multiFrames = false ) ; } ; #endif
[ "Yuta.Takahashi@cern.ch" ]
Yuta.Takahashi@cern.ch
bd1a7ac8c9eb6ce2ee5358d3d6347f22e84d9b40
c22db6c48f9f221a9aa5710bfdb4a32620d28be9
/build-Merge-Desktop_Qt_5_3_GCC_32bit-Release/moc_loginform.cpp
58bb316cd6521f148d64e1d3911db90c2e63399f
[]
no_license
allen7593/Overlapit
8040fdda5868e4433c0aa2e038205e8f2e54276c
71daab4c92d8715641b773293e74afca5ed16335
refs/heads/master
2020-06-14T16:13:12.776338
2014-11-20T09:52:06
2014-11-20T09:52:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,944
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'loginform.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Merge/loginform.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'loginform.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_LoginForm_t { QByteArrayData data[8]; char stringdata[70]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_LoginForm_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_LoginForm_t qt_meta_stringdata_LoginForm = { { QT_MOC_LITERAL(0, 0, 9), QT_MOC_LITERAL(1, 10, 9), QT_MOC_LITERAL(2, 20, 0), QT_MOC_LITERAL(3, 21, 6), QT_MOC_LITERAL(4, 28, 7), QT_MOC_LITERAL(5, 36, 13), QT_MOC_LITERAL(6, 50, 8), QT_MOC_LITERAL(7, 59, 10) }, "LoginForm\0backToPre\0\0turnOn\0turnOff\0" "resetPassword\0resetPic\0restoreSys" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_LoginForm[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 6, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 44, 2, 0x08 /* Private */, 3, 0, 45, 2, 0x08 /* Private */, 4, 0, 46, 2, 0x08 /* Private */, 5, 0, 47, 2, 0x08 /* Private */, 6, 0, 48, 2, 0x08 /* Private */, 7, 0, 49, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void LoginForm::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { LoginForm *_t = static_cast<LoginForm *>(_o); switch (_id) { case 0: _t->backToPre(); break; case 1: _t->turnOn(); break; case 2: _t->turnOff(); break; case 3: _t->resetPassword(); break; case 4: _t->resetPic(); break; case 5: _t->restoreSys(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject LoginForm::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_LoginForm.data, qt_meta_data_LoginForm, qt_static_metacall, 0, 0} }; const QMetaObject *LoginForm::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *LoginForm::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_LoginForm.stringdata)) return static_cast<void*>(const_cast< LoginForm*>(this)); return QDialog::qt_metacast(_clname); } int LoginForm::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 6) qt_static_metacall(this, _c, _id, _a); _id -= 6; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 6) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 6; } return _id; } QT_END_MOC_NAMESPACE
[ "=" ]
=
d6f1bb5625ad0300475b11dd50458bd71bdb110a
f5f750efbde0ccd95856820c975ec88ee6ace0f8
/aws-cpp-sdk-iam/include/aws/iam/model/UpdateAssumeRolePolicyRequest.h
6b49231867f75e08397cae7e4b43db28ae300807
[ "JSON", "MIT", "Apache-2.0" ]
permissive
csimmons0/aws-sdk-cpp
578a4ae6e7899944f8850dc37accba5568b919eb
1d0e1ddb51022a02700a9d1d3658abf628bb41c8
refs/heads/develop
2020-06-17T14:58:41.406919
2017-04-12T03:45:33
2017-04-12T03:45:33
74,995,798
0
0
null
2017-03-02T05:35:49
2016-11-28T17:12:34
C++
UTF-8
C++
false
false
9,560
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/iam/IAM_EXPORTS.h> #include <aws/iam/IAMRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace IAM { namespace Model { /** */ class AWS_IAM_API UpdateAssumeRolePolicyRequest : public IAMRequest { public: UpdateAssumeRolePolicyRequest(); Aws::String SerializePayload() const override; protected: void DumpBodyToUrl(Aws::Http::URI& uri ) const override; public: /** * <p>The name of the role to update with the new policy.</p> <p>This parameter * allows (per its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a * string of characters consisting of upper and lowercase alphanumeric characters * with no spaces. You can also include any of the following characters: =,.@-</p> */ inline const Aws::String& GetRoleName() const{ return m_roleName; } /** * <p>The name of the role to update with the new policy.</p> <p>This parameter * allows (per its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a * string of characters consisting of upper and lowercase alphanumeric characters * with no spaces. You can also include any of the following characters: =,.@-</p> */ inline void SetRoleName(const Aws::String& value) { m_roleNameHasBeenSet = true; m_roleName = value; } /** * <p>The name of the role to update with the new policy.</p> <p>This parameter * allows (per its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a * string of characters consisting of upper and lowercase alphanumeric characters * with no spaces. You can also include any of the following characters: =,.@-</p> */ inline void SetRoleName(Aws::String&& value) { m_roleNameHasBeenSet = true; m_roleName = value; } /** * <p>The name of the role to update with the new policy.</p> <p>This parameter * allows (per its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a * string of characters consisting of upper and lowercase alphanumeric characters * with no spaces. You can also include any of the following characters: =,.@-</p> */ inline void SetRoleName(const char* value) { m_roleNameHasBeenSet = true; m_roleName.assign(value); } /** * <p>The name of the role to update with the new policy.</p> <p>This parameter * allows (per its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a * string of characters consisting of upper and lowercase alphanumeric characters * with no spaces. You can also include any of the following characters: =,.@-</p> */ inline UpdateAssumeRolePolicyRequest& WithRoleName(const Aws::String& value) { SetRoleName(value); return *this;} /** * <p>The name of the role to update with the new policy.</p> <p>This parameter * allows (per its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a * string of characters consisting of upper and lowercase alphanumeric characters * with no spaces. You can also include any of the following characters: =,.@-</p> */ inline UpdateAssumeRolePolicyRequest& WithRoleName(Aws::String&& value) { SetRoleName(value); return *this;} /** * <p>The name of the role to update with the new policy.</p> <p>This parameter * allows (per its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a * string of characters consisting of upper and lowercase alphanumeric characters * with no spaces. You can also include any of the following characters: =,.@-</p> */ inline UpdateAssumeRolePolicyRequest& WithRoleName(const char* value) { SetRoleName(value); return *this;} /** * <p>The policy that grants an entity permission to assume the role.</p> <p>The <a * href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this * parameter is a string of characters consisting of any printable ASCII character * ranging from the space character (\u0020) through end of the ASCII character * range as well as the printable characters in the Basic Latin and Latin-1 * Supplement character set (through \u00FF). It also includes the special * characters tab (\u0009), line feed (\u000A), and carriage return (\u000D).</p> */ inline const Aws::String& GetPolicyDocument() const{ return m_policyDocument; } /** * <p>The policy that grants an entity permission to assume the role.</p> <p>The <a * href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this * parameter is a string of characters consisting of any printable ASCII character * ranging from the space character (\u0020) through end of the ASCII character * range as well as the printable characters in the Basic Latin and Latin-1 * Supplement character set (through \u00FF). It also includes the special * characters tab (\u0009), line feed (\u000A), and carriage return (\u000D).</p> */ inline void SetPolicyDocument(const Aws::String& value) { m_policyDocumentHasBeenSet = true; m_policyDocument = value; } /** * <p>The policy that grants an entity permission to assume the role.</p> <p>The <a * href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this * parameter is a string of characters consisting of any printable ASCII character * ranging from the space character (\u0020) through end of the ASCII character * range as well as the printable characters in the Basic Latin and Latin-1 * Supplement character set (through \u00FF). It also includes the special * characters tab (\u0009), line feed (\u000A), and carriage return (\u000D).</p> */ inline void SetPolicyDocument(Aws::String&& value) { m_policyDocumentHasBeenSet = true; m_policyDocument = value; } /** * <p>The policy that grants an entity permission to assume the role.</p> <p>The <a * href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this * parameter is a string of characters consisting of any printable ASCII character * ranging from the space character (\u0020) through end of the ASCII character * range as well as the printable characters in the Basic Latin and Latin-1 * Supplement character set (through \u00FF). It also includes the special * characters tab (\u0009), line feed (\u000A), and carriage return (\u000D).</p> */ inline void SetPolicyDocument(const char* value) { m_policyDocumentHasBeenSet = true; m_policyDocument.assign(value); } /** * <p>The policy that grants an entity permission to assume the role.</p> <p>The <a * href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this * parameter is a string of characters consisting of any printable ASCII character * ranging from the space character (\u0020) through end of the ASCII character * range as well as the printable characters in the Basic Latin and Latin-1 * Supplement character set (through \u00FF). It also includes the special * characters tab (\u0009), line feed (\u000A), and carriage return (\u000D).</p> */ inline UpdateAssumeRolePolicyRequest& WithPolicyDocument(const Aws::String& value) { SetPolicyDocument(value); return *this;} /** * <p>The policy that grants an entity permission to assume the role.</p> <p>The <a * href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this * parameter is a string of characters consisting of any printable ASCII character * ranging from the space character (\u0020) through end of the ASCII character * range as well as the printable characters in the Basic Latin and Latin-1 * Supplement character set (through \u00FF). It also includes the special * characters tab (\u0009), line feed (\u000A), and carriage return (\u000D).</p> */ inline UpdateAssumeRolePolicyRequest& WithPolicyDocument(Aws::String&& value) { SetPolicyDocument(value); return *this;} /** * <p>The policy that grants an entity permission to assume the role.</p> <p>The <a * href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this * parameter is a string of characters consisting of any printable ASCII character * ranging from the space character (\u0020) through end of the ASCII character * range as well as the printable characters in the Basic Latin and Latin-1 * Supplement character set (through \u00FF). It also includes the special * characters tab (\u0009), line feed (\u000A), and carriage return (\u000D).</p> */ inline UpdateAssumeRolePolicyRequest& WithPolicyDocument(const char* value) { SetPolicyDocument(value); return *this;} private: Aws::String m_roleName; bool m_roleNameHasBeenSet; Aws::String m_policyDocument; bool m_policyDocumentHasBeenSet; }; } // namespace Model } // namespace IAM } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
312cb7f5ddb6be032c9a5974e0725ffdbc2d6ddd
4bc6b8754cb0968cd4706ed40f41dcf389f873cf
/Graph/DFS/657 - The die is cast.cpp
6b10c78aefef30a1ace390bbfa162a61bf067b7f
[]
no_license
nikhilyadv/UVA
cf0a7d304ffbed96c0a87c25275a7835ab5c6c86
2a762ebffe7de088e957b77c1e10b6cc038cd960
refs/heads/master
2021-04-29T13:44:07.583507
2019-02-10T17:38:41
2019-02-10T17:38:41
121,758,739
0
0
null
null
null
null
UTF-8
C++
false
false
1,840
cpp
#include<bits/stdc++.h> using namespace std; typedef vector<int> vi; int n , m , ans; vector <string> a; int dr[] = {-1,0,1,0}; int dc[] = {0,1,0,-1}; void floodfill1(int r , int c , char ch1, char ch2){ if( r<0 || r>=n || c>=m || c<0) return ; if(a[r][c] != ch1) return ; a[r][c] = ch2; for(int k = 0 ; k < 4 ; k++) floodfill1(r + dr[k] , c + dc[k] , ch1 , ch2); } int floodfill(int r , int c , char ch1, char ch2 ){ if( r<0 || r>=n || c>=m || c<0) return 0; if(a[r][c] == '.') return 0; if(a[r][c] == 'X'){ floodfill1(r, c, 'X', '*'); ans++; } a[r][c] = ch2; for(int k = 0 ; k < 4 ; k++) floodfill(r + dr[k] , c + dc[k] , ch1 , ch2); return 0; } int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt" , "r" , stdin); freopen("out.txt" , "w" , stdout); int count = 1; while(cin>>m>>n , n && m){ a.resize(n); vi answer; for(int i = 0 ; i < n ; i++) cin>>a[i]; for(int i = 0 ; i < n ; i++){ for(int j = 0 ; j < m ; j++){ ans = 0; if(a[i][j] == '*') { floodfill(i, j, '*', '.'); answer.push_back(ans); } } } for(int i = 0 ; i < n ; i++){ for(int j = 0 ; j < m ; j++){ ans = 0; if(a[i][j] == 'X'){ floodfill1(i, j, 'X', '.'); answer.push_back(1); } } } sort(answer.begin() , answer.end()); cout<<"Throw "<<count++<<"\n"; for(int i = 0 ; i < answer.size() - 1 ; i++) cout << answer[i] <<" "; cout << answer[answer.size() - 1]; cout << "\n\n"; } return 0; }
[ "nikhilk.yadav22@gmail.com" ]
nikhilk.yadav22@gmail.com
78374bac86ac6a072d39b41efd9b41a8273e94d8
e09e3b8efb0c58d8cbb3f3e8a19e886c5fad3da2
/Engine/src/Bindables/IndexBuffer.h
c937fba8512f7237dcd8c3b5268d978680ba92dc
[]
no_license
Mihajlo05/mihajlo-engine-3d
87de63d206e93f02879774333be543f4f83feb02
45a9c5fb05442f84732b7eb9e51733ae7833468a
refs/heads/master
2023-06-28T11:10:40.355085
2021-08-03T06:42:07
2021-08-03T06:42:07
369,467,905
0
0
null
2021-07-29T11:30:47
2021-05-21T08:30:21
C++
UTF-8
C++
false
false
1,009
h
#pragma once #include "Graphics/Graphics.h" #include <vector> #include "Bindable.h" #include "Math/Index.h" namespace Binds { class IndexBuffer : public Bindable { public: IndexBuffer(Graphics& gfx, const std::string& tag, const std::vector<Index>& indices); void Bind(Graphics& gfx) const override; uint32_t GetCount() const; static std::shared_ptr<IndexBuffer> Resolve(Graphics& gfx, const std::string& tag, const std::vector<Index>& indices) { return Codex::Resolve<IndexBuffer>(gfx, tag, indices); } template<typename... Ignore> static std::string GenerateUID(const std::string& tag, Ignore&&... ignore) { return _GenerateUID(tag); } std::string GetUID() const override { return GenerateUID(tag); } private: static std::string _GenerateUID(const std::string& tag) { using namespace std::string_literals; return typeid(IndexBuffer).name() + "#"s + tag; } private: std::string tag; Microsoft::WRL::ComPtr<ID3D11Buffer> pData; uint32_t count; }; }
[ "mihajlosrec12@gmail.com" ]
mihajlosrec12@gmail.com
6f29e10867a8585f0fd5d74467531a4c90b22f76
a9c8428848bdb60374d187b7d437efc0372a951e
/nnacs/dplantid/dplantid.cpp
642578e6f18928c67fe99f8735c6959986c551ed
[]
no_license
evlad/phdworks
17d26d412d10b2559287060aa5fc51dd400c28df
daa8420ffd334a409fcf0cab06610924de3624a3
refs/heads/master
2021-01-19T08:50:22.849306
2013-05-19T20:53:57
2013-05-19T20:53:57
12,561,787
1
0
null
null
null
null
UTF-8
C++
false
false
11,942
cpp
/* dplantid.cpp */ static char rcsid[] = "$Id$"; #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> //#include <unistd.h> #include <NaLogFil.h> #include <NaGenerl.h> #include <NaExcept.h> #include <NaConfig.h> #include <NaTrFunc.h> #include <NaDataIO.h> #include <NaParams.h> #include <kbdif.h> #include "NaNNRPL.h" /*********************************************************************** * Train neural net plant identification model. ***********************************************************************/ int main (int argc, char* argv[]) { if(argc < 2) { fprintf(stderr, "Usage: dplantid ParamFile [Extra name=value pairs]\n"); return 1; } try{ NaParams par(argv[1], argc - 2, argv + 2); NaPrintLog("Run dplantid with %s\n", argv[1]); par.ListOfParamsToLog(); // Read neural network from file NaNNUnit au_nn; au_nn.Load(par("in_nnp_file")); // Additional log files NaDataFile *nnllog = OpenOutputDataFile(par("trace_file"), bdtAuto, 8); nnllog->SetTitle("NN regression plant learning"); nnllog->SetVarName(0, "Mean"); nnllog->SetVarName(1, "StdDev"); nnllog->SetVarName(2, "MSE"); NaNNRegrPlantLearn nnrol(NaTrainingAlgorithm, "nnpl"); NaNNRegrPlantLearn nnroe(NaEvaluationAlgorithm, "nnpe"); // Configure nodes unsigned *input_delays = au_nn.descr.InputDelays(); unsigned *output_delays = au_nn.descr.OutputDelays(); int nLearn, nList_in_u, nList_in_y, nList_nn_y, nList_tr_y; char **szList_in_u = par("in_u", nList_in_u); char **szList_in_y = par("in_y", nList_in_y); char **szList_nn_y = par("nn_y", nList_nn_y); char **szList_tr_y = par("tr_y", nList_tr_y); /* nLearn=MIN4(a,b,c,d) */ nLearn = nList_in_u; if(nLearn > nList_in_y) nLearn = nList_in_y; if(nLearn > nList_nn_y) nLearn = nList_nn_y; if(nLearn > nList_tr_y) nLearn = nList_tr_y; NaPrintLog("Total %d learning data files\n", nLearn); int nTest, nList_test_in_u, nList_test_in_y, nList_test_nn_y, nList_test_tr_y; char **szList_test_in_u = par("test_in_u", nList_test_in_u); char **szList_test_in_y = par("test_in_y", nList_test_in_y); char **szList_test_nn_y = par("test_nn_y", nList_test_nn_y); char **szList_test_tr_y = par("test_tr_y", nList_test_tr_y); /* nTest=MIN4(a,b,c,d) */ nTest = nList_test_in_u; if(nTest > nList_test_in_y) nTest = nList_test_in_y; if(nTest > nList_test_nn_y) nTest = nList_test_nn_y; if(nTest > nList_test_tr_y) nTest = nList_test_tr_y; NaPrintLog("Total %d testing data files\n", nTest); nnrol.nnplant.set_transfer_func(&au_nn); nnrol.nnteacher.set_nn(&nnrol.nnplant); nnrol.delay_u.set_delay(au_nn.descr.nInputsRepeat, input_delays); nnrol.delay_y.set_delay(au_nn.descr.nOutputsRepeat, output_delays); unsigned iDelay_u = nnrol.delay_u.get_max_delay(); unsigned iDelay_y = nnrol.delay_y.get_max_delay(); unsigned iSkip_u = 0, iSkip_y = 0; unsigned iDelay_yt, iSkip_yt; // Skip u or y due to absent earlier values of y or u if(iDelay_y >= iDelay_u) { iSkip_u = iDelay_y - iDelay_u + 1; } else /* if(iDelay_u > iDelay_y) */ { iSkip_y = iDelay_u - iDelay_y - 1; } iDelay_yt = iDelay_y + iSkip_y; iSkip_yt = 1 + iDelay_yt; nnrol.skip_u.set_skip_number(iSkip_u); nnroe.skip_u.set_skip_number(iSkip_u); nnrol.skip_y.set_skip_number(iSkip_y); nnroe.skip_y.set_skip_number(iSkip_y); // Additional delay for target value nnrol.skip_yt.set_skip_number(iSkip_yt); nnrol.delay_yt.set_delay(0); nnrol.delay_yt.add_delay(iDelay_yt); nnroe.skip_yt.set_skip_number(iSkip_yt); nnroe.delay_yt.set_delay(0); nnroe.delay_yt.add_delay(iDelay_yt); nnroe.nnplant.set_transfer_func(&au_nn); nnroe.delay_u.set_delay(au_nn.descr.nInputsRepeat, input_delays); nnroe.delay_y.set_delay(au_nn.descr.nOutputsRepeat, output_delays); NaPrintLog("delay_u=%d, skip_u=%d\n", iDelay_u, iSkip_u); NaPrintLog("delay_y=%d, skip_y=%d\n", iDelay_y, iSkip_y); NaPrintLog("delay_yt=%d, skip_yt=%d\n", iDelay_yt, iSkip_yt); // Duplicate input y series at the same time ticks as nn_y nnrol.fetch_y.set_output(0); nnroe.fetch_y.set_output(0); // Configure learning parameters nnrol.nnteacher.lpar.eta = atof(par("eta")); nnrol.nnteacher.lpar.eta_output = atof(par("eta_output")); nnrol.nnteacher.lpar.alpha = atof(par("alpha")); // Number of successful descending MSE to make faster learning // rate (=0 means off) int nAccelHits = atoi(par("accel_hits")); float fMaxEta = atof(par("eta")); if(nAccelHits > 0) NaPrintLog("when learning will succeed for %d epochs" \ " eta will be enlarged\n", nAccelHits); //ask_user_lpar(nnrol.nnteacher.lpar); //putchar('\n'); // Teach the network iteratively NaPNEvent pnev, pnev_test; int iIter = 0, iEpoch = 0, iData, nHits = 0; #if defined(__MSDOS__) || defined(__WIN32__) printf("Press 'q' or 'x' for exit\n"); #endif /* DOS & Win */ //au_nn.Initialize(); NaReal fNormMSE, fNormTestMSE; NaReal fPrevMSE = 0.0, fLastMSE = 0.0; NaReal fPrevTestMSE = 0.0; int nGrowingMSE = 0; NaNNUnit rPrevNN(au_nn); bool bTeach, bTeachLinkage = false, bTestLinkage = false; /* number of epochs when MSE on test set grows to finish the learning */ int nFinishOnGrowMSE = atoi(par("finish_on_grow")); /* number of epochs to stop learning anyway */ int nFinishOnMaxEpoch = atoi(par("finish_max_epoch")); /* absolute value of MSE to stop learning if reached */ NaReal fFinishOnReachMSE = atof(par("finish_on_value")); // Time chart //nnrol.net.time_chart(true); do{ ++iIter; // teach pass for(iData = 0; iData < nLearn; ++iData) { NaPrintLog("*** Teach pass: '%s' '%s' '%s' '%s' ***\n", szList_in_u[iData], szList_in_y[iData], szList_tr_y[iData], szList_nn_y[iData]); nnrol.in_u.set_input_filename(szList_in_u[iData]); nnrol.in_y.set_input_filename(szList_in_y[iData]); nnrol.nn_y.set_output_filename(szList_nn_y[iData]); nnrol.tr_y.set_output_filename(szList_tr_y[iData]); if(!bTeachLinkage) { nnrol.link_net(); bTeachLinkage = true; } pnev = nnrol.run_net(); if(pneError == pnev || pneTerminate == pnev) break; } if(pneError == pnev || pneTerminate == pnev) break; NaPrintLog("*** Teach passed ***\n"); nnrol.statan.print_stat(); fNormMSE = nnrol.statan.RMS[0] / nnrol.statan_y.RMS[0]; printf("Iteration %-4d, MSE=%g (%g)", iIter, nnrol.statan.RMS[0], fNormMSE); if(1 == iIter) { fLastMSE = fPrevMSE = fNormMSE; rPrevNN = au_nn; nnrol.nnteacher.update_nn(); printf(" -> teach NN\n"); fflush(stdout); bTeach = true; } else { /* next passes */ if(fLastMSE < fNormMSE) { /* growing MSE on learning set */ nnrol.nnteacher.lpar.eta /= 2; nnrol.nnteacher.lpar.eta_output /= 2; nnrol.nnteacher.lpar.alpha /= 2; nHits = 0; NaPrintLog("Learning parameters: "\ "lrate=%g lrate(out)=%g momentum=%g\n", nnrol.nnteacher.lpar.eta, nnrol.nnteacher.lpar.eta_output, nnrol.nnteacher.lpar.alpha); au_nn = rPrevNN; fLastMSE = fNormMSE; nnrol.nnplant.set_transfer_func(&au_nn); nnrol.nnteacher.reset_training(); printf(" -> repeat with (%g, %g, %g)\n", nnrol.nnteacher.lpar.eta, nnrol.nnteacher.lpar.eta_output, nnrol.nnteacher.lpar.alpha); fflush(stdout); bTeach = false; } else { /* MSE became less */ fLastMSE = fPrevMSE = fNormMSE; rPrevNN = au_nn; nnrol.nnteacher.update_nn(); bTeach = true; /* Try to accelerate learning */ ++nHits; if(nAccelHits > 0 && nHits >= nAccelHits && nnrol.nnteacher.lpar.eta < fMaxEta) { nnrol.nnteacher.lpar.eta *= 1.5; nnrol.nnteacher.lpar.eta_output *= 1.5; nnrol.nnteacher.lpar.alpha *= 1.5; nHits = 0; NaPrintLog("Learning parameters: " \ "lrate=%g lrate(out)=%g momentum=%g\n", nnrol.nnteacher.lpar.eta, nnrol.nnteacher.lpar.eta_output, nnrol.nnteacher.lpar.alpha); printf(" -> teach NN and continue with (%g, %g, %g)\n", nnrol.nnteacher.lpar.eta, nnrol.nnteacher.lpar.eta_output, nnrol.nnteacher.lpar.alpha); fflush(stdout); } else { printf(" -> teach NN\n"); fflush(stdout); } } } if(bTeach) { ++iEpoch; nnllog->AppendRecord(); nnllog->SetValue(nnrol.statan.Mean[0], 0); nnllog->SetValue(nnrol.statan.StdDev[0], 1); nnllog->SetValue(nnrol.statan.RMS[0], 2); // test pass for(iData = 0; iData < nTest; ++iData) { NaPrintLog("*** Test pass: '%s' '%s' '%s' '%s' ***\n", szList_test_in_u[iData], szList_test_in_y[iData], szList_test_tr_y[iData], szList_test_nn_y[iData]); nnroe.in_u.set_input_filename(szList_test_in_u[iData]); nnroe.in_y.set_input_filename(szList_test_in_y[iData]); nnroe.nn_y.set_output_filename(szList_test_nn_y[iData]); nnroe.tr_y.set_output_filename(szList_test_tr_y[iData]); if(!bTestLinkage) { nnroe.link_net(); bTestLinkage = true; } pnev_test = nnroe.run_net(); if(pneError == pnev_test || pneTerminate == pnev_test) break; } if(pneError == pnev_test || pneTerminate == pnev_test) break; fNormTestMSE = nnroe.statan.RMS[0] / nnroe.statan_y.RMS[0]; printf(" Test: MSE=%g (%g)", nnroe.statan.RMS[0], nnroe.statan.RMS[0] / nnroe.statan_y.RMS[0]); NaPrintLog("*** Test passed ***\n"); nnroe.statan.print_stat(); nnllog->SetValue(nnroe.statan.Mean[0], 3); nnllog->SetValue(nnroe.statan.StdDev[0], 4); nnllog->SetValue(nnroe.statan.RMS[0], 5); nnllog->SetValue(fNormMSE, 6); nnllog->SetValue(fNormTestMSE, 7); if(fNormTestMSE < fFinishOnReachMSE) { NaPrintLog("Test MSE reached preset value %g -> stop\n", fFinishOnReachMSE); printf(" -> reached preset value %g -> stop\n", fFinishOnReachMSE); fflush(stdout); break; } if(fPrevTestMSE < fNormTestMSE) { /* Start growing */ ++nGrowingMSE; if(nGrowingMSE > nFinishOnGrowMSE && nFinishOnGrowMSE > 0) { NaPrintLog("Test MSE was growing for %d epoch -> stop\n", nFinishOnGrowMSE); printf(" -> grew for %d epochs -> stop\n", nFinishOnGrowMSE); fflush(stdout); break; } printf(" -> grows\n", nFinishOnGrowMSE); fflush(stdout); } else { /* Reset counter */ nGrowingMSE = 0; printf(" -> descents\n"); fflush(stdout); } if(nFinishOnMaxEpoch != 0 && iEpoch >= nFinishOnMaxEpoch) { NaPrintLog("Max number of epoch %d is reached -> stop\n", nFinishOnMaxEpoch); printf(" %d epochs is over -> stop\n", nFinishOnMaxEpoch); fflush(stdout); break; } fPrevTestMSE = fNormTestMSE; } }while(pneDead == pnev); NaPrintLog("IMPORTANT: net is dead due to "); switch(pnev){ case pneTerminate: NaPrintLog("user break.\n"); break; case pneHalted: NaPrintLog("internal halt.\n"); break; case pneDead: NaPrintLog("data are exhausted.\n"); break; case pneError: NaPrintLog("some error occured.\n"); break; default: NaPrintLog("unknown reason.\n"); break; } delete nnllog; au_nn.Save(par("out_nnp_file")); } catch(NaException& ex){ NaPrintLog("EXCEPTION: %s\n", NaExceptionMsg(ex)); fprintf(stderr, "EXCEPTION: %s\n", NaExceptionMsg(ex)); } return 0; }
[ "ev1ad@yandex.ru" ]
ev1ad@yandex.ru
0e30c543c893b0d80ad581f00fb4772f2ee184e8
c0d556febf976aa295692c961e56ebcb09f6953e
/Bots.Native/BotTaskStatus.h
42024feacf2ec7fec17189118c059e28c73f9806
[]
no_license
GerryFranco/Bot-Manager
a29c566f7a23b51542907261ab3c169257ea18ef
e744e3dd802c91f699d8247e9b485b7aedb8a694
refs/heads/master
2020-08-06T11:40:37.972146
2019-11-13T06:40:26
2019-11-13T06:40:26
212,962,696
1
0
null
null
null
null
UTF-8
C++
false
false
241
h
//BotTaskStatus.h - Defines a native bot task status. #pragma once #ifndef BOTSNATIVE_BOTTASKSTATUS_H #define BOTSNATIVE_BOTTASKSTATUS_H TRUE namespace BotsNative { enum class BotTaskStatus { Started = 0, Completed = 1 }; } #endif
[ "gfrancojr@knights.ucf.edu" ]
gfrancojr@knights.ucf.edu
0d598980a5385a81d223e181bddfcff1ce1e709b
6e2790210b3f07bfd38a0c03476cfdddbd0ddd92
/leetcode109.cpp
e17afdf44198c6e5b607f06aaa873a1bbabe11bf
[]
no_license
VictorCPH/Leetcode-practice
3dbf301bd2b6a55995f497f03907f7da4c407c6e
0d044a5a214d98c5fcc9f02697da9a3ae94e05ae
refs/heads/master
2021-01-10T15:22:26.871958
2016-03-25T17:03:48
2016-03-25T17:03:48
54,078,787
0
0
null
null
null
null
GB18030
C++
false
false
1,097
cpp
// leetcode109.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; /** * Definition for a binary tree node. */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode* sortedListToBST(ListNode* head) { if (!head) return NULL; ListNode* preMid = NULL; ListNode* mid = head; ListNode* doubleMid = head; while (doubleMid->next && doubleMid->next->next) { preMid = mid; mid = mid->next; doubleMid = doubleMid->next->next; } TreeNode* root = new TreeNode(mid->val); TreeNode* left; if (preMid == NULL) left = NULL; else { preMid->next = NULL; left = sortedListToBST(head); } TreeNode* right = sortedListToBST(mid->next); root->left = left; root->right = right; return root; } }; int main() { system("pause"); return 0; }
[ "867118422@qq.com" ]
867118422@qq.com
00346e27290286f2a4fd03056747fa63c3ba8de6
b2f61fff84645f3dac70c0878cf524f453bff18e
/TestGame/WhiteFigure.h
b8611354800c61c72a4e2547e62eb7b6581314eb
[]
no_license
AFoki/TestGame
b0ef1d8aaad541d4367a7c340db3a6c36ebf8815
719ae17f5126cdfb37ba646ef99588b17e0a96fd
refs/heads/master
2023-07-20T09:36:34.240105
2021-08-22T15:15:48
2021-08-22T15:15:48
394,410,524
0
0
null
null
null
null
UTF-8
C++
false
false
149
h
#pragma once #include "Figure.h" class WhiteFigure : public Figure { public: WhiteFigure(Texture& NewTexture); ~WhiteFigure() override; };
[ "afokipig@gmail.com" ]
afokipig@gmail.com
074cfc3d70c98ec20b55060994c159976720b92d
ec1b8e17446bd67c18369391a57d9d5abab36453
/Interceptor/CallGraphRecorder/CallStackRecord.h
af199492a653416e8026ddc7b6cb5691fa56dbbe
[ "MIT" ]
permissive
19317362/Interceptor
72a19fbf404f364a0d7a6742f384a54e15ba9c91
a64e8283454cd70b6e16161c322dc4d85663caa9
refs/heads/master
2020-04-04T00:15:18.515027
2018-11-08T06:52:15
2018-11-08T06:52:15
155,646,261
0
0
MIT
2018-11-01T01:43:49
2018-11-01T01:43:48
null
UTF-8
C++
false
false
1,522
h
#pragma once #include "InterceptorConfig.h" #include "StringIndexer.h" #include <string> #include <thread> #include <vector> namespace Interceptor { enum class CALL_STATUS { CALL_IN, CALL_OUT }; class CallStackRecord { string_id m_function; string_id m_function_file_data; CALL_STATUS m_call_status; public: CallStackRecord(const string_id &_function_name, const string_id &_function_file_path, CALL_STATUS _call_status = CALL_STATUS::CALL_IN); bool operator ==(const CallStackRecord &_record)const; bool fn_equal(const CallStackRecord &_record)const; string_id get_function_name()const; string_id get_file_data()const; CALL_STATUS get_call_status()const; }; // maps of thread id to the collection of calls stack records // if the call is Fn in ->Fn Out -> Fn in ->Fn out pattern then the count(second parameter in the pair // is incremented typedef std::map<std::thread::id, std::vector<std::pair<CallStackRecord, std::size_t> > > CallStackPerThread; //CALL_GRAPH : map of string id of function name to all the functions it calls and the count typedef std::map<string_id, std::map<string_id, std::size_t> > CALL_GRAPH; class CallStackUtils { public: static void get_call_chart(const std::vector<std::pair<CallStackRecord, std::size_t> > &_call_stack, CALL_GRAPH &_call_graph, const RecordType &_mode); static void check_call_stack(const std::vector<std::pair<CallStackRecord, std::size_t> > &_call_stack); }; }
[ "prakaramjoshi@gmail.com" ]
prakaramjoshi@gmail.com
189bc1405ef49e2354f0f739c4693f3b768ed0bb
b708b0b4cc1e345560a90c52865f16c139b9cfff
/src/mathtool/Basic.h
8e4d903f826aacb7c1bc464883abdb8978da4048
[ "MIT" ]
permissive
xinyut/lightbender
f591974ebd309e67a3a61f3b2d752091cd5687e3
510f1971614930e2d75911d23a97b1ba77426074
refs/heads/main
2023-04-14T12:28:30.976112
2021-04-14T13:45:43
2021-04-14T13:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,816
h
//------------------------------------------------------------------------------ // Copyright 2007-2014 by Jyh-Ming Lien and George Mason University // See the file "LICENSE" for more information //------------------------------------------------------------------------------ #ifndef _H_UTILITY #define _H_UTILITY #include <cmath> #include <cassert> #include <stdlib.h> #include <string.h> #include <limits.h> #include <string> #include <iostream> // define C++ stream I/O routines #include <iomanip> using namespace std; namespace mathtool { // Miscellaneous Scalar Math template<class T> T abs(T x) { return (((x) < 0) ? (-(x)) : (x)); } template<class T> T sqr(T x) { return ((x)* (x)); } template<class T> int round(T x, int p) { return (long int)(((long int)((x)*std::pow(10.0, p) + ((x)<0 ? -0.5 : 0.5))) / std::pow(10.0, p)); } template<class T> int round(T v) { int integer = (int)floor((long int)(v)); T fraction = v - integer; if (v>0) return (fraction >= 0.5) ? integer + 1 : integer; else return (fraction >= -0.5) ? integer : integer + 1; } template<class T> int sign(T x) { return ((x) >= 0 ? 1 : -1); } //#define swap(x1, x2) {int tmp=x1; x1=x2; x2=tmp} template<class T, class S> T applysign(T x, S y) { return ((y) >= 0 ? abs(x) : -abs(x)); } // Angle Conversions & Constants #ifndef PI #define PI 3.1415926535897f #endif #ifndef PI2 #define PI2 6.2831853071794f #endif #define RAD2DEG (180/PI) #define DEG2RAD (PI/180) #define DegToRad(x) ((x)*DEG2RAD) #define RadToDeg(x) ((x)*RAD2DEG) /* range of real numbers */ #ifndef SMALLNUMBER #define SMALLNUMBER 1.0e-10 #endif #ifndef HUGENUMBER #define HUGENUMBER 1.0e10 #endif //computes sqrt(a^2 + b^2) without destructive underflow or overflow template<class T> T pythag(T a, T b) { T absa, absb; absa = fabs(a); absb = fabs(b); if (absa > absb) return absa * sqrt(1.0 + sqr(absb / absa)); else if (absb > 0) return absb * sqrt(1.0 + sqr(absa / absb)); else return 0; } // Utility Error message routines // print s to stdout with trailing blank and no terminating end of line // Utility message routines inline void prompt(char *s) { cout << s << " "; } // print s1, s2, s3 to stdout as blank separated fields with terminating eol inline void message(char *s1, char *s2 = NULL, char *s3 = NULL) { cout << s1; if (s2 != NULL && strlen(s2) > 0) cout << " " << s2; if (s3 != NULL && strlen(s3) > 0) cout << " " << s3; cout << endl; } // print Status: to stdout followed by message(s1, s2, s3) inline void status(char *s1, char *s2=NULL, char *s3=NULL) { cout << "Status: "; message(s1, s2, s3); } // print Error: followed by s1, s2 and s3 to stderr as blank separated fields // with terminating eol inline void error(char *s1, char *s2 = NULL, char *s3 = NULL) { cerr << "Error: "; cerr << s1; if (s2 != NULL && strlen(s2) > 0) cerr << " " << s2; if (s3 != NULL && strlen(s3) > 0) cerr << " " << s3; cerr << endl; } // print error(s1, s2, s3) and then exit program with code 1 inline void abort(char *s1, char *s2 = NULL, char *s3 = NULL) { error(s1, s2, s3); exit(1); } ///Added by Jyh-Ming Lien #ifdef WIN32 //////////////////////////////////////////////////////////////////////////////////////// // Following functions define M_PI and drand48, which are not starndard c library and // definitions. In addition, rint used to round off float points to int is also here. ///////////////////////////////////////////////////////////////////////////////////////// #define M_PI 3.1415926 //reference PI above extern "C" { //Implementation of these functions are located in util.cpp double drand48(); double erand48(register unsigned short *xsubi); long irand48(register unsigned short m); long krand48(register unsigned short *xsubi, unsigned short m); long lrand48(); long mrand48(); static void next(); void srand48(long seedval); unsigned short * seed48(unsigned short seed16v[3]); void lcong48(unsigned short param[7]); long nrand48(register unsigned short *xsubi); long jrand48(register unsigned short *xsubi); /**Round to closest integer. *The rint() function rounds x to an integer value according *to the prevalent rounding mode. The default rounding mode *is to round to the nearest integer. *@return The rint() function returns the integer value as a float- *ing-point number. */ double rint(double x); } //end extern "C" #endif //_WIN32 } //end of nprmlib #endif
[ "jmlien@cs.gmu.edu" ]
jmlien@cs.gmu.edu
b3d78f78ea1dee553ccff33b7d431b1e863dc6e6
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/base/memory/platform_shared_memory_mapper_fuchsia.cc
357b3b3951d363589aed349f8e65c3a4ceb69ad9
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
1,253
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/platform_shared_memory_mapper.h" #include "base/logging.h" #include <lib/zx/vmar.h> #include "base/fuchsia/fuchsia_logging.h" namespace base { absl::optional<span<uint8_t>> PlatformSharedMemoryMapper::Map( subtle::PlatformSharedMemoryHandle handle, bool write_allowed, uint64_t offset, size_t size) { uintptr_t addr; zx_vm_option_t options = ZX_VM_REQUIRE_NON_RESIZABLE | ZX_VM_PERM_READ; if (write_allowed) options |= ZX_VM_PERM_WRITE; zx_status_t status = zx::vmar::root_self()->map(options, /*vmar_offset=*/0, *handle, offset, size, &addr); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "zx_vmar_map"; return absl::nullopt; } return make_span(reinterpret_cast<uint8_t*>(addr), size); } void PlatformSharedMemoryMapper::Unmap(span<uint8_t> mapping) { uintptr_t addr = reinterpret_cast<uintptr_t>(mapping.data()); zx_status_t status = zx::vmar::root_self()->unmap(addr, mapping.size()); if (status != ZX_OK) ZX_DLOG(ERROR, status) << "zx_vmar_unmap"; } } // namespace base
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
26ac795738f7befcde26b76c317ad3c8636ada42
541c4f648cee67b937b3a5087d69a467826aff52
/Src/Equation/Centered/EnthalpyFD/enthalpyfd_coefficients.cpp
2f12703f170416720bdf3fd246603f6fc7035cc2
[]
no_license
Wentao2017/PSI-Boil-liquid-film
9831382e5d3303a7be54f2216225f113c804c630
8c59435c4bc6c75bb06b17f6d4c899aee0099aa0
refs/heads/master
2023-05-07T05:38:07.261651
2021-05-31T06:28:25
2021-05-31T06:28:25
328,350,633
0
1
null
null
null
null
UTF-8
C++
false
false
901
cpp
#include "enthalpyfd.h" /***************************************************************************//** * \brief Coefficients for the derivatives (to be overwritten by child class). *******************************************************************************/ real EnthalpyFD::coef_x_m(const real dxm, const real dxp, const real x0) { return 2.0/dxm/(dxm+dxp); } real EnthalpyFD::coef_x_p(const real dxm, const real dxp, const real x0) { return 2.0/dxp/(dxm+dxp); } real EnthalpyFD::coef_y_m(const real dxm, const real dxp, const real x0) { return 2.0/dxm/(dxm+dxp); } real EnthalpyFD::coef_y_p(const real dxm, const real dxp, const real x0) { return 2.0/dxp/(dxm+dxp); } real EnthalpyFD::coef_z_m(const real dxm, const real dxp, const real x0) { return 2.0/dxm/(dxm+dxp); } real EnthalpyFD::coef_z_p(const real dxm, const real dxp, const real x0) { return 2.0/dxp/(dxm+dxp); }
[ "guow@eu-login-06.euler.ethz.ch" ]
guow@eu-login-06.euler.ethz.ch
cbf39dbbcf16c66d3f73a0b9ed38712fa0d31e5d
14ccd1eb6898455b579ab0acd48131b50dbc4a2b
/src/world/network/ServDisconnectListener.cpp
d7e8f2495bf6370dee103972985a44c8c032fefc
[]
no_license
navispeed/indiestudio
40a542af254dca06a6cbadb29aaa124a62c56067
55e0451334fa5047b671e64cd33cab5a4e1839e0
refs/heads/master
2021-01-01T18:44:43.562091
2016-06-21T13:20:45
2016-06-21T13:20:45
98,419,981
0
1
null
null
null
null
UTF-8
C++
false
false
661
cpp
// // ServDisconnectListener.cpp for indie in /home/trouve_b/Desktop/CPP_project/cpp_indie_studio // // Made by Alexis Trouve // Login <trouve_b@epitech.net> // // Started on Sun May 22 22:22:49 2016 Alexis Trouve // Last update Mon May 23 22:21:30 2016 Alexis Trouve // #include "ServDisconnectListener.hh" using namespace gauntlet; using namespace world; using namespace network; ServDisconnectListener::ServDisconnectListener(GameServer *gameServ) { gameServer = gameServ; } ServDisconnectListener::~ServDisconnectListener() { } void ServDisconnectListener::notify(const network::PacketDisconnect *packet) { gameServer->receiveDeco(packet); }
[ "alexis.trouve@epitech.eu" ]
alexis.trouve@epitech.eu
9f17a57252ca19853150ca04f6ac85da8c8eb926
5ec61911b971de3deb2e98b3fe92df1bba63db77
/prj_4/obj_dir/Vmem__Syms.cpp
baae7c4b32528572c440c4d16da3da641b1e3437
[]
no_license
nchronas/verilator_examples
574ff2a9505ff47e33ae2861d61236ceb98678eb
3fab42395a02f762ccfff7b71ad2f6bc4801e28d
refs/heads/master
2021-01-23T16:53:00.316724
2017-06-09T10:53:38
2017-06-09T10:53:38
93,307,996
1
0
null
null
null
null
UTF-8
C++
false
false
564
cpp
// Verilated -*- C++ -*- // DESCRIPTION: Verilator output: Symbol table implementation internals #include "Vmem__Syms.h" #include "Vmem.h" // FUNCTIONS Vmem__Syms::Vmem__Syms(Vmem* topp, const char* namep) // Setup locals : __Vm_namep(namep) , __Vm_activity(false) , __Vm_didInit(false) // Setup submodule names { // Pointer to top level TOPp = topp; // Setup each module's pointers to their submodules // Setup each module's pointer back to symbol table (for public functions) TOPp->__Vconfigure(this, true); // Setup scope names }
[ "nchronas@gmail.com" ]
nchronas@gmail.com
88762b213fad89624c2b662b320e947817fe3395
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
/Windows API函数参考手册/第03章设备上下文─DC/3.4区域操作/3_4_2_1/StdAfx.cpp
3c018ae3c54e1b2a7500767264b2352b0d30fc06
[]
no_license
IgorYunusov/Mega-collection-cpp-1
c7c09e3c76395bcbf95a304db6462a315db921ba
42d07f16a379a8093b6ddc15675bf777eb10d480
refs/heads/master
2020-03-24T10:20:15.783034
2018-06-12T13:19:05
2018-06-12T13:19:05
142,653,486
3
1
null
2018-07-28T06:36:35
2018-07-28T06:36:35
null
UTF-8
C++
false
false
288
cpp
// stdafx.cpp : source file that includes just the standard includes // 3_4_2_1.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "wyrover@gmail.com" ]
wyrover@gmail.com
3372ef2bed97f9ec35dc4974a73305bbe757d1dd
b0298c872be146ff191f31e244f7dd0857da9d67
/engine/include/ph/config/GlobalConfig.hpp
2d04a20ace6f1ce3782ca36e1139c1e13ed135cc
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
PetorSFZ/PhantasyEngine
a6773d31465a62a0636ca4b6d9b8cf60f1c70f21
befe8e9499b7fd93d8765721b6841337a57b0dd6
refs/heads/master
2020-04-02T07:11:31.736512
2019-11-17T20:25:38
2019-11-17T20:25:38
154,185,401
0
0
null
null
null
null
UTF-8
C++
false
false
5,935
hpp
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // For other contributors see Contributors.txt // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #pragma once #include <sfz/containers/DynArray.hpp> #include <sfz/memory/Allocator.hpp> #include "ph/config/Setting.hpp" namespace ph { using sfz::Allocator; using sfz::DynArray; // GlobalConfig // ------------------------------------------------------------------------------------------------ struct GlobalConfigImpl; // Pimpl pattern /// A global configuration class /// /// The singleton instance should be acquired from the Phantasy Engine global context /// /// Setting invariants: /// 1, All settings are owned by the singleton instance, no one else may delete the memory. /// 2, A setting, once created, can never be destroyed or removed during runtime. /// 3, A setting will occupy the same place in memory for the duration of the program's runtime. /// 4, A setting can not change section or key identifiers once created. /// /// These invariants mean that it is safe (and expected) to store direct pointers to settings and /// read/write to them when needed. However, settings may change type during runtime. So it is /// recommended to store a pointer to the setting itself and not its internal int value for /// example. /// /// Settings are expected to stay relatively static during the runtime of a program. They are not /// meant for communication and should not be changed unless the user specifically requests for /// them to be changed. class GlobalConfig { public: // Constructors & destructors // -------------------------------------------------------------------------------------------- inline GlobalConfig() noexcept : mImpl(nullptr) {} // Compile fix for Emscripten GlobalConfig(const GlobalConfig&) = delete; GlobalConfig& operator= (const GlobalConfig&) = delete; GlobalConfig(GlobalConfig&&) = delete; GlobalConfig& operator= (GlobalConfig&&) = delete; ~GlobalConfig() noexcept; // Methods // -------------------------------------------------------------------------------------------- void init(const char* basePath, const char* fileName, Allocator* allocator) noexcept; void destroy() noexcept; void load() noexcept; bool save() noexcept; /// Gets the specified Setting. If it does not exist it will be created (type int with value 0). /// The optional parameter "created" returns whether the Setting was created or already existed. Setting* createSetting(const char* section, const char* key, bool* created = nullptr) noexcept; // Getters // -------------------------------------------------------------------------------------------- /// Gets the specified Setting. Returns nullptr if it does not exist. Setting* getSetting(const char* section, const char* key) noexcept; Setting* getSetting(const char* key) noexcept; /// Returns pointers to all available settings void getAllSettings(DynArray<Setting*>& settings) noexcept; /// Returns all sections available void getSections(DynArray<str32>& sections) noexcept; /// Returns all settings available in a given section void getSectionSettings(const char* section, DynArray<Setting*>& settings) noexcept; // Sanitizers // -------------------------------------------------------------------------------------------- /// A sanitizer is basically a wrapper around createSetting, with the addition that it also /// ensures that the Setting is of the requested type and with values conforming to the /// specified bounds. If the setting does not exist or is of an incompatible type it will be /// set to the specified default value. Setting* sanitizeInt( const char* section, const char* key, bool writeToFile = true, const IntBounds& bounds = IntBounds(0)) noexcept; Setting* sanitizeFloat( const char* section, const char* key, bool writeToFile = true, const FloatBounds& bounds = FloatBounds(0.0f)) noexcept; Setting* sanitizeBool( const char* section, const char* key, bool writeToFile = true, const BoolBounds& bounds = BoolBounds(false)) noexcept; Setting* sanitizeInt( const char* section, const char* key, bool writeToFile = true, int32_t defaultValue = 0, int32_t minValue = INT32_MIN, int32_t maxValue = INT32_MAX, int32_t step = 1) noexcept; Setting* sanitizeFloat( const char* section, const char* key, bool writeToFile = true, float defaultValue = 0.0f, float minValue = FLT_MIN, float maxValue = FLT_MAX) noexcept; Setting* sanitizeBool( const char* section, const char* key, bool writeToFile = true, bool defaultValue = false) noexcept; private: // Private members // -------------------------------------------------------------------------------------------- GlobalConfigImpl* mImpl; }; // Statically owned global config // ------------------------------------------------------------------------------------------------ /// Statically owned global config. Default constructed. Only to be used for setContext() in /// PhantasyEngineMain.cpp during boot. GlobalConfig* getStaticGlobalConfigBoot() noexcept; } // namespace ph
[ "peter@hstroem.se" ]
peter@hstroem.se