void core::RestrictedLineF::setP2(const QPointF &p2) { switch(lineConstrain){ case RestrictedLineF::HorizontalLeft: if(p2.x() <= p1().x()){ QLineF::setP2(QPointF(p2.x(), p1().y())); }else{ QLineF::setP2(p1()); } break; case RestrictedLineF::HorizontalRight: if(p2.x() >= p1().x()){ QLineF::setP2(QPointF(p2.x(), p1().y())); }else{ QLineF::setP2(p1()); } break; case RestrictedLineF::Horizontal: QLineF::setP2(QPointF(p2.x(), p1().y())); break; case RestrictedLineF::VerticalUp: if(p2.y() <= p1().y()){ QLineF::setP2(QPointF(p1().x(), p2.y())); }else{ QLineF::setP2(p1()); } break; case RestrictedLineF::VerticalDown: if(p2.y() >= p1().y()){ QLineF::setP2(QPointF(p1().x(), p2.y())); }else{ QLineF::setP2(p1()); } break; case RestrictedLineF::Vertical: QLineF::setP2(QPointF(p1().x(), p2.y())); break; case RestrictedLineF::None: QLineF::setP2(p2); break; case RestrictedLineF::Both: default: break; } }
void VisibilityLayout::layout(GraphAttributes &GA, const UpwardPlanRep &UPROrig) { UpwardPlanRep UPR = UPROrig; //clear some data for(edge e : GA.constGraph().edges) { GA.bends(e).clear(); } int minGridDist = 1; for(node v : GA.constGraph().nodes) { if (minGridDist < max(GA.height(v), GA.width(v))) minGridDist = (int) max(GA.height(v), GA.width(v)); } minGridDist = max(minGridDist*2+1, m_grid_dist); CombinatorialEmbedding &gamma = UPR.getEmbedding(); //add edge (s,t) adjEntry adjSrc = nullptr; for(adjEntry adj : UPR.getSuperSource()->adjEntries) { if (gamma.rightFace(adj) == gamma.externalFace()) adjSrc = adj; break; } OGDF_ASSERT(adjSrc != nullptr); edge e_st = UPR.newEdge(adjSrc, UPR.getSuperSink()); // on the right gamma.computeFaces(); gamma.setExternalFace(gamma.rightFace(e_st->adjSource())); constructVisibilityRepresentation(UPR); // the preliminary postion NodeArray<int> xPos(UPR); NodeArray<int> yPos(UPR); // node Position for(node v : UPR.nodes) { NodeSegment vVis = nodeToVis[v]; int x = (int) (vVis.x_l + vVis.x_r)/2 ; // median positioning xPos[v] = x; yPos[v] = vVis.y; if (UPR.original(v) != nullptr) { node vOrig = UPR.original(v); //final position GA.x(vOrig) = x * minGridDist; GA.y(vOrig) = vVis.y * minGridDist; } } //compute bendpoints for(edge e : GA.constGraph().edges) { const List<edge> &chain = UPR.chain(e); for(edge eUPR : chain) { EdgeSegment eVis = edgeToVis[eUPR]; if (chain.size() == 1) { if ((yPos[eUPR->target()] - yPos[eUPR->source()]) > 1) { DPoint p1(eVis.x*minGridDist, (yPos[eUPR->source()]+1)*minGridDist); DPoint p2(eVis.x*minGridDist, (yPos[eUPR->target()]-1)*minGridDist); GA.bends(e).pushBack(p1); if (yPos[eUPR->source()]+1 != yPos[eUPR->target()]-1) GA.bends(e).pushBack(p2); } } else { //short edge if ((yPos[eUPR->target()] - yPos[eUPR->source()]) == 1) { if (UPR.original(eUPR->target()) == nullptr) { node tgtUPR = eUPR->target(); DPoint p(xPos[tgtUPR]*minGridDist, yPos[tgtUPR]*minGridDist); GA.bends(e).pushBack(p); } } //long edge else { DPoint p1(eVis.x*minGridDist, (yPos[eUPR->source()]+1)*minGridDist); DPoint p2(eVis.x*minGridDist, (yPos[eUPR->target()]-1)*minGridDist); GA.bends(e).pushBack(p1); if (yPos[eUPR->source()]+1 != yPos[eUPR->target()]-1) GA.bends(e).pushBack(p2); if (UPR.original(eUPR->target()) == nullptr) { node tgtUPR = eUPR->target(); DPoint p(xPos[tgtUPR]*minGridDist, yPos[tgtUPR]*minGridDist); GA.bends(e).pushBack(p); } } } } DPolyline &poly = GA.bends(e); DPoint pSrc(GA.x(e->source()), GA.y(e->source())); DPoint pTgt(GA.x(e->target()), GA.y(e->target())); poly.normalize(pSrc, pTgt); } }
void serialization_test() { std::string file("test"); bool tbIn = true,tbOut; char tcIn = 't',tcOut; unsigned char tucIn = 'u',tucOut; short tsIn = 6,tsOut; int tiIn = -10,tiOut; unsigned int tuiIn = 10,tuiOut; float tfIn = 1.0005,tfOut; double tdIn = 1.000000005,tdOut; int* tinpIn = NULL,*tinpOut = NULL; float* tfpIn = new float,*tfpOut = NULL; *tfpIn = 1.11101; std::string tstrIn("test12345"),tstrOut; Test2 tObjIn,tObjOut; int ti = 2; tObjIn.ti = &ti; Test1 test1,test2,test3; test1.ts = "100"; test2.ts = "200"; test3.ts = "300"; Test1 testA, testC; testA.tt = &test1; testA.ts = "test123"; testA.tvt.push_back(&test2); testA.tvt.push_back(&test3); Test1 testB = testA; testB.ts = "400"; testB.tvt.pop_back(); std::pair<int,bool> tPairIn(10,true); std::pair<int,bool> tPairOut; std::vector<int> tVector1In ={1,2,3,4,5}; std::vector<int> tVector1Out; std::pair<int,bool> p1(10,1); std::pair<int,bool> p2(1,0); std::pair<int,bool> p3(10000,1); std::vector<std::pair<int,bool> > tVector2In ={p1,p2,p3}; std::vector<std::pair<int,bool> > tVector2Out; std::set<std::pair<int,bool> > tSetIn ={p1,p2,p3}; std::set<std::pair<int,bool> > tSetOut; std::map<int,bool> tMapIn ={p1,p2,p3}; std::map<int,bool> tMapOut; Eigen::Matrix<float,3,3> tDenseMatrixIn; tDenseMatrixIn << Eigen::Matrix<float,3,3>::Random(); tDenseMatrixIn.coeffRef(0,0) = 1.00001; Eigen::Matrix<float,3,3> tDenseMatrixOut; Eigen::Matrix<float,3,3,Eigen::RowMajor> tDenseRowMatrixIn; tDenseRowMatrixIn << Eigen::Matrix<float,3,3,Eigen::RowMajor>::Random(); Eigen::Matrix<float,3,3,Eigen::RowMajor> tDenseRowMatrixOut; Eigen::SparseMatrix<double> tSparseMatrixIn; tSparseMatrixIn.resize(3,3); tSparseMatrixIn.insert(0,0) = 1.3; tSparseMatrixIn.insert(1,1) = 10.2; tSparseMatrixIn.insert(2,2) = 100.1; tSparseMatrixIn.finalize(); Eigen::SparseMatrix<double> tSparseMatrixOut; // binary serialization igl::serialize(tbIn,file); igl::deserialize(tbOut,file); assert(tbIn == tbOut); igl::serialize(tcIn,file); igl::deserialize(tcOut,file); assert(tcIn == tcOut); igl::serialize(tucIn,file); igl::deserialize(tucOut,file); assert(tucIn == tucOut); igl::serialize(tsIn,file); igl::deserialize(tsOut,file); assert(tsIn == tsOut); igl::serialize(tiIn,file); igl::deserialize(tiOut,file); assert(tiIn == tiOut); igl::serialize(tuiIn,file); igl::deserialize(tuiOut,file); assert(tuiIn == tuiOut); igl::serialize(tfIn,file); igl::deserialize(tfOut,file); assert(tfIn == tfOut); igl::serialize(tdIn,file); igl::deserialize(tdOut,file); assert(tdIn == tdOut); igl::serialize(tinpIn,file); igl::deserialize(tinpOut,file); assert(tinpIn == tinpOut); igl::serialize(tfpIn,file); igl::deserialize(tfpOut,file); assert(*tfpIn == *tfpOut); tfpOut = NULL; igl::serialize(tstrIn,file); igl::deserialize(tstrOut,file); assert(tstrIn == tstrOut); // updating igl::serialize(tbIn,"tb",file,true); igl::serialize(tcIn,"tc",file); igl::serialize(tiIn,"ti",file); tiIn++; igl::serialize(tiIn,"ti",file); tiIn++; igl::serialize(tiIn,"ti",file); igl::deserialize(tbOut,"tb",file); igl::deserialize(tcOut,"tc",file); igl::deserialize(tiOut,"ti",file); assert(tbIn == tbOut); assert(tcIn == tcOut); assert(tiIn == tiOut); igl::serialize(tsIn,"tsIn",file,true); igl::serialize(tVector1In,"tVector1In",file); igl::serialize(tVector2In,"tsIn",file); igl::deserialize(tVector2Out,"tsIn",file); for(unsigned int i=0;i<tVector2In.size();i++) { assert(tVector2In[i].first == tVector2Out[i].first); assert(tVector2In[i].second == tVector2Out[i].second); } tVector2Out.clear(); igl::serialize(tObjIn,file); igl::deserialize(tObjOut,file); assert(tObjIn.tc == tObjOut.tc); assert(*tObjIn.ti == *tObjOut.ti); for(unsigned int i=0;i<tObjIn.tvb.size();i++) assert(tObjIn.tvb[i] == tObjOut.tvb[i]); tObjOut.ti = NULL; igl::serialize(tPairIn,file); igl::deserialize(tPairOut,file); assert(tPairIn.first == tPairOut.first); assert(tPairIn.second == tPairOut.second); igl::serialize(tVector1In,file); igl::deserialize(tVector1Out,file); for(unsigned int i=0;i<tVector1In.size();i++) assert(tVector1In[i] == tVector1Out[i]); igl::serialize(tVector2In,file); igl::deserialize(tVector2Out,file); for(unsigned int i=0;i<tVector2In.size();i++) { assert(tVector2In[i].first == tVector2Out[i].first); assert(tVector2In[i].second == tVector2Out[i].second); } igl::serialize(tSetIn,file); igl::deserialize(tSetOut,file); assert(tSetIn.size() == tSetOut.size()); igl::serialize(tMapIn,file); igl::deserialize(tMapOut,file); assert(tMapIn.size() == tMapOut.size()); igl::serialize(tDenseMatrixIn,file); igl::deserialize(tDenseMatrixOut,file); assert((tDenseMatrixIn - tDenseMatrixOut).sum() == 0); igl::serialize(tDenseRowMatrixIn,file); igl::deserialize(tDenseRowMatrixOut,file); assert((tDenseRowMatrixIn - tDenseRowMatrixOut).sum() == 0); igl::serialize(tSparseMatrixIn,file); igl::deserialize(tSparseMatrixOut,file); assert((tSparseMatrixIn - tSparseMatrixOut).sum() == 0); igl::serialize(testB,file); igl::deserialize(testC,file); assert(testB.ts == testC.ts); assert(testB.tvt.size() == testC.tvt.size()); for(unsigned int i=0;i<testB.tvt.size();i++) { assert(testB.tvt[i]->ts == testC.tvt[i]->ts); assert(testB.tvt[i]->tvt.size() == testC.tvt[i]->tvt.size()); assert(testB.tvt[i]->tt == testC.tvt[i]->tt); } assert(testB.tt->ts == testC.tt->ts); assert(testB.tt->tvt.size() == testC.tt->tvt.size()); assert(testB.tt->tt == testC.tt->tt); testC = Test1(); // big data test /*std::vector<std::vector<float> > bigDataIn,bigDataOut; for(unsigned int i=0;i<10000;i++) { std::vector<float> v; for(unsigned int j=0;j<10000;j++) { v.push_back(j); } bigDataIn.push_back(v); } igl::Timer timer; timer.start(); igl::serialize(bigDataIn,file); timer.stop(); std::cout << "ser: " << timer.getElapsedTimeInMilliSec() << std::endl; timer.start(); igl::deserialize(bigDataOut,file); timer.stop(); std::cout << "des: " << timer.getElapsedTimeInMilliSec() << std::endl; char c; std::cin >> c; */ // xml serialization igl::serialize_xml(tbIn,file); igl::deserialize_xml(tbOut,file); assert(tbIn == tbOut); igl::serialize_xml(tcIn,file); igl::deserialize_xml(tcOut,file); assert(tcIn == tcOut); igl::serialize_xml(tucIn,file); igl::deserialize_xml(tucOut,file); assert(tucIn == tucOut); igl::serialize_xml(tsIn,file); igl::deserialize_xml(tsOut,file); assert(tsIn == tsOut); igl::serialize_xml(tiIn,file); igl::deserialize_xml(tiOut,file); assert(tiIn == tiOut); igl::serialize_xml(tuiIn,file); igl::deserialize_xml(tuiOut,file); assert(tuiIn == tuiOut); igl::serialize_xml(tfIn,file); igl::deserialize_xml(tfOut,file); assert(tfIn == tfOut); igl::serialize_xml(tdIn,file); igl::deserialize_xml(tdOut,file); assert(tdIn == tdOut); igl::serialize_xml(tinpIn,file); igl::deserialize_xml(tinpOut,file); assert(tinpIn == tinpOut); igl::serialize_xml(tfpIn,file); igl::deserialize_xml(tfpOut,file); assert(*tfpIn == *tfpOut); igl::serialize_xml(tstrIn,file); igl::deserialize_xml(tstrOut,file); assert(tstrIn == tstrOut); // updating igl::serialize_xml(tbIn,"tb",file,false,true); igl::serialize_xml(tcIn,"tc",file); igl::serialize_xml(tiIn,"ti",file); tiIn++; igl::serialize_xml(tiIn,"ti",file); tiIn++; igl::serialize_xml(tiIn,"ti",file); igl::deserialize_xml(tbOut,"tb",file); igl::deserialize_xml(tcOut,"tc",file); igl::deserialize_xml(tiOut,"ti",file); assert(tbIn == tbOut); assert(tcIn == tcOut); assert(tiIn == tiOut); igl::serialize_xml(tsIn,"tsIn",file,false,true); igl::serialize_xml(tVector1In,"tVector1In",file); igl::serialize_xml(tVector2In,"tsIn",file); igl::deserialize_xml(tVector2Out,"tsIn",file); for(unsigned int i=0;i<tVector2In.size();i++) { assert(tVector2In[i].first == tVector2Out[i].first); assert(tVector2In[i].second == tVector2Out[i].second); } tVector2Out.clear(); // binarization igl::serialize_xml(tVector2In,"tVector2In",file,true); igl::deserialize_xml(tVector2Out,"tVector2In",file); for(unsigned int i=0;i<tVector2In.size();i++) { assert(tVector2In[i].first == tVector2Out[i].first); assert(tVector2In[i].second == tVector2Out[i].second); } igl::serialize_xml(tObjIn,file); igl::deserialize_xml(tObjOut,file); assert(tObjIn.tc == tObjOut.tc); assert(*tObjIn.ti == *tObjOut.ti); for(unsigned int i=0;i<tObjIn.tvb.size();i++) assert(tObjIn.tvb[i] == tObjOut.tvb[i]); igl::serialize_xml(tPairIn,file); igl::deserialize_xml(tPairOut,file); assert(tPairIn.first == tPairOut.first); assert(tPairIn.second == tPairOut.second); igl::serialize_xml(tVector1In,file); igl::deserialize_xml(tVector1Out,file); for(unsigned int i=0;i<tVector1In.size();i++) assert(tVector1In[i] == tVector1Out[i]); igl::serialize_xml(tVector2In,file); igl::deserialize_xml(tVector2Out,file); for(unsigned int i=0;i<tVector2In.size();i++) { assert(tVector2In[i].first == tVector2Out[i].first); assert(tVector2In[i].second == tVector2Out[i].second); } igl::serialize_xml(tSetIn,file); igl::deserialize_xml(tSetOut,file); assert(tSetIn.size() == tSetOut.size()); igl::serialize_xml(tMapIn,file); igl::deserialize_xml(tMapOut,file); assert(tMapIn.size() == tMapOut.size()); igl::serialize_xml(tDenseMatrixIn,file); igl::deserialize_xml(tDenseMatrixOut,file); assert((tDenseMatrixIn - tDenseMatrixOut).sum() == 0); igl::serialize_xml(tDenseRowMatrixIn,file); igl::deserialize_xml(tDenseRowMatrixOut,file); assert((tDenseRowMatrixIn - tDenseRowMatrixOut).sum() == 0); igl::serialize_xml(tSparseMatrixIn,file); igl::deserialize_xml(tSparseMatrixOut,file); assert((tSparseMatrixIn - tSparseMatrixOut).sum() == 0); igl::serialize_xml(testB,file); igl::deserialize_xml(testC,file); assert(testB.ts == testC.ts); assert(testB.tvt.size() == testC.tvt.size()); for(unsigned int i=0;i<testB.tvt.size();i++) { assert(testB.tvt[i]->ts == testC.tvt[i]->ts); assert(testB.tvt[i]->tvt.size() == testC.tvt[i]->tvt.size()); assert(testB.tvt[i]->tt == testC.tvt[i]->tt); } assert(testB.tt->ts == testC.tt->ts); assert(testB.tt->tvt.size() == testC.tt->tvt.size()); assert(testB.tt->tt == testC.tt->tt); // big data test /*std::vector<std::vector<float> > bigDataIn,bigDataOut; for(unsigned int i=0;i<10000;i++) { std::vector<float> v; for(unsigned int j=0;j<10000;j++) { v.push_back(j); } bigDataIn.push_back(v); } igl::Timer timer; timer.start(); igl::serialize_xml(bigDataIn,"bigDataIn",file,igl::SERIALIZE_BINARY); timer.stop(); std::cout << "ser: " << timer.getElapsedTimeInMilliSec() << std::endl; timer.start(); igl::deserialize_xml(bigDataOut,"bigDataIn",file); timer.stop(); std::cout << "des: " << timer.getElapsedTimeInMilliSec() << std::endl; char c; std::cin >> c;*/ std::cout << "All tests run successfully!\n"; }
/* perform actions required when leaving 'port_state' and entering 'state' */ void toState(UInteger8 state, RunTimeOpts *rtOpts, PtpClock *ptpClock) { ptpClock->message_activity = TRUE; /* leaving state tasks */ switch (ptpClock->portState) { case PTP_MASTER: timerStop(SYNC_INTERVAL_TIMER, ptpClock->itimer); timerStop(ANNOUNCE_INTERVAL_TIMER, ptpClock->itimer); timerStop(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer); break; case PTP_SLAVE: timerStop(ANNOUNCE_RECEIPT_TIMER, ptpClock->itimer); if (ptpClock->delayMechanism == E2E) timerStop(DELAYREQ_INTERVAL_TIMER, ptpClock->itimer); else if (ptpClock->delayMechanism == P2P) timerStop(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer); initClock(rtOpts, ptpClock); break; case PTP_PASSIVE: timerStop(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer); timerStop(ANNOUNCE_RECEIPT_TIMER, ptpClock->itimer); break; case PTP_LISTENING: timerStop(ANNOUNCE_RECEIPT_TIMER, ptpClock->itimer); break; default: break; } /* entering state tasks */ /* * No need of PRE_MASTER state because of only ordinary clock * implementation. */ switch (state) { case PTP_INITIALIZING: DBG("state PTP_INITIALIZING\n"); ptpClock->portState = PTP_INITIALIZING; break; case PTP_FAULTY: DBG("state PTP_FAULTY\n"); ptpClock->portState = PTP_FAULTY; break; case PTP_DISABLED: DBG("state PTP_DISABLED\n"); ptpClock->portState = PTP_DISABLED; break; case PTP_LISTENING: /* in Listening mode, make sure we don't send anything. Instead we just expect/wait for announces (started below) */ timerStop(SYNC_INTERVAL_TIMER, ptpClock->itimer); timerStop(ANNOUNCE_INTERVAL_TIMER, ptpClock->itimer); timerStop(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer); timerStop(DELAYREQ_INTERVAL_TIMER, ptpClock->itimer); /* * Count how many _unique_ timeouts happen to us. * If we were already in Listen mode, then do not count this as a seperate reset, but stil do a new IGMP refresh */ if (ptpClock->portState != PTP_LISTENING) { ptpClock->reset_count++; } /* Revert to the original DelayReq interval, and ignore the one for the last master */ ptpClock->logMinDelayReqInterval = rtOpts->initial_delayreq; /* force a IGMP refresh per reset */ if (rtOpts->do_IGMP_refresh) { netRefreshIGMP(&ptpClock->netPath, rtOpts, ptpClock); } DBG("state PTP_LISTENING\n"); INFO(" now in state PTP_LISTENING\n"); timerStart(ANNOUNCE_RECEIPT_TIMER, (ptpClock->announceReceiptTimeout) * (pow(2,ptpClock->logAnnounceInterval)), ptpClock->itimer); ptpClock->portState = PTP_LISTENING; break; case PTP_MASTER: DBG("state PTP_MASTER\n"); INFO(" now in state PTP_MASTER\n"); timerStart(SYNC_INTERVAL_TIMER, pow(2,ptpClock->logSyncInterval), ptpClock->itimer); DBG("SYNC INTERVAL TIMER : %f \n", pow(2,ptpClock->logSyncInterval)); timerStart(ANNOUNCE_INTERVAL_TIMER, pow(2,ptpClock->logAnnounceInterval), ptpClock->itimer); timerStart(PDELAYREQ_INTERVAL_TIMER, pow(2,ptpClock->logMinPdelayReqInterval), ptpClock->itimer); ptpClock->portState = PTP_MASTER; break; case PTP_PASSIVE: DBG("state PTP_PASSIVE\n"); INFO(" now in state PTP_PASSIVE\n"); timerStart(PDELAYREQ_INTERVAL_TIMER, pow(2,ptpClock->logMinPdelayReqInterval), ptpClock->itimer); timerStart(ANNOUNCE_RECEIPT_TIMER, (ptpClock->announceReceiptTimeout) * (pow(2,ptpClock->logAnnounceInterval)), ptpClock->itimer); ptpClock->portState = PTP_PASSIVE; p1(ptpClock, rtOpts); break; case PTP_UNCALIBRATED: DBG("state PTP_UNCALIBRATED\n"); ptpClock->portState = PTP_UNCALIBRATED; break; case PTP_SLAVE: DBG("state PTP_SLAVE\n"); INFO(" now in state PTP_SLAVE\n"); initClock(rtOpts, ptpClock); ptpClock->waitingForFollow = FALSE; ptpClock->waitingForDelayResp = FALSE; // FIXME: clear these vars inside initclock clearTime(&ptpClock->pdelay_req_send_time); clearTime(&ptpClock->pdelay_req_receive_time); clearTime(&ptpClock->pdelay_resp_send_time); clearTime(&ptpClock->pdelay_resp_receive_time); timerStart(OPERATOR_MESSAGES_TIMER, OPERATOR_MESSAGES_INTERVAL, ptpClock->itimer); timerStart(ANNOUNCE_RECEIPT_TIMER, (ptpClock->announceReceiptTimeout) * (pow(2,ptpClock->logAnnounceInterval)), ptpClock->itimer); /* * Previously, this state transition would start the delayreq timer immediately. * However, if this was faster than the first received sync, then the servo would drop the delayResp * Now, we only start the timer after we receive the first sync (in handle_sync()) */ ptpClock->waiting_for_first_sync = TRUE; ptpClock->waiting_for_first_delayresp = TRUE; ptpClock->portState = PTP_SLAVE; break; default: DBG("to unrecognized state\n"); break; } if (rtOpts->displayStats) displayStats(rtOpts, ptpClock); }
AlprFullDetails AlprImpl::recognizeFullDetails(cv::Mat img, std::vector<cv::Rect> regionsOfInterest) { timespec startTime; getTimeMonotonic(&startTime); AlprFullDetails response; response.results.epoch_time = getEpochTimeMs(); response.results.img_width = img.cols; response.results.img_height = img.rows; for (unsigned int i = 0; i < regionsOfInterest.size(); i++) { response.results.regionsOfInterest.push_back(AlprRegionOfInterest(regionsOfInterest[i].x, regionsOfInterest[i].y, regionsOfInterest[i].width, regionsOfInterest[i].height)); } if (!img.data) { // Invalid image if (this->config->debugGeneral) std::cerr << "Invalid image" << std::endl; return response; } // Convert image to grayscale if required Mat grayImg = img; if (img.channels() > 2) cvtColor( img, grayImg, CV_BGR2GRAY ); // Prewarp the image and ROIs if configured] std::vector<cv::Rect> warpedRegionsOfInterest = regionsOfInterest; // Warp the image if prewarp is provided grayImg = prewarp->warpImage(grayImg); warpedRegionsOfInterest = prewarp->projectRects(regionsOfInterest, grayImg.cols, grayImg.rows, false); vector<PlateRegion> warpedPlateRegions; // Find all the candidate regions if (config->skipDetection == false) { warpedPlateRegions = plateDetector->detect(grayImg, warpedRegionsOfInterest); } else { // They have elected to skip plate detection. Instead, return a list of plate regions // based on their regions of interest for (unsigned int i = 0; i < warpedRegionsOfInterest.size(); i++) { PlateRegion pr; pr.rect = cv::Rect(warpedRegionsOfInterest[i]); warpedPlateRegions.push_back(pr); } } queue<PlateRegion> plateQueue; for (unsigned int i = 0; i < warpedPlateRegions.size(); i++) plateQueue.push(warpedPlateRegions[i]); int platecount = 0; while(!plateQueue.empty()) { PlateRegion plateRegion = plateQueue.front(); plateQueue.pop(); PipelineData pipeline_data(img, grayImg, plateRegion.rect, config); timespec platestarttime; getTimeMonotonic(&platestarttime); LicensePlateCandidate lp(&pipeline_data); lp.recognize(); bool plateDetected = false; if (!pipeline_data.disqualified) { AlprPlateResult plateResult; plateResult.region = defaultRegion; plateResult.regionConfidence = 0; plateResult.plate_index = platecount++; // If using prewarp, remap the plate corners to the original image vector<Point2f> cornerPoints = pipeline_data.plate_corners; cornerPoints = prewarp->projectPoints(cornerPoints, true); for (int pointidx = 0; pointidx < 4; pointidx++) { plateResult.plate_points[pointidx].x = (int) cornerPoints[pointidx].x; plateResult.plate_points[pointidx].y = (int) cornerPoints[pointidx].y; } if (detectRegion) { stateIdentifier->recognize(&pipeline_data); if (pipeline_data.region_confidence > 0) { plateResult.region = pipeline_data.region_code; plateResult.regionConfidence = (int) pipeline_data.region_confidence; } } if (plateResult.region.length() > 0 && ocr->postProcessor.regionIsValid(plateResult.region) == false) { std::cerr << "Invalid pattern provided: " << plateResult.region << std::endl; std::cerr << "Valid patterns are located in the " << config->country << ".patterns file" << std::endl; } ocr->performOCR(&pipeline_data); ocr->postProcessor.analyze(plateResult.region, topN); timespec resultsStartTime; getTimeMonotonic(&resultsStartTime); const vector<PPResult> ppResults = ocr->postProcessor.getResults(); int bestPlateIndex = 0; cv::Mat charTransformMatrix = getCharacterTransformMatrix(&pipeline_data); for (unsigned int pp = 0; pp < ppResults.size(); pp++) { // Set our "best plate" match to either the first entry, or the first entry with a postprocessor template match if (bestPlateIndex == 0 && ppResults[pp].matchesTemplate) bestPlateIndex = plateResult.topNPlates.size(); AlprPlate aplate; aplate.characters = ppResults[pp].letters; aplate.overall_confidence = ppResults[pp].totalscore; aplate.matches_template = ppResults[pp].matchesTemplate; // Grab detailed results for each character for (unsigned int c_idx = 0; c_idx < ppResults[pp].letter_details.size(); c_idx++) { AlprChar character_details; character_details.character = ppResults[pp].letter_details[c_idx].letter; character_details.confidence = ppResults[pp].letter_details[c_idx].totalscore; cv::Rect char_rect = pipeline_data.charRegions[ppResults[pp].letter_details[c_idx].charposition]; std::vector<AlprCoordinate> charpoints = getCharacterPoints(char_rect, charTransformMatrix ); for (int cpt = 0; cpt < 4; cpt++) character_details.corners[cpt] = charpoints[cpt]; aplate.character_details.push_back(character_details); } plateResult.topNPlates.push_back(aplate); } if (plateResult.topNPlates.size() > bestPlateIndex) { AlprPlate bestPlate; bestPlate.characters = plateResult.topNPlates[bestPlateIndex].characters; bestPlate.matches_template = plateResult.topNPlates[bestPlateIndex].matches_template; bestPlate.overall_confidence = plateResult.topNPlates[bestPlateIndex].overall_confidence; bestPlate.character_details = plateResult.topNPlates[bestPlateIndex].character_details; plateResult.bestPlate = bestPlate; } timespec plateEndTime; getTimeMonotonic(&plateEndTime); plateResult.processing_time_ms = diffclock(platestarttime, plateEndTime); if (config->debugTiming) { cout << "Result Generation Time: " << diffclock(resultsStartTime, plateEndTime) << "ms." << endl; } if (plateResult.topNPlates.size() > 0) { plateDetected = true; response.results.plates.push_back(plateResult); } } if (!plateDetected) { // Not a valid plate // Check if this plate has any children, if so, send them back up for processing for (unsigned int childidx = 0; childidx < plateRegion.children.size(); childidx++) { plateQueue.push(plateRegion.children[childidx]); } } } // Unwarp plate regions if necessary prewarp->projectPlateRegions(warpedPlateRegions, grayImg.cols, grayImg.rows, true); response.plateRegions = warpedPlateRegions; timespec endTime; getTimeMonotonic(&endTime); response.results.total_processing_time_ms = diffclock(startTime, endTime); if (config->debugTiming) { cout << "Total Time to process image: " << diffclock(startTime, endTime) << "ms." << endl; } if (config->debugGeneral && config->debugShowImages) { for (unsigned int i = 0; i < regionsOfInterest.size(); i++) { rectangle(img, regionsOfInterest[i], Scalar(0,255,0), 2); } for (unsigned int i = 0; i < response.plateRegions.size(); i++) { rectangle(img, response.plateRegions[i].rect, Scalar(0, 0, 255), 2); } for (unsigned int i = 0; i < response.results.plates.size(); i++) { // Draw a box around the license plate for (int z = 0; z < 4; z++) { AlprCoordinate* coords = response.results.plates[i].plate_points; Point p1(coords[z].x, coords[z].y); Point p2(coords[(z + 1) % 4].x, coords[(z + 1) % 4].y); line(img, p1, p2, Scalar(255,0,255), 2); } // Draw the individual character boxes for (int q = 0; q < response.results.plates[i].bestPlate.character_details.size(); q++) { AlprChar details = response.results.plates[i].bestPlate.character_details[q]; line(img, Point(details.corners[0].x, details.corners[0].y), Point(details.corners[1].x, details.corners[1].y), Scalar(0,255,0), 1); line(img, Point(details.corners[1].x, details.corners[1].y), Point(details.corners[2].x, details.corners[2].y), Scalar(0,255,0), 1); line(img, Point(details.corners[2].x, details.corners[2].y), Point(details.corners[3].x, details.corners[3].y), Scalar(0,255,0), 1); line(img, Point(details.corners[3].x, details.corners[3].y), Point(details.corners[0].x, details.corners[0].y), Scalar(0,255,0), 1); } } displayImage(config, "Main Image", img); // Sleep 1ms sleep_ms(1); } if (config->debugPauseOnFrame) { // Pause indefinitely until they press a key while ((char) cv::waitKey(50) == -1) {} } return response; }
void AngleBendContrib::getGrad(double *pos,double *grad) const { PRECONDITION(dp_forceField,"no owner"); PRECONDITION(pos,"bad vector"); PRECONDITION(grad,"bad vector"); double dist1=this->dp_forceField->distance(this->d_at1Idx,this->d_at2Idx,pos); double dist2=this->dp_forceField->distance(this->d_at2Idx,this->d_at3Idx,pos); //std::cout << "\tAngle("<<this->d_at1Idx<<","<<this->d_at2Idx<<","<<this->d_at3Idx<<") " << dist1 << " " << dist2 << std::endl; RDGeom::Point3D p1(pos[3*this->d_at1Idx], pos[3*this->d_at1Idx+1], pos[3*this->d_at1Idx+2]); RDGeom::Point3D p2(pos[3*this->d_at2Idx], pos[3*this->d_at2Idx+1], pos[3*this->d_at2Idx+2]); RDGeom::Point3D p3(pos[3*this->d_at3Idx], pos[3*this->d_at3Idx+1], pos[3*this->d_at3Idx+2]); double *g1=&(grad[3*this->d_at1Idx]); double *g2=&(grad[3*this->d_at2Idx]); double *g3=&(grad[3*this->d_at3Idx]); RDGeom::Point3D p12=p1-p2; RDGeom::Point3D p32=p3-p2; double cosTheta = p12.dotProduct(p32)/(dist1*dist2); double sinTheta = std::max(sqrt(1.0-cosTheta*cosTheta),1e-8); //std::cerr << "GRAD: " << cosTheta << " (" << acos(cosTheta)<< "), "; //std::cerr << sinTheta << " (" << asin(sinTheta)<< ")" << std::endl; // use the chain rule: // dE/dx = dE/dTheta * dTheta/dx // dE/dTheta is independent of cartesians: double dE_dTheta=getThetaDeriv(cosTheta,sinTheta); // ------- // dTheta/dx is trickier: double dCos_dS1=1./dist1 * (p32.x/dist2 - cosTheta*p12.x/dist1); double dCos_dS2=1./dist1 * (p32.y/dist2 - cosTheta*p12.y/dist1); double dCos_dS3=1./dist1 * (p32.z/dist2 - cosTheta*p12.z/dist1); double dCos_dS4=1./dist2 * (p12.x/dist1 - cosTheta*p32.x/dist2); double dCos_dS5=1./dist2 * (p12.y/dist1 - cosTheta*p32.y/dist2); double dCos_dS6=1./dist2 * (p12.z/dist1 - cosTheta*p32.z/dist2); g1[0] += dE_dTheta*dCos_dS1/(-sinTheta); g1[1] += dE_dTheta*dCos_dS2/(-sinTheta); g1[2] += dE_dTheta*dCos_dS3/(-sinTheta); g2[0] += dE_dTheta*(-dCos_dS1 - dCos_dS4)/(-sinTheta); g2[1] += dE_dTheta*(-dCos_dS2 - dCos_dS5)/(-sinTheta); g2[2] += dE_dTheta*(-dCos_dS3 - dCos_dS6)/(-sinTheta); g3[0] += dE_dTheta*dCos_dS4/(-sinTheta); g3[1] += dE_dTheta*dCos_dS5/(-sinTheta); g3[2] += dE_dTheta*dCos_dS6/(-sinTheta); }
int run_main (int, ACE_TCHAR *[]) { ACE_START_TEST (ACE_TEXT ("Bound_Ptr_Test")); // ========================================================================= // The following test uses the ACE_Strong_Bound_Ptr in a single // thread of control, hence we use the ACE_Null_Mutex ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) performing synchronous test...\n"))); Parent *parent1 = 0; ACE_NEW_RETURN (parent1, Parent, -1); ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p8; { // Must get the pointer from the parent object's weak_self_ member. ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p(parent1->weak_self_); ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p1(p); ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p2(p); ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p3(p); ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p4(p); ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p5 = p2; ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p6 = p3; ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p7(p1); p8 = p2; p->child_->do_something (); } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Parent instance count is %d, expecting 0\n"), Parent::instance_count_)); if (Parent::instance_count_ != 0) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) parent instance count not 0...\n")), -1); } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Child instance count is %d, expecting 0\n"), Child::instance_count_)); if (Child::instance_count_ != 0) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) child instance count not 0...\n")), -1); } // Weak pointer should now be set to null. if(!p8.null ()) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) p8 not nill...\n")), -1); } Printer *printer1 = 0; ACE_NEW_RETURN (printer1, Printer ("I am printer 1"), -1); ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r9; { ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r(printer1); ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r1(r); ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r2(r); ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r3(r); ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r4(r); ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r5 = r2; ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r6 = r1; ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r7(r1); ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r8 = r2; r9 = r3; r9->print (); } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Printer instance count is %d, expecting 0\n"), Printer::instance_count_)); if (Printer::instance_count_ != 0) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Printer instance count not 0...\n")), -1); } // Weak pointer should now be set to null. if (!r9.null ()) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) r9 not nill...\n")), -1); } #if defined (ACE_HAS_THREADS) // ========================================================================= // The following test uses the ACE_Strong_Bound_Ptr in multiple // threads of control. ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) performing asynchronous test...\n"))); Scheduler *scheduler_ptr = 0; // Create active objects.. ACE_NEW_RETURN (scheduler_ptr, Scheduler (), -1); ACE_Strong_Bound_Ptr<Scheduler, ACE_Null_Mutex> scheduler(scheduler_ptr); if (scheduler->open () == -1) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Scheduler open failed...\n")), -1); } { Printer *printer2 = 0; ACE_NEW_RETURN (printer2, Printer ("I am printer 2"), -1); // Ownership is transferred from the auto_ptr to the strong pointer. auto_ptr<Printer> a (printer2); Printer_var r (a); for (int i = 0; i < n_loops; i++) // Spawn off the methods, which run in a separate thread as // active object invocations. scheduler->print (r); } // Close things down. scheduler->end (); scheduler->wait (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Printer instance count is %d, expecting 0\n"), Printer::instance_count_)); if (Printer::instance_count_ != 0) return -1; #endif /* ACE_HAS_THREADS */ ACE_END_TEST; return 0; }
/* * Dump TCP statistics structure. */ void tcp_stats(u_long off, char *name) { struct tcpstat tcpstat; if (off == 0) return; printf("%s:\n", name); kread(off, (char *)&tcpstat, sizeof (tcpstat)); #define p(f, m) if (tcpstat.f || sflag <= 1) \ printf(m, tcpstat.f, plural(tcpstat.f)) #define p1(f, m) if (tcpstat.f || sflag <= 1) \ printf(m, tcpstat.f) #define p2(f1, f2, m) if (tcpstat.f1 || tcpstat.f2 || sflag <= 1) \ printf(m, tcpstat.f1, plural(tcpstat.f1), tcpstat.f2, plural(tcpstat.f2)) #define p2a(f1, f2, m) if (tcpstat.f1 || tcpstat.f2 || sflag <= 1) \ printf(m, tcpstat.f1, plural(tcpstat.f1), tcpstat.f2) #define p3(f, m) if (tcpstat.f || sflag <= 1) \ printf(m, tcpstat.f, plurales(tcpstat.f)) p(tcps_sndtotal, "\t%u packet%s sent\n"); p2(tcps_sndpack,tcps_sndbyte, "\t\t%u data packet%s (%qd byte%s)\n"); p2(tcps_sndrexmitpack, tcps_sndrexmitbyte, "\t\t%u data packet%s (%qd byte%s) retransmitted\n"); p(tcps_sndrexmitfast, "\t\t%qd fast retransmitted packet%s\n"); p2a(tcps_sndacks, tcps_delack, "\t\t%u ack-only packet%s (%u delayed)\n"); p(tcps_sndurg, "\t\t%u URG only packet%s\n"); p(tcps_sndprobe, "\t\t%u window probe packet%s\n"); p(tcps_sndwinup, "\t\t%u window update packet%s\n"); p(tcps_sndctrl, "\t\t%u control packet%s\n"); p(tcps_outhwcsum, "\t\t%u packet%s hardware-checksummed\n"); p(tcps_rcvtotal, "\t%u packet%s received\n"); p2(tcps_rcvackpack, tcps_rcvackbyte, "\t\t%u ack%s (for %qd byte%s)\n"); p(tcps_rcvdupack, "\t\t%u duplicate ack%s\n"); p(tcps_rcvacktoomuch, "\t\t%u ack%s for unsent data\n"); p2(tcps_rcvpack, tcps_rcvbyte, "\t\t%u packet%s (%qu byte%s) received in-sequence\n"); p2(tcps_rcvduppack, tcps_rcvdupbyte, "\t\t%u completely duplicate packet%s (%qd byte%s)\n"); p(tcps_pawsdrop, "\t\t%u old duplicate packet%s\n"); p2(tcps_rcvpartduppack, tcps_rcvpartdupbyte, "\t\t%u packet%s with some duplicate data (%qd byte%s duplicated)\n"); p2(tcps_rcvoopack, tcps_rcvoobyte, "\t\t%u out-of-order packet%s (%qd byte%s)\n"); p2(tcps_rcvpackafterwin, tcps_rcvbyteafterwin, "\t\t%u packet%s (%qd byte%s) of data after window\n"); p(tcps_rcvwinprobe, "\t\t%u window probe%s\n"); p(tcps_rcvwinupd, "\t\t%u window update packet%s\n"); p(tcps_rcvafterclose, "\t\t%u packet%s received after close\n"); p(tcps_rcvbadsum, "\t\t%u discarded for bad checksum%s\n"); p(tcps_rcvbadoff, "\t\t%u discarded for bad header offset field%s\n"); p1(tcps_rcvshort, "\t\t%u discarded because packet too short\n"); p1(tcps_rcvnosec, "\t\t%u discarded for missing IPsec protection\n"); p1(tcps_rcvmemdrop, "\t\t%u discarded due to memory shortage\n"); p(tcps_inhwcsum, "\t\t%u packet%s hardware-checksummed\n"); p(tcps_rcvbadsig, "\t\t%u bad/missing md5 checksum%s\n"); p(tcps_rcvgoodsig, "\t\t%qd good md5 checksum%s\n"); p(tcps_connattempt, "\t%u connection request%s\n"); p(tcps_accepts, "\t%u connection accept%s\n"); p(tcps_connects, "\t%u connection%s established (including accepts)\n"); p2(tcps_closed, tcps_drops, "\t%u connection%s closed (including %u drop%s)\n"); p(tcps_conndrained, "\t%qd connection%s drained\n"); p(tcps_conndrops, "\t%u embryonic connection%s dropped\n"); p2(tcps_rttupdated, tcps_segstimed, "\t%u segment%s updated rtt (of %u attempt%s)\n"); p(tcps_rexmttimeo, "\t%u retransmit timeout%s\n"); p(tcps_timeoutdrop, "\t\t%u connection%s dropped by rexmit timeout\n"); p(tcps_persisttimeo, "\t%u persist timeout%s\n"); p(tcps_keeptimeo, "\t%u keepalive timeout%s\n"); p(tcps_keepprobe, "\t\t%u keepalive probe%s sent\n"); p(tcps_keepdrops, "\t\t%u connection%s dropped by keepalive\n"); p(tcps_predack, "\t%u correct ACK header prediction%s\n"); p(tcps_preddat, "\t%u correct data packet header prediction%s\n"); p3(tcps_pcbhashmiss, "\t%u PCB cache miss%s\n"); p(tcps_ecn_accepts, "\t%u ECN connection%s accepted\n"); p(tcps_ecn_rcvece, "\t\t%u ECE packet%s received\n"); p(tcps_ecn_rcvcwr, "\t\t%u CWR packet%s received\n"); p(tcps_ecn_rcvce, "\t\t%u CE packet%s received\n"); p(tcps_ecn_sndect, "\t\t%u ECT packet%s sent\n"); p(tcps_ecn_sndece, "\t\t%u ECE packet%s sent\n"); p(tcps_ecn_sndcwr, "\t\t%u CWR packet%s sent\n"); p1(tcps_cwr_frecovery, "\t\t\tcwr by fastrecovery: %u\n"); p1(tcps_cwr_timeout, "\t\t\tcwr by timeout: %u\n"); p1(tcps_cwr_ecn, "\t\t\tcwr by ecn: %u\n"); p(tcps_badsyn, "\t%u bad connection attempt%s\n"); p1(tcps_sc_added, "\t%qd SYN cache entries added\n"); p(tcps_sc_collisions, "\t\t%qd hash collision%s\n"); p1(tcps_sc_completed, "\t\t%qd completed\n"); p1(tcps_sc_aborted, "\t\t%qd aborted (no space to build PCB)\n"); p1(tcps_sc_timed_out, "\t\t%qd timed out\n"); p1(tcps_sc_overflowed, "\t\t%qd dropped due to overflow\n"); p1(tcps_sc_bucketoverflow, "\t\t%qd dropped due to bucket overflow\n"); p1(tcps_sc_reset, "\t\t%qd dropped due to RST\n"); p1(tcps_sc_unreach, "\t\t%qd dropped due to ICMP unreachable\n"); p(tcps_sc_retransmitted, "\t%qd SYN,ACK%s retransmitted\n"); p(tcps_sc_dupesyn, "\t%qd duplicate SYN%s received for entries " "already in the cache\n"); p(tcps_sc_dropped, "\t%qd SYN%s dropped (no route or no space)\n"); #undef p #undef p1 #undef p2 #undef p2a #undef p3 }
int main(int argc, char **argv) { plan_tests(41); FlatPoint p1(fixed_one, fixed_one); FlatPoint p2(fixed_one, fixed_two); FlatPoint p3(fixed(3), fixed_ten); // test cross() ok1(equals(p1.CrossProduct(p2), 1)); ok1(equals(p2.CrossProduct(p1), -1)); ok1(equals(p1.CrossProduct(p3), 7)); ok1(equals(p3.CrossProduct(p1), -7)); ok1(equals(p2.CrossProduct(p3), 4)); ok1(equals(p3.CrossProduct(p2), -4)); // test mul_y() p2.MultiplyY(fixed_two); ok1(equals(p2.x, 1)); ok1(equals(p2.y, 4)); // test sub() p2.Subtract(p1); ok1(equals(p2.x, 0)); ok1(equals(p2.y, 3)); // test add() p2.Add(p3); ok1(equals(p2.x, 3)); ok1(equals(p2.y, 13)); // test rotate() p2.Rotate(Angle::Degrees(fixed(-90))); ok1(equals(p2.x, 13)); ok1(equals(p2.y, -3)); p2.Rotate(Angle::Degrees(fixed(45))); p2.Rotate(Angle::Degrees(fixed(45))); ok1(equals(p2.x, 3)); ok1(equals(p2.y, 13)); // test d() ok1(equals(p2.Distance(p3), 3)); ok1(equals(p3.Distance(p2), 3)); // test mag_sq() ok1(equals(p1.MagnitudeSquared(), 2)); ok1(equals(p2.MagnitudeSquared(), 178)); ok1(equals(p3.MagnitudeSquared(), 109)); // test mag() ok1(equals(p1.Magnitude(), 1.4142135623730950488016887242097)); ok1(equals(p2.Magnitude(), 13.341664064126333712489436272508)); ok1(equals(p3.Magnitude(), 10.440306508910550179757754022548)); // test dot() ok1(equals(p1.DotProduct(p2), 16)); ok1(equals(p2.DotProduct(p1), 16)); ok1(equals(p1.DotProduct(p3), 13)); ok1(equals(p3.DotProduct(p1), 13)); ok1(equals(p2.DotProduct(p3), 139)); ok1(equals(p3.DotProduct(p2), 139)); // test == ok1(p1 == p1); ok1(p2 == p2); ok1(p3 == p3); /* // Test #2 fails due to floating point inaccuracies ok1(p1 == FlatPoint(fixed_one, fixed_one)); ok1(p2 == FlatPoint(fixed(3), fixed(13))); ok1(p3 == FlatPoint(fixed(3), fixed_ten)); */ // test * p2 = p3 * fixed(1.5); ok1(equals(p2.x, 4.5)); ok1(equals(p2.y, 15)); // test + p2 = p1 + p3; ok1(equals(p2.x, 4)); ok1(equals(p2.y, 11)); // test += p2 += p1; ok1(equals(p2.x, 5)); ok1(equals(p2.y, 12)); // test - p2 = p3 - p1; ok1(equals(p2.x, 2)); ok1(equals(p2.y, 9)); return exit_status(); }
void EnemyList::checkCollisions(PlayerProjectiles& playerProjectiles) { for (unsigned int i = 0; i < enemyList.size(); i++) { Point enemy(enemyList[i].getCompX(), enemyList[i].getCompY()); for (unsigned int j = 0; j < playerProjectiles.getSize(); j++) { Bullet* b = playerProjectiles.getBullet(j); Point bulPoint(b->getX(), b->getY()); if (enemyList[i].enemyType == 0 && Collision().checkCollision(playerProjectiles.getVector()[j].box, enemy, 0.97)) { b->destroy(); enemyList[i].enemyHP--; Explosion explosion; if (enemyList[i].enemyHP <= 0) { enemyList[i].destroyed = true; if (enemyList[i].enemyType == 0) { explosion = Explosion(enemyList[i].compX, enemyList[i].compY, 1, explosionTextureID); } else { explosion = Explosion(enemyList[i].compX, enemyList[i].compY, 2, explosionTextureID); } explosionList.addExplosion(explosion); } } else if (enemyList[i].enemyType == 1 && Collision().isIntersect(enemyList[i].box, enemy, b->box, bulPoint, 28, minTransDist)) { b->destroy(); enemyList[i].enemyHP--; if (enemyList[i].enemyHP <= 0) { enemyList[i].destroyed = true; Explosion explosion(enemyList[i].compX, enemyList[i].compY, 1, explosionTextureID); explosionList.addExplosion(explosion); } } } for (unsigned int j = 0; j < enemyList.size(); j++) { Point p2(enemyList[j].getCompX(), enemyList[j].getCompY()); if (i != j && Collision().isIntersect(enemyList[i].box, enemy, enemyList[j].box, p2, 28, minTransDist)) { if (enemyList[i].enemyType == 1) { enemyList[j].setMinTransDist(minTransDist.pointX, minTransDist.pointY); } else if (enemyList[j].enemyType == 1) { enemyList[i].setMinTransDist(minTransDist.pointX, minTransDist.pointY); } else { enemyList[i].setMinTransDist(minTransDist.pointX * 0.5, minTransDist.pointY * 0.5); enemyList[j].setMinTransDist(-minTransDist.pointX * 0.5, -minTransDist.pointY * 0.5); } } } Point playerPos(playerShipX, playerShipY); //std::cout << playerPos.pointX << "\t" << playerPos.pointY << "\t" << enemy.pointX << "\t" << enemy.pointY << std::endl; BoundingQuad lineBox(playerPos, playerPos, enemy, enemy); bool result = true; for (unsigned int j = 0; j < asteroidMapListRef->asteroidField.size(); j++) { Point p2(asteroidMapListRef->asteroidField[j].getRoidX(), asteroidMapListRef->asteroidField[j].getRoidY()); if (Collision().isIntersect(enemyList[i].box, enemy, asteroidMapListRef->asteroidField[j].box, p2, 28, minTransDist)) { enemyList[i].setMinTransDist(minTransDist.pointX * 2, minTransDist.pointY * 2); enemyList[i].turnAround(); } if (!Collision().hasLineOfSight(enemy, playerPos, lineBox, asteroidMapListRef->asteroidField[j].box, p2, 28)) { result = false; } } enemyList[i].setLOS(result); } for (unsigned int i = 0; i < playerProjectiles.getSize(); i++) { Bullet* b = playerProjectiles.getBullet(i); Point p1(b->getX(), b->getY()); for (unsigned int j = 0; j < asteroidMapListRef->asteroidField.size(); j++) { Point p2(asteroidMapListRef->asteroidField[j].getRoidX(), asteroidMapListRef->asteroidField[j].getRoidY()); if (Collision().isIntersect(b->box, p1, asteroidMapListRef->asteroidField[j].box, p2, 40, minTransDist)) { Explosion explosion(b->box.pointsN[2].pointX, b->box.pointsN[2].pointY, 0.3, explosionTextureID); explosionList.addExplosion(explosion); b->destroyed = true; } } } }
void Enemy_Avatar_Wander_Character_Role::update(Area_Manager *area) { if (al_get_time() >= next_check) { next_check = al_get_time() + (General::rand()%1000)/1000.0*5.0 + 5.0; const float radius = 200.0f; Map_Entity *player = area->get_entity(0); int layer = player->get_layer(); General::Point<float> player_pos = player->get_position(); Area_Loop *loop = GET_AREA_LOOP; if (!player->input_is_disabled() && layer == entity->get_layer() && !area->point_is_in_no_enemy_zone(player_pos.x, player_pos.y) && !area->get_in_speech_loop() && (!loop || loop->battle_event_is_done()) && loop->get_num_jumping() == 0) { General::Point<float> this_pos = entity->get_position(); if (General::distance(player_pos.x, player_pos.y, this_pos.x, this_pos.y) <= radius) { float dx = player_pos.x - this_pos.x; float dy = player_pos.y - this_pos.y; float angle1 = atan2(dy, dx) + M_PI / 2.0f; float angle2 = angle1 + M_PI; General::Point<float> pp1( player_pos.x + cos(angle1) * General::TILE_SIZE/2, player_pos.y + sin(angle1) * General::TILE_SIZE/2 ); General::Point<float> pp2( player_pos.x + cos(angle2) * General::TILE_SIZE/2, player_pos.y + sin(angle2) * General::TILE_SIZE/2 ); General::Point<float> tp1( this_pos.x + cos(angle1) * General::TILE_SIZE/2, this_pos.y + sin(angle1) * General::TILE_SIZE/2 ); General::Point<float> tp2( this_pos.x + cos(angle2) * General::TILE_SIZE/2, this_pos.y + sin(angle2) * General::TILE_SIZE/2 ); std::vector< General::Line<float> > *lines = area->get_collision_lines(); bool collision = false; for (size_t i = 0; i < lines[layer].size(); i++) { General::Point<float> p1(lines[layer][i].x1, lines[layer][i].y1); General::Point<float> p2(lines[layer][i].x2, lines[layer][i].y2); if (checkcoll_line_line(&pp1, &tp1, &p1, &p2, NULL)) { collision = true; break; } if (checkcoll_line_line(&pp2, &tp2, &p1, &p2, NULL)) { collision = true; break; } } if (!collision) { Battle_Event_Type type = (Battle_Event_Type)(General::rand() % 3); float *inputs = player->get_inputs(); player->set_panning_to_entity(entity->get_id()); player->set_input_disabled(true); if (type != BATTLE_EVENT_SIGHTED && (inputs[Map_Entity::X] != 0.0f || inputs[Map_Entity::Y] != 0.0f)) { General::Direction d = player->get_direction(); float a; if (d == General::DIR_N) { player->get_animation_set()->set_sub_animation("trip-up"); a = M_PI / 2; } else if (d == General::DIR_S) { player->get_animation_set()->set_sub_animation("trip-down"); a = M_PI * 3 / 2; } else if (d == General::DIR_E) { player->get_animation_set()->set_sub_animation("trip"); a = M_PI; } else { player->get_animation_set()->set_sub_animation("trip"); a = 0; } a += ((General::rand()%1000)/1000.0f)*M_PI/3 - M_PI/6; player->get_animation_set()->reset(); if (type == BATTLE_EVENT_TRIPPED) { engine->play_sample("sfx/trip.ogg"); } else if (type == BATTLE_EVENT_SLIPPED) { engine->play_sample("sfx/slip.ogg"); lua_State *stack = area->get_lua_state(); Lua::call_lua(stack, "toss_banana", "iddd>", layer, player_pos.x, player_pos.y, a); } } else { engine->play_sample("sfx/enemy_alerted.ogg"); player->update_direction(false); } GET_AREA_LOOP->set_battle_was_event(type); entity->kamikaze(this_pos.x + dx * 0.9f, this_pos.y + dy * 0.9f); return; } } } } Wander_Character_Role::update(area); }
void drawRect(cv::Mat image,cv::Rect rect) { cv::Point p1(rect.x,rect.y); cv::Point p2(rect.x+rect.width,rect.y+rect.height); cv::rectangle(image,p1,p2,cv::Scalar(0,255,0),1); }
void test_RT() { typedef RT Cls; // _test_cls_regular_3( Cls() ); typedef traits::Bare_point Point; typedef traits::Weighted_point Weighted_point; typedef typename Cls::Vertex_handle Vertex_handle; typedef typename Cls::Cell_handle Cell_handle; typedef typename Cls::Facet Facet; typedef typename Cls::Edge Edge; typedef std::list<Weighted_point> list_point; typedef typename Cls::Finite_cells_iterator Finite_cells_iterator; // temporary version int n, m; int count = 0; // For dimension 0, we need to check that the point of highest weight is the // one that finally ends up in the vertex. std::cout << " test dimension 0 " << std::endl; Cls T0; T0.insert(Weighted_point( Point (0,0,0), 0) ); T0.insert(Weighted_point( Point (0,0,0), 1) ); T0.insert(Weighted_point( Point (0,0,0), -1) ); assert(T0.dimension() == 0); assert(T0.number_of_vertices() == 1); assert(T0.finite_vertices_begin()->point().weight() == 1); std::cout << " test dimension 1 " << std::endl; Cls T1; std::cout << " number of inserted points : " ; Weighted_point p[5]; for ( m=0; m<5; m++) { if ( (m%2)== 0 ) p[m] = Weighted_point( Point( 2*m,0,0 ), 2 ); else p[m] = Weighted_point( Point( -2*m+1,0,0 ), 2 ); T1.insert( p[m] ); count++; if (count <10) std::cout << count << '\b' ; else if (count < 100) std::cout << count << '\b' << '\b' ; else std::cout << count << '\b' << '\b' << '\b' ; std::cout.flush(); } assert( T1.is_valid() ); std::cout << std::endl << " number of vertices : " << T1.number_of_vertices() << std::endl; std::cout << " number of inserted points : " ; Weighted_point q[5]; for ( m=0; m<5; m++) { if ( (m%2)== 0 ) q[m] = Weighted_point( Point( 2*m+1,0,0 ), 5 ); else q[m] = Weighted_point( Point( -2*m+1,0,0 ), 5 ); T1.insert( q[m] ); count++; if (count <10) std::cout << count << '\b' ; else if (count < 100) std::cout << count << '\b' << '\b' ; else std::cout << count << '\b' << '\b' << '\b' ; std::cout.flush(); } assert( T1.is_valid() ); std::cout << std::endl << " number of vertices : " << T1.number_of_vertices() << std::endl; std::cout << " number of inserted points : " ; Weighted_point r[10]; for ( m=0; m<10; m++) { if ( (m%2)== 0 ) r[m] = Weighted_point( Point( m,0,0 ), 1 ); else r[m] = Weighted_point( Point( -m,0,0 ), 1 ); T1.insert( r[m] ); count++; if (count <10) std::cout << count << '\b' ; else if (count < 100) std::cout << count << '\b' << '\b' ; else std::cout << count << '\b' << '\b' << '\b' ; std::cout.flush(); } assert( T1.is_valid() ); std::cout << std::endl << " number of vertices : " << T1.number_of_vertices() << std::endl; assert( T1.dimension()==1 ); // The following is distilled from a bug report by Wulue Zhao // ([email protected]), a student of Tamal Dey. Point pt0(0,0,0); Point pt1( 1,0,0), pt2(2,0,0), pt3(3,0,0); Point pt4(-1,0,0), pt5(-2,0,0), pt6(-3,0,0); Weighted_point wp0(pt0,10.0); Weighted_point wp1(pt1,0.0), wp2(pt2,0.0), wp3(pt3,0.0); Weighted_point wp4(pt4,0.0), wp5(pt5,0.0), wp6(pt6,0.0); Cls T11; T11.insert(wp0); T11.insert(wp1); T11.insert(wp2); T11.insert(wp3); T11.insert(wp4); T11.insert(wp5); T11.insert(wp6); assert(T11.is_valid()); // And another distilled bug report from the same guy. { Point p1(-0.07, 0.04, 0.04); Point p2(0.09, 0.04, 0.04); Point p3(0.09, -0.05, 0.04); Point p4(0.05, -0.05, 0.04); Point p5(0.05, 0.0, 0.04); Point p6(-0.07, 0.0, 0.04); Point p7(-0.07, 0.04, -0.04); Point p8(0.09, 0.04, -0.04); Point p9(0.09, -0.05, -0.04); Point p10(0.05, -0.05, -0.04); Point p11(0.05, 0.0, -0.04); Point p12(-0.07, 0.0, -0.04); Weighted_point wp1(p1,0); Weighted_point wp2(p2,0); Weighted_point wp3(p3,0); Weighted_point wp4(p4,0); Weighted_point wp5(p5,0); Weighted_point wp6(p6,0); Weighted_point wp7(p7,0); Weighted_point wp8(p8,0); Weighted_point wp9(p9,0); Weighted_point wp10(p10,0); Weighted_point wp11(p11,0); Weighted_point wp12(p12,0); Weighted_point wp13(p3,0.3); // wp13 has the same coordinates with wp3 Cls T111; T111.insert(wp1); T111.insert(wp2); T111.insert(wp3); T111.insert(wp13); // it doesnot work inserting wp13 here T111.insert(wp4); T111.insert(wp5); T111.insert(wp6); T111.insert(wp7); T111.insert(wp8); T111.insert(wp9); T111.insert(wp10); T111.insert(wp11); T111.insert(wp12); assert(T111.is_valid()); } std::cout << " test dimension 2 " << std::endl; std::cout << " number of inserted points : " ; Cls T2; count = 0 ; int px=1, py=1; int qx=-1, qy=2; Weighted_point s[400]; for (m=0; m<10; m++) for (n=0; n<10; n++) { s[m+20*n] = Weighted_point( Point(m*px+n*qx, m*py+n*qy, 0), 1 ); T2.insert( s[m+20*n] ); count++; if (count <10) std::cout << count << '\b' ; else if (count < 100) std::cout << count << '\b' << '\b' ; else std::cout << count << '\b' << '\b' << '\b' ; std::cout.flush(); } for (m=10; m<20; m++) for (n=0; n<10; n++) { s[m+20*n] = Weighted_point( Point(m*px+n*qx, m*py+n*qy, 0), -1 ); T2.insert( s[m+20*n] ); count++; if (count <10) std::cout << count << '\b' ; else if (count < 100) std::cout << count << '\b' << '\b' ; else std::cout << count << '\b' << '\b' << '\b' ; std::cout.flush(); } for (m=0; m<10; m++) for (n=10; n<20; n++) { s[m+20*n] = Weighted_point( Point(m*px+n*qx, m*py+n*qy, 0), -2 ); T2.insert( s[m+20*n] ); count++; if (count <10) std::cout << count << '\b' ; else if (count < 100) std::cout << count << '\b' << '\b' ; else std::cout << count << '\b' << '\b' << '\b' ; std::cout.flush(); } for (m=10; m<20; m++) for (n=10; n<20; n++) { s[m+20*n] = Weighted_point( Point(m*px+n*qx, m*py+n*qy, 0), 5 ); T2.insert( s[m+20*n] ); count++; if (count <10) std::cout << count << '\b' ; else if (count < 100) std::cout << count << '\b' << '\b' ; else std::cout << count << '\b' << '\b' << '\b' ; std::cout.flush(); } std::cout << std::endl << " number of vertices : " << T2.number_of_vertices() << std::endl; assert( T2.dimension()==2 ); assert( T2.is_valid() ); // dimension 3 std::cout << " test dimension 3" << std::endl; Cls T; list_point lp; int a, b, d; for (a=0;a!=10;a++) // for (b=0;b!=10;b++) for (b=0;b!=5;b++) // for (d=0;d!=10;d++) for (d=0;d!=5;d++) lp.push_back(Weighted_point( Point(a*b-d*a + (a-b)*10 +a , a-b+d +5*b, a*a-d*d+b), a*b-a*d) ); list_point::iterator it; count = 0 ; std::cout << " number of inserted points : " ; for (it=lp.begin(); it!=lp.end(); ++it){ count++; T.insert(*it); if (count <10) std::cout << count << '\b' ; else if (count < 100) std::cout << count << '\b' << '\b' ; else if (count < 1000) std::cout << count << '\b' << '\b' << '\b' ; else std::cout << count << std::endl; std::cout.flush(); } std::cout << std::endl; std::cout << " number of vertices : " << T.number_of_vertices() << std::endl; assert(T.is_valid()); assert(T.dimension()==3); T.clear(); std::cout << " test iterator range insert" << std::endl; T.insert (lp.begin(), lp.end()); std::cout << " number of vertices : " << T.number_of_vertices() << std::endl; assert(T.is_valid()); assert(T.dimension()==3); //test nearest_power_vertex std::cout << " test nearest_power_vertex " << std::endl; Point pp1(0.0, 0.0, 0.0); Point pp2(1.0, 0.0, 0.0); Point pp3(0.0, 1.0, 0.0); Point pp4(0.0, 0.0, 1.0); Point pp5(1.0, 1.0, 0.0); Point pp6(0.0, 1.0, 1.0); Point pp7(1.0, 0.0, 1.0); Point pp8(1.0, 1.0, 1.0); Weighted_point wpp1(pp1, 1.0); Weighted_point wpp2(pp2, 2.0); Weighted_point wpp3(pp3, 1.0); Weighted_point wpp4(pp4, 4.0); Weighted_point wpp5(pp5, 1.0); Weighted_point wpp6(pp6, 1.0); Weighted_point wpp7(pp7, 1.0); Weighted_point wpp8(pp8, 8.0); Cls T3; T3.insert(wpp1); Vertex_handle v2 = T3.insert(wpp2); assert( T3.nearest_power_vertex(Point(0.5,0.5,0.5)) == v2); T3.insert(wpp3); Vertex_handle v4 = T3.insert(wpp4); assert( T3.nearest_power_vertex(Point(0.5,0.5,0.5)) == v4); T3.insert(wpp5); T3.insert(wpp6); T3.insert(wpp7); // Avoid inserting the same point twice, now that hidden points are handled, // insert (existing_point) returns Vertex_handle(). // T3.insert(wpp8); Vertex_handle v8 = T3.insert(wpp8); Point query(0.5,0.5,0.5); assert(T3.nearest_power_vertex(query) == v8); assert(T3.nearest_power_vertex(Weighted_point(query,1.0)) == v8 ); assert(T3.nearest_power_vertex_in_cell(query ,v8->cell()) == v8); // test dual std::cout << " test dual member functions" << std::endl; Finite_cells_iterator fcit = T3.finite_cells_begin(); for( ; fcit != T3.finite_cells_end(); ++fcit) { Point cc = T3.dual(fcit); Vertex_handle ncc = T3.nearest_power_vertex(cc); assert(fcit->has_vertex(ncc)); } // test Gabriel std::cout << " test is_Gabriel " << std::endl; Point q0(0.,0.,0.); Point q1(2.,0.,0.); Point q2(0.,2.,0.); Point q3(0.,0.,2.); Weighted_point wq0(q0,0.); Weighted_point wq1(q1,0.); Weighted_point wq2(q2,0.); Weighted_point wq3(q3,0.); Weighted_point wq01(q0,2.); Cls T4; Vertex_handle v0 = T4.insert(wq0); Vertex_handle v1 = T4.insert(wq1); v2 = T4.insert(wq2); Vertex_handle v3 = T4.insert(wq3); Cell_handle c; int i,j,k,l; assert(T4.is_facet(v0,v1,v2,c,j,k,l)); i = 6 - (j+k+l); Facet f = std::make_pair(c,i); assert(T4.is_Gabriel(c,i)); assert(T4.is_Gabriel(f)); assert(T4.is_facet(v1,v2,v3,c,j,k,l)); i = 6 - (j+k+l); assert(!T4.is_Gabriel(c,i)); assert(T4.is_edge(v0,v1,c,i,j)); assert(T4.is_Gabriel(c,i,j)); Edge e = make_triple(c,i,j); assert(T4.is_Gabriel(e)); assert(T4.is_edge(v2,v3,c,i,j)); assert(T4.is_Gabriel(c,i,j)); Vertex_handle v01 = T4.insert(wq01); (void) v01; // kill warning assert(T4.is_edge(v2,v3,c,i,j)); assert(!T4.is_Gabriel(c,i,j)); Weighted_point wwq0(q0,0.); Weighted_point wwq1(q1,0.); Weighted_point wwq2(q2,0.); Weighted_point wwq3(q3,5.); Cls T5; v0 = T5.insert(wwq0); v1 = T5.insert(wwq1); v2 = T5.insert(wwq2); v3 = T5.insert(wwq3); assert(T5.nearest_power_vertex(v3->point().point()) == v3); assert(T5.nearest_power_vertex(v0->point().point()) == v3); assert(T5.is_Gabriel(v3)); assert(!T5.is_Gabriel(v0)); }
QPointF core::RestrictedLineF::getCorrectedP2(const QPointF &p2) { switch(lineConstrain){ case RestrictedLineF::HorizontalLeft: if(p2.x() <= p1().x()){ return QPointF(p2.x(), p1().y()); }else{ return p1(); } case RestrictedLineF::HorizontalRight: if(p2.x() >= p1().x()){ return QPointF(p2.x(), p1().y()); }else{ return p1(); } case RestrictedLineF::Horizontal: return QPointF(p2.x(), p1().y()); case RestrictedLineF::VerticalUp: if(p2.y() <= p1().y()){ return QPointF(p1().x(), p2.y()); }else{ return p1(); } case RestrictedLineF::VerticalDown: if(p2.y() >= p1().y()){ return QPointF(p1().x(), p2.y()); }else{ return p1(); } case RestrictedLineF::Vertical: return QPointF(p1().x(), p2.y()); case RestrictedLineF::Both: return this->p2(); case RestrictedLineF::None: default: return p2; } }
/** * This test checks various generic API methods in DecimalFormat to achieve 100% * API coverage. */ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) { UErrorCode status = U_ZERO_ERROR; // ======= Test constructors logln((UnicodeString)"Testing DecimalFormat constructors"); DecimalFormat def(status); if(U_FAILURE(status)) { errcheckln(status, "ERROR: Could not create DecimalFormat (default) - %s", u_errorName(status)); return; } // bug 10864 status = U_ZERO_ERROR; DecimalFormat noGrouping("###0.##", status); if (noGrouping.getGroupingSize() != 0) { errln("Grouping size should be 0 for no grouping."); } // end bug 10864 status = U_ZERO_ERROR; const UnicodeString pattern("#,##0.# FF"); DecimalFormat pat(pattern, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern)"); return; } status = U_ZERO_ERROR; DecimalFormatSymbols *symbols = new DecimalFormatSymbols(Locale::getFrench(), status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormatSymbols (French)"); return; } status = U_ZERO_ERROR; DecimalFormat cust1(pattern, symbols, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols*)"); } status = U_ZERO_ERROR; DecimalFormat cust2(pattern, *symbols, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols)"); } DecimalFormat copy(pat); // ======= Test clone(), assignment, and equality logln((UnicodeString)"Testing clone(), assignment and equality operators"); if( ! (copy == pat) || copy != pat) { errln((UnicodeString)"ERROR: Copy constructor or == failed"); } copy = cust1; if(copy != cust1) { errln((UnicodeString)"ERROR: Assignment (or !=) failed"); } Format *clone = def.clone(); if( ! (*clone == def) ) { errln((UnicodeString)"ERROR: Clone() failed"); } delete clone; // ======= Test various format() methods logln((UnicodeString)"Testing various format() methods"); double d = -10456.0037; int32_t l = 100000000; Formattable fD(d); Formattable fL(l); UnicodeString res1, res2, res3, res4; FieldPosition pos1(0), pos2(0), pos3(0), pos4(0); res1 = def.format(d, res1, pos1); logln( (UnicodeString) "" + (int32_t) d + " formatted to " + res1); res2 = pat.format(l, res2, pos2); logln((UnicodeString) "" + (int32_t) l + " formatted to " + res2); status = U_ZERO_ERROR; res3 = cust1.format(fD, res3, pos3, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: format(Formattable [double]) failed"); } logln((UnicodeString) "" + (int32_t) fD.getDouble() + " formatted to " + res3); status = U_ZERO_ERROR; res4 = cust2.format(fL, res4, pos4, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: format(Formattable [long]) failed"); } logln((UnicodeString) "" + fL.getLong() + " formatted to " + res4); // ======= Test parse() logln((UnicodeString)"Testing parse()"); UnicodeString text("-10,456.0037"); Formattable result1, result2; ParsePosition pos(0); UnicodeString patt("#,##0.#"); status = U_ZERO_ERROR; pat.applyPattern(patt, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: applyPattern() failed"); } pat.parse(text, result1, pos); if(result1.getType() != Formattable::kDouble && result1.getDouble() != d) { errln((UnicodeString)"ERROR: Roundtrip failed (via parse()) for " + text); } logln(text + " parsed into " + (int32_t) result1.getDouble()); status = U_ZERO_ERROR; pat.parse(text, result2, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: parse() failed"); } if(result2.getType() != Formattable::kDouble && result2.getDouble() != d) { errln((UnicodeString)"ERROR: Roundtrip failed (via parse()) for " + text); } logln(text + " parsed into " + (int32_t) result2.getDouble()); // ======= Test getters and setters logln((UnicodeString)"Testing getters and setters"); const DecimalFormatSymbols *syms = pat.getDecimalFormatSymbols(); DecimalFormatSymbols *newSyms = new DecimalFormatSymbols(*syms); def.setDecimalFormatSymbols(*newSyms); def.adoptDecimalFormatSymbols(newSyms); // don't use newSyms after this if( *(pat.getDecimalFormatSymbols()) != *(def.getDecimalFormatSymbols())) { errln((UnicodeString)"ERROR: adopt or set DecimalFormatSymbols() failed"); } UnicodeString posPrefix; pat.setPositivePrefix("+"); posPrefix = pat.getPositivePrefix(posPrefix); logln((UnicodeString)"Positive prefix (should be +): " + posPrefix); if(posPrefix != "+") { errln((UnicodeString)"ERROR: setPositivePrefix() failed"); } UnicodeString negPrefix; pat.setNegativePrefix("-"); negPrefix = pat.getNegativePrefix(negPrefix); logln((UnicodeString)"Negative prefix (should be -): " + negPrefix); if(negPrefix != "-") { errln((UnicodeString)"ERROR: setNegativePrefix() failed"); } UnicodeString posSuffix; pat.setPositiveSuffix("_"); posSuffix = pat.getPositiveSuffix(posSuffix); logln((UnicodeString)"Positive suffix (should be _): " + posSuffix); if(posSuffix != "_") { errln((UnicodeString)"ERROR: setPositiveSuffix() failed"); } UnicodeString negSuffix; pat.setNegativeSuffix("~"); negSuffix = pat.getNegativeSuffix(negSuffix); logln((UnicodeString)"Negative suffix (should be ~): " + negSuffix); if(negSuffix != "~") { errln((UnicodeString)"ERROR: setNegativeSuffix() failed"); } int32_t multiplier = 0; pat.setMultiplier(8); multiplier = pat.getMultiplier(); logln((UnicodeString)"Multiplier (should be 8): " + multiplier); if(multiplier != 8) { errln((UnicodeString)"ERROR: setMultiplier() failed"); } int32_t groupingSize = 0; pat.setGroupingSize(2); groupingSize = pat.getGroupingSize(); logln((UnicodeString)"Grouping size (should be 2): " + (int32_t) groupingSize); if(groupingSize != 2) { errln((UnicodeString)"ERROR: setGroupingSize() failed"); } pat.setDecimalSeparatorAlwaysShown(TRUE); UBool tf = pat.isDecimalSeparatorAlwaysShown(); logln((UnicodeString)"DecimalSeparatorIsAlwaysShown (should be TRUE) is " + (UnicodeString) (tf ? "TRUE" : "FALSE")); if(tf != TRUE) { errln((UnicodeString)"ERROR: setDecimalSeparatorAlwaysShown() failed"); } // Added by Ken Liu testing set/isExponentSignAlwaysShown pat.setExponentSignAlwaysShown(TRUE); UBool esas = pat.isExponentSignAlwaysShown(); logln((UnicodeString)"ExponentSignAlwaysShown (should be TRUE) is " + (UnicodeString) (esas ? "TRUE" : "FALSE")); if(esas != TRUE) { errln((UnicodeString)"ERROR: ExponentSignAlwaysShown() failed"); } // Added by Ken Liu testing set/isScientificNotation pat.setScientificNotation(TRUE); UBool sn = pat.isScientificNotation(); logln((UnicodeString)"isScientificNotation (should be TRUE) is " + (UnicodeString) (sn ? "TRUE" : "FALSE")); if(sn != TRUE) { errln((UnicodeString)"ERROR: setScientificNotation() failed"); } // Added by Ken Liu testing set/getMinimumExponentDigits int8_t MinimumExponentDigits = 0; pat.setMinimumExponentDigits(2); MinimumExponentDigits = pat.getMinimumExponentDigits(); logln((UnicodeString)"MinimumExponentDigits (should be 2) is " + (int8_t) MinimumExponentDigits); if(MinimumExponentDigits != 2) { errln((UnicodeString)"ERROR: setMinimumExponentDigits() failed"); } // Added by Ken Liu testing set/getRoundingIncrement double RoundingIncrement = 0.0; pat.setRoundingIncrement(2.0); RoundingIncrement = pat.getRoundingIncrement(); logln((UnicodeString)"RoundingIncrement (should be 2.0) is " + (double) RoundingIncrement); if(RoundingIncrement != 2.0) { errln((UnicodeString)"ERROR: setRoundingIncrement() failed"); } //end of Ken's Adding UnicodeString funkyPat; funkyPat = pat.toPattern(funkyPat); logln((UnicodeString)"Pattern is " + funkyPat); UnicodeString locPat; locPat = pat.toLocalizedPattern(locPat); logln((UnicodeString)"Localized pattern is " + locPat); // ======= Test applyPattern() logln((UnicodeString)"Testing applyPattern()"); UnicodeString p1("#,##0.0#;(#,##0.0#)"); logln((UnicodeString)"Applying pattern " + p1); status = U_ZERO_ERROR; pat.applyPattern(p1, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: applyPattern() failed with " + (int32_t) status); } UnicodeString s2; s2 = pat.toPattern(s2); logln((UnicodeString)"Extracted pattern is " + s2); if(s2 != p1) { errln((UnicodeString)"ERROR: toPattern() result did not match pattern applied"); } if(pat.getSecondaryGroupingSize() != 0) { errln("FAIL: Secondary Grouping Size should be 0, not %d\n", pat.getSecondaryGroupingSize()); } if(pat.getGroupingSize() != 3) { errln("FAIL: Primary Grouping Size should be 3, not %d\n", pat.getGroupingSize()); } UnicodeString p2("#,##,##0.0# FF;(#,##,##0.0# FF)"); logln((UnicodeString)"Applying pattern " + p2); status = U_ZERO_ERROR; pat.applyLocalizedPattern(p2, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: applyPattern() failed with " + (int32_t) status); } UnicodeString s3; s3 = pat.toLocalizedPattern(s3); logln((UnicodeString)"Extracted pattern is " + s3); if(s3 != p2) { errln((UnicodeString)"ERROR: toLocalizedPattern() result did not match pattern applied"); } status = U_ZERO_ERROR; UParseError pe; pat.applyLocalizedPattern(p2, pe, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: applyPattern((with ParseError)) failed with " + (int32_t) status); } UnicodeString s4; s4 = pat.toLocalizedPattern(s3); logln((UnicodeString)"Extracted pattern is " + s4); if(s4 != p2) { errln((UnicodeString)"ERROR: toLocalizedPattern(with ParseErr) result did not match pattern applied"); } if(pat.getSecondaryGroupingSize() != 2) { errln("FAIL: Secondary Grouping Size should be 2, not %d\n", pat.getSecondaryGroupingSize()); } if(pat.getGroupingSize() != 3) { errln("FAIL: Primary Grouping Size should be 3, not %d\n", pat.getGroupingSize()); } // ======= Test getStaticClassID() logln((UnicodeString)"Testing getStaticClassID()"); status = U_ZERO_ERROR; NumberFormat *test = new DecimalFormat(status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Couldn't create a DecimalFormat"); } if(test->getDynamicClassID() != DecimalFormat::getStaticClassID()) { errln((UnicodeString)"ERROR: getDynamicClassID() didn't return the expected value"); } delete test; }
// add a pad hole or slot bool PCBMODEL::AddPadHole( KICADPAD* aPad ) { if( NULL == aPad || !aPad->IsThruHole() ) return false; if( !aPad->m_drill.oval ) { TopoDS_Shape s = BRepPrimAPI_MakeCylinder( aPad->m_drill.size.x * 0.5, m_thickness * 2.0 ).Shape(); gp_Trsf shift; shift.SetTranslation( gp_Vec( aPad->m_position.x, aPad->m_position.y, -m_thickness * 0.5 ) ); BRepBuilderAPI_Transform hole( s, shift ); m_cutouts.push_back( hole.Shape() ); return true; } // slotted hole double angle_offset = 0.0; double rad; // radius of the slot double hlen; // half length of the slot if( aPad->m_drill.size.x < aPad->m_drill.size.y ) { angle_offset = M_PI_2; rad = aPad->m_drill.size.x * 0.5; hlen = aPad->m_drill.size.y * 0.5 - rad; } else { rad = aPad->m_drill.size.y * 0.5; hlen = aPad->m_drill.size.x * 0.5 - rad; } DOUBLET c0( -hlen, 0.0 ); DOUBLET c1( hlen, 0.0 ); DOUBLET p0( -hlen, rad ); DOUBLET p1( -hlen, -rad ); DOUBLET p2( hlen, -rad ); DOUBLET p3( hlen, rad ); angle_offset += aPad->m_rotation; double dlim = (double)std::numeric_limits< float >::epsilon(); if( angle_offset < -dlim || angle_offset > dlim ) { double vsin = sin( angle_offset ); double vcos = cos( angle_offset ); double x = c0.x * vcos - c0.y * vsin; double y = c0.x * vsin + c0.y * vcos; c0.x = x; c0.y = y; x = c1.x * vcos - c1.y * vsin; y = c1.x * vsin + c1.y * vcos; c1.x = x; c1.y = y; x = p0.x * vcos - p0.y * vsin; y = p0.x * vsin + p0.y * vcos; p0.x = x; p0.y = y; x = p1.x * vcos - p1.y * vsin; y = p1.x * vsin + p1.y * vcos; p1.x = x; p1.y = y; x = p2.x * vcos - p2.y * vsin; y = p2.x * vsin + p2.y * vcos; p2.x = x; p2.y = y; x = p3.x * vcos - p3.y * vsin; y = p3.x * vsin + p3.y * vcos; p3.x = x; p3.y = y; } c0.x += aPad->m_position.x; c0.y += aPad->m_position.y; c1.x += aPad->m_position.x; c1.y += aPad->m_position.y; p0.x += aPad->m_position.x; p0.y += aPad->m_position.y; p1.x += aPad->m_position.x; p1.y += aPad->m_position.y; p2.x += aPad->m_position.x; p2.y += aPad->m_position.y; p3.x += aPad->m_position.x; p3.y += aPad->m_position.y; OUTLINE oln; oln.SetMinSqDistance( m_minDistance2 ); KICADCURVE crv0, crv1, crv2, crv3; // crv0 = arc crv0.m_start = c0; crv0.m_end = p0; crv0.m_ep = p1; crv0.m_angle = M_PI; crv0.m_radius = rad; crv0.m_form = CURVE_ARC; // crv1 = line crv1.m_start = p1; crv1.m_end = p2; crv1.m_form = CURVE_LINE; // crv2 = arc crv2.m_start = c1; crv2.m_end = p2; crv2.m_ep = p3; crv2.m_angle = M_PI; crv2.m_radius = rad; crv2.m_form = CURVE_ARC; // crv3 = line crv3.m_start = p3; crv3.m_end = p0; crv3.m_form = CURVE_LINE; oln.AddSegment( crv0 ); oln.AddSegment( crv1 ); oln.AddSegment( crv2 ); oln.AddSegment( crv3 ); TopoDS_Shape slot; if( oln.MakeShape( slot, m_thickness ) ) { if( !slot.IsNull() ) m_cutouts.push_back( slot ); return true; } return false; }
/** * Draw a cube into the verticies buffer. Draws the cube in the x-z plane at * the specified row and column with a set height and color. * * In most cases, the texture coordinates are the same as the offsets for the cube * vertex coordinates. Minor exception for left and right side to ensure texture * is not sideways. * * @param x coordinate location * @param y coordinate location * @param z coordinate location * @param size cube scaling size * @param side cube side to draw * @param type tile type to draw */ void WorldNode::DrawTile(float x, float y, float z, float s, CubeSide side, TileType type) { D3DXVECTOR3 n; // normal switch(side) { case kTop: { D3DXVECTOR3 p1( x, y+s, z ); D3DXVECTOR3 p2( x, y+s, z+s ); D3DXVECTOR3 p3( x+s, y+s, z+s ); D3DXVECTOR3 p4( x+s, y+s, z ); D3DXVec3Cross(&n, &(p2-p1), &(p3-p1)); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p2, n, D3DXVECTOR2(0.0f, 0.0f) ), CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ), type); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ), CustomVertex( p4, n, D3DXVECTOR2(1.0f, 1.0f) ), type); m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); break; } case kBottom: { D3DXVECTOR3 p1( x, y, z ); D3DXVECTOR3 p2( x, y, z+s ); D3DXVECTOR3 p3( x+s, y, z+s ); D3DXVECTOR3 p4( x+s, y, z ); D3DXVec3Cross(&n, &(p2-p1), &(p3-p1)); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p2, n, D3DXVECTOR2(0.0f, 0.0f) ), CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ), type); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ), CustomVertex( p4, n, D3DXVECTOR2(1.0f, 1.0f) ), type); m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); break; } case kLeft: { D3DXVECTOR3 p1( x, y, z ); D3DXVECTOR3 p2( x, y, z+s ); D3DXVECTOR3 p3( x, y+s, z+s ); D3DXVECTOR3 p4( x, y+s, z ); D3DXVec3Cross(&n, &(p2-p1), &(p3-p1)); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(1.0f, 1.0f) ), CustomVertex( p2, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p3, n, D3DXVECTOR2(0.0f, 0.0f) ), type); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(1.0f, 1.0f) ), CustomVertex( p3, n, D3DXVECTOR2(0.0f, 0.0f) ), CustomVertex( p4, n, D3DXVECTOR2(1.0f, 0.0f) ), type); m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); break; } case kRight: { D3DXVECTOR3 p1( x+s, y, z ); D3DXVECTOR3 p2( x+s, y+s, z ); D3DXVECTOR3 p3( x+s, y+s, z+s ); D3DXVECTOR3 p4( x+s, y, z+s ); D3DXVec3Cross(&n, &(p2-p1), &(p3-p1)); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p2, n, D3DXVECTOR2(0.0f, 0.0f) ), CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ), type); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ), CustomVertex( p4, n, D3DXVECTOR2(1.0f, 1.0f) ), type); m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); break; } case kUpper: { D3DXVECTOR3 p1( x, y, z+s ); D3DXVECTOR3 p2( x+s, y, z+s ); D3DXVECTOR3 p3( x+s, y+s, z+s ); D3DXVECTOR3 p4( x, y+s, z+s ); D3DXVec3Cross(&n, &(p2-p1), &(p3-p1)); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(1.0f, 1.0f) ), CustomVertex( p2, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p3, n, D3DXVECTOR2(0.0f, 0.0f) ), type); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(1.0f, 1.0f) ), CustomVertex( p3, n, D3DXVECTOR2(0.0f, 0.0f) ), CustomVertex( p4, n, D3DXVECTOR2(1.0f, 0.0f) ), type); m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); break; } case kLower: { D3DXVECTOR3 p1( x, y, z ); D3DXVECTOR3 p2( x, y+s, z ); D3DXVECTOR3 p3( x+s, y+s, z ); D3DXVECTOR3 p4( x+s, y, z ); D3DXVec3Cross(&n, &(p2-p1), &(p3-p1)); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p2, n, D3DXVECTOR2(0.0f, 0.0f) ), CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ), type); AddPlane( CustomVertex( p1, n, D3DXVECTOR2(0.0f, 1.0f) ), CustomVertex( p3, n, D3DXVECTOR2(1.0f, 0.0f) ), CustomVertex( p4, n, D3DXVECTOR2(1.0f, 1.0f) ), type); m_vCollQuads.push_back( CollQuad(p1, p2, p3, p4, n) ); break; } default: break; } }
void scan3d::reconstruct_model_simple(Pointcloud & pointcloud, CalibrationData const& calib, cv::Mat const& pattern_image, cv::Mat const& min_max_image, cv::Mat const& color_image, cv::Size const& projector_size, int threshold, double max_dist, QWidget * parent_widget) { if (!pattern_image.data || pattern_image.type()!=CV_32FC2) { //pattern not correctly decoded std::cerr << "[reconstruct_model] ERROR invalid pattern_image\n"; return; } if (!min_max_image.data || min_max_image.type()!=CV_8UC2) { //pattern not correctly decoded std::cerr << "[reconstruct_model] ERROR invalid min_max_image\n"; return; } if (color_image.data && color_image.type()!=CV_8UC3) { //not standard RGB image std::cerr << "[reconstruct_model] ERROR invalid color_image\n"; return; } if (!calib.is_valid()) { //invalid calibration return; } //parameters //const unsigned threshold = config.value("main/shadow_threshold", 70).toUInt(); //const double max_dist = config.value("main/max_dist_threshold", 40).toDouble(); //const bool remove_background = config.value("main/remove_background", true).toBool(); //const double plane_dist = config.value("main/plane_dist", 100.0).toDouble(); double plane_dist = 100.0; /* background removal cv::Point2i plane_coord[3]; plane_coord[0] = cv::Point2i(config.value("background_plane/x1").toUInt(), config.value("background_plane/y1").toUInt()); plane_coord[1] = cv::Point2i(config.value("background_plane/x2").toUInt(), config.value("background_plane/y2").toUInt()); plane_coord[2] = cv::Point2i(config.value("background_plane/x3").toUInt(), config.value("background_plane/y3").toUInt()); if (plane_coord[0].x<=0 || plane_coord[0].x>=pattern_local.cols || plane_coord[0].y<=0 || plane_coord[0].y>=pattern_local.rows) { plane_coord[0] = cv::Point2i(50, 50); config.setValue("background_plane/x1", plane_coord[0].x); config.setValue("background_plane/y1", plane_coord[0].y); } if (plane_coord[1].x<=0 || plane_coord[1].x>=pattern_local.cols || plane_coord[1].y<=0 || plane_coord[1].y>=pattern_local.rows) { plane_coord[1] = cv::Point2i(50, pattern_local.rows-50); config.setValue("background_plane/x2", plane_coord[1].x); config.setValue("background_plane/y2", plane_coord[1].y); } if (plane_coord[2].x<=0 || plane_coord[2].x>=pattern_local.cols || plane_coord[2].y<=0 || plane_coord[2].y>=pattern_local.rows) { plane_coord[2] = cv::Point2i(pattern_local.cols-50, 50); config.setValue("background_plane/x3", plane_coord[2].x); config.setValue("background_plane/y3", plane_coord[2].y); } */ //init point cloud int scale_factor = 1; int out_cols = pattern_image.cols/scale_factor; int out_rows = pattern_image.rows/scale_factor; pointcloud.clear(); pointcloud.init_points(out_rows, out_cols); pointcloud.init_color(out_rows, out_cols); //progress QProgressDialog * progress = NULL; if (parent_widget) { progress = new QProgressDialog("Reconstruction in progress.", "Abort", 0, pattern_image.rows, parent_widget, Qt::Dialog|Qt::CustomizeWindowHint|Qt::WindowCloseButtonHint); progress->setWindowModality(Qt::WindowModal); progress->setWindowTitle("Processing"); progress->setMinimumWidth(400); } //take 3 points in back plane /*cv::Mat plane; if (remove_background) { cv::Point3d p[3]; for (unsigned i=0; i<3;i++) { for (unsigned j=0; j<10 && ( INVALID(pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x)[0]) || INVALID(pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x)[1])); j++) { plane_coord[i].x += 1.f; } const cv::Vec2f & pattern = pattern_local.at<cv::Vec2f>(plane_coord[i].y, plane_coord[i].x); const float col = pattern[0]; const float row = pattern[1]; if (projector_size.width<=static_cast<int>(col) || projector_size.height<=static_cast<int>(row)) { //abort continue; } //shoot a ray through the image: u=\lambda*v + q cv::Point3d u1 = camera.to_world_coord(plane_coord[i].x, plane_coord[i].y); cv::Point3d v1 = camera.world_ray(plane_coord[i].x, plane_coord[i].y); //shoot a ray through the projector: u=\lambda*v + q cv::Point3d u2 = projector.to_world_coord(col, row); cv::Point3d v2 = projector.world_ray(col, row); //compute ray-ray approximate intersection double distance = 0.0; p[i] = geometry::approximate_ray_intersection(v1, u1, v2, u2, &distance); std::cout << "Plane point " << i << " distance " << distance << std::endl; } plane = geometry::get_plane(p[0], p[1], p[2]); if (cv::Mat(plane.rowRange(0,3).t()*cv::Mat(cv::Point3d(p[0].x, p[0].y, p[0].z-1.0)) + plane.at<double>(3,0)).at<double>(0,0) <0.0) { plane = -1.0*plane; } std::cout << "Background plane: " << plane << std::endl; } */ cv::Mat Rt = calib.R.t(); unsigned good = 0; unsigned bad = 0; unsigned invalid = 0; unsigned repeated = 0; for (int h=0; h<pattern_image.rows; h+=scale_factor) { if (progress && h%4==0) { progress->setValue(h); progress->setLabelText(QString("Reconstruction in progress: %1 good points/%2 bad points").arg(good).arg(bad)); QApplication::instance()->processEvents(); } if (progress && progress->wasCanceled()) { //abort pointcloud.clear(); return; } register const cv::Vec2f * curr_pattern_row = pattern_image.ptr<cv::Vec2f>(h); register const cv::Vec2b * min_max_row = min_max_image.ptr<cv::Vec2b>(h); for (register int w=0; w<pattern_image.cols; w+=scale_factor) { double distance = max_dist; //quality meassure cv::Point3d p; //reconstructed point //cv::Point3d normal(0.0, 0.0, 0.0); const cv::Vec2f & pattern = curr_pattern_row[w]; const cv::Vec2b & min_max = min_max_row[w]; if (sl::INVALID(pattern) || pattern[0]<0.f || pattern[1]<0.f || (min_max[1]-min_max[0])<static_cast<int>(threshold)) { //skip invalid++; continue; } const float col = pattern[0]; const float row = pattern[1]; if (projector_size.width<=static_cast<int>(col) || projector_size.height<=static_cast<int>(row)) { //abort continue; } cv::Vec3f & cloud_point = pointcloud.points.at<cv::Vec3f>(h/scale_factor, w/scale_factor); if (!sl::INVALID(cloud_point[0])) { //point already reconstructed! repeated++; continue; } //standard cv::Point2d p1(w, h); cv::Point2d p2(col, row); triangulate_stereo(calib.cam_K, calib.cam_kc, calib.proj_K, calib.proj_kc, Rt, calib.T, p1, p2, p, &distance); //save texture coordinates /* normal.x = static_cast<float>(w)/static_cast<float>(color_image.cols); normal.y = static_cast<float>(h)/static_cast<float>(color_image.rows); normal.z = 0; */ if (distance < max_dist) { //good point //evaluate the plane double d = plane_dist+1; /*if (remove_background) { d = cv::Mat(plane.rowRange(0,3).t()*cv::Mat(p) + plane.at<double>(3,0)).at<double>(0,0); }*/ if (d>plane_dist) { //object point, keep good++; cloud_point[0] = p.x; cloud_point[1] = p.y; cloud_point[2] = p.z; //normal /*cpoint.normal_x = normal.x; cpoint.normal_y = normal.y; cpoint.normal_z = normal.z;*/ if (color_image.data) { const cv::Vec3b & vec = color_image.at<cv::Vec3b>(h, w); cv::Vec3b & cloud_color = pointcloud.colors.at<cv::Vec3b>(h/scale_factor, w/scale_factor); cloud_color[0] = vec[0]; cloud_color[1] = vec[1]; cloud_color[2] = vec[2]; } } } else { //skip bad++; //std::cout << " d = " << distance << std::endl; } } //for each column } //for each row if (progress) { progress->setValue(pattern_image.rows); progress->close(); delete progress; progress = NULL; } std::cout << "Reconstructed points[simple]: " << good << " (" << bad << " skipped, " << invalid << " invalid) " << std::endl << " - repeated points: " << repeated << " (ignored) " << std::endl; }
void fill_t::checkerboard_fill(point_t p,float width,float height){ int minx=p.getX(); int miny=p.getY(); int maxx=p.getX(); int maxy=p.getY(); find_min_max(p,miny,maxy,minx,maxx,width,height); std::queue <point_t> fillQueue; fillQueue.push(p); float pointx=p.getX(); float pointy=p.getY(); color_t c=colorArray[(int)pointx][(int)pointy]; color_t pixels; float trans_x,trans_y; while(!fillQueue.empty()){ // std::cout<<c.getR()<<" ANSSS"<<std::endl; // exit(0); p=fillQueue.front(); pointx=p.getX(); pointy=p.getY(); fillQueue.pop(); //Added Canvas size check if(pointx>=width || pointy>=height || pointx<0 || pointy<0) continue; //glReadPixels(pointx,pointy,1.0,1.0,GL_RGB,GL_FLOAT,pixels); pixels = colorArray[(int)pointx][(int)pointy]; if( (pixels.getR()==c.getR()) && (pixels.getG()==c.getG()) && (pixels.getB()==c.getB()) ) { point_t p1(pointx, pointy); trans_x=pointx-minx; trans_y=pointy-miny; if((((int)trans_x/16)%2)==0){ if((((int)trans_y/16)%2)==0){ p1.draw(pen_t(color1,1)); } else{ p1.draw(pen_t(color2,1)); } } else{ if((((int)trans_y/16)%2)==0){ p1.draw(pen_t(color2,1)); } else{ p1.draw(pen_t(color1,1)); } } fillQueue.push(point_t(pointx+1,pointy)); fillQueue.push(point_t(pointx,pointy+1)); fillQueue.push(point_t(pointx-1,pointy)); fillQueue.push(point_t(pointx,pointy-1)); } } }
void old_tesselate_polygon(QVector<XTrapezoid> *traps, const QPointF *pg, int pgSize, bool winding) { QVector<QEdge> edges; edges.reserve(128); qreal ymin(INT_MAX/256); qreal ymax(INT_MIN/256); //painter.begin(pg, pgSize); Q_ASSERT(pg[0] == pg[pgSize-1]); // generate edge table // qDebug() << "POINTS:"; for (int x = 0; x < pgSize-1; ++x) { QEdge edge; QPointF p1(Q27Dot5ToDouble(FloatToQ27Dot5(pg[x].x())), Q27Dot5ToDouble(FloatToQ27Dot5(pg[x].y()))); QPointF p2(Q27Dot5ToDouble(FloatToQ27Dot5(pg[x+1].x())), Q27Dot5ToDouble(FloatToQ27Dot5(pg[x+1].y()))); // qDebug() << " " // << p1; edge.winding = p1.y() > p2.y() ? 1 : -1; if (edge.winding > 0) qSwap(p1, p2); edge.p1.x = XDoubleToFixed(p1.x()); edge.p1.y = XDoubleToFixed(p1.y()); edge.p2.x = XDoubleToFixed(p2.x()); edge.p2.y = XDoubleToFixed(p2.y()); edge.m = (p1.y() - p2.y()) / (p1.x() - p2.x()); // line derivative edge.b = p1.y() - edge.m * p1.x(); // intersection with y axis edge.m = edge.m != 0.0 ? 1.0 / edge.m : 0.0; // inverted derivative edges.append(edge); ymin = qMin(ymin, qreal(XFixedToDouble(edge.p1.y))); ymax = qMax(ymax, qreal(XFixedToDouble(edge.p2.y))); } QList<const QEdge *> et; // edge list for (int i = 0; i < edges.size(); ++i) et.append(&edges.at(i)); // sort edge table by min y value qSort(et.begin(), et.end(), compareEdges); // eliminate shared edges for (int i = 0; i < et.size(); ++i) { for (int k = i+1; k < et.size(); ++k) { const QEdge *edgeI = et.at(i); const QEdge *edgeK = et.at(k); if (edgeK->p1.y > edgeI->p1.y) break; if (edgeI->winding != edgeK->winding && isEqual(edgeI->p1, edgeK->p1) && isEqual(edgeI->p2, edgeK->p2) ) { et.removeAt(k); et.removeAt(i); --i; break; } } } if (ymax <= ymin) return; QList<const QEdge *> aet; // edges that intersects the current scanline // if (ymin < 0) // ymin = 0; // if (paintEventClipRegion) // don't scan more lines than we have to // ymax = paintEventClipRegion->boundingRect().height(); #ifdef QT_DEBUG_TESSELATOR qDebug("==> ymin = %f, ymax = %f", ymin, ymax); #endif // QT_DEBUG_TESSELATOR currentY = ymin; // used by the less than op for (qreal y = ymin; y < ymax;) { // fill active edge table with edges that intersect the current line for (int i = 0; i < et.size(); ++i) { const QEdge *edge = et.at(i); if (edge->p1.y > XDoubleToFixed(y)) break; aet.append(edge); et.removeAt(i); --i; } // remove processed edges from active edge table for (int i = 0; i < aet.size(); ++i) { if (aet.at(i)->p2.y <= XDoubleToFixed(y)) { aet.removeAt(i); --i; } } if (aet.size()%2 != 0) { #ifndef QT_NO_DEBUG qWarning("QX11PaintEngine: aet out of sync - this should not happen."); #endif return; } // done? if (!aet.size()) { if (!et.size()) { break; } else { y = currentY = XFixedToDouble(et.at(0)->p1.y); continue; } } // calculate the next y where we have to start a new set of trapezoids qreal next_y(INT_MAX/256); for (int i = 0; i < aet.size(); ++i) { const QEdge *edge = aet.at(i); if (XFixedToDouble(edge->p2.y) < next_y) next_y = XFixedToDouble(edge->p2.y); } if (et.size() && next_y > XFixedToDouble(et.at(0)->p1.y)) next_y = XFixedToDouble(et.at(0)->p1.y); int aetSize = aet.size(); for (int i = 0; i < aetSize; ++i) { for (int k = i+1; k < aetSize; ++k) { const QEdge *edgeI = aet.at(i); const QEdge *edgeK = aet.at(k); qreal m1 = edgeI->m; qreal b1 = edgeI->b; qreal m2 = edgeK->m; qreal b2 = edgeK->b; if (qAbs(m1 - m2) < 0.001) continue; // ### intersect is not calculated correctly when optimized with -O2 (gcc) volatile qreal intersect = 0; if (!qIsFinite(b1)) intersect = (1.f / m2) * XFixedToDouble(edgeI->p1.x) + b2; else if (!qIsFinite(b2)) intersect = (1.f / m1) * XFixedToDouble(edgeK->p1.x) + b1; else intersect = (b1*m1 - b2*m2) / (m1 - m2); if (intersect > y && intersect < next_y) next_y = intersect; } } XFixed yf, next_yf; yf = qrealToXFixed(y); next_yf = qrealToXFixed(next_y); if (yf == next_yf) { y = currentY = next_y; continue; } #ifdef QT_DEBUG_TESSELATOR qDebug("###> y = %f, next_y = %f, %d active edges", y, next_y, aet.size()); qDebug("===> edges"); dump_edges(et); qDebug("===> active edges"); dump_edges(aet); #endif // calc intersection points QVarLengthArray<QIntersectionPoint> isects(aet.size()+1); for (int i = 0; i < isects.size()-1; ++i) { const QEdge *edge = aet.at(i); isects[i].x = (edge->p1.x != edge->p2.x) ? ((y - edge->b)*edge->m) : XFixedToDouble(edge->p1.x); isects[i].edge = edge; } Q_ASSERT(isects.size()%2 == 1); // sort intersection points qSort(&isects[0], &isects[isects.size()-1], compareIntersections); // qDebug() << "INTERSECTION_POINTS:"; // for (int i = 0; i < isects.size(); ++i) // qDebug() << isects[i].edge << isects[i].x; if (winding) { // winding fill rule for (int i = 0; i < isects.size()-1;) { int winding = 0; const QEdge *left = isects[i].edge; const QEdge *right = 0; winding += isects[i].edge->winding; for (++i; i < isects.size()-1 && winding != 0; ++i) { winding += isects[i].edge->winding; right = isects[i].edge; } if (!left || !right) break; //painter.addTrapezoid(&toXTrapezoid(yf, next_yf, *left, *right)); traps->append(toXTrapezoid(yf, next_yf, *left, *right)); } } else { // odd-even fill rule for (int i = 0; i < isects.size()-2; i += 2) { //painter.addTrapezoid(&toXTrapezoid(yf, next_yf, *isects[i].edge, *isects[i+1].edge)); traps->append(toXTrapezoid(yf, next_yf, *isects[i].edge, *isects[i+1].edge)); } } y = currentY = next_y; } #ifdef QT_DEBUG_TESSELATOR qDebug("==> number of trapezoids: %d - edge table size: %d\n", traps->size(), et.size()); for (int i = 0; i < traps->size(); ++i) dump_trap(traps->at(i)); #endif // optimize by unifying trapezoids that share left/right lines // and have a common top/bottom edge // for (int i = 0; i < tps.size(); ++i) { // for (int k = i+1; k < tps.size(); ++k) { // if (i != k && tps.at(i).right == tps.at(k).right // && tps.at(i).left == tps.at(k).left // && (tps.at(i).top == tps.at(k).bottom // || tps.at(i).bottom == tps.at(k).top)) // { // tps[i].bottom = tps.at(k).bottom; // tps.removeAt(k); // i = 0; // break; // } // } // } //static int i = 0; //QImage img = painter.end(); //img.save(QString("res%1.png").arg(i++), "PNG"); }
bool CCurve::CheckForArc(const CVertex& prev_vt, std::list<const CVertex*>& might_be_an_arc, CArc &arc_returned) { // this examines the vertices in might_be_an_arc // if they do fit an arc, set arc to be the arc that they fit and return true // returns true, if arc added if(might_be_an_arc.size() < 2)return false; // find middle point int num = might_be_an_arc.size(); int i = 0; const CVertex* mid_vt = NULL; int mid_i = (num-1)/2; for(std::list<const CVertex*>::iterator It = might_be_an_arc.begin(); It != might_be_an_arc.end(); It++, i++) { if(i == mid_i) { mid_vt = *It; break; } } // create a circle to test Point p0(prev_vt.m_p); Point p1(mid_vt->m_p); Point p2(might_be_an_arc.back()->m_p); Circle c(p0, p1, p2); const CVertex* current_vt = &prev_vt; double accuracy = CArea::m_accuracy * 1.4 / CArea::m_units; for(std::list<const CVertex*>::iterator It = might_be_an_arc.begin(); It != might_be_an_arc.end(); It++) { const CVertex* vt = *It; if(!c.LineIsOn(current_vt->m_p, vt->m_p, accuracy)) return false; current_vt = vt; } CArc arc; arc.m_c = c.m_c; arc.m_s = prev_vt.m_p; arc.m_e = might_be_an_arc.back()->m_p; arc.SetDirWithPoint(might_be_an_arc.front()->m_p); arc.m_user_data = might_be_an_arc.back()->m_user_data; double angs = atan2(arc.m_s.y - arc.m_c.y, arc.m_s.x - arc.m_c.x); double ange = atan2(arc.m_e.y - arc.m_c.y, arc.m_e.x - arc.m_c.x); if(arc.m_dir) { // make sure ange > angs if(ange < angs)ange += 6.2831853071795864; } else { // make sure angs > ange if(angs < ange)angs += 6.2831853071795864; } if(arc.IncludedAngle() >= 3.15)return false; // We don't want full arcs, so limit to about 180 degrees for(std::list<const CVertex*>::iterator It = might_be_an_arc.begin(); It != might_be_an_arc.end(); It++) { const CVertex* vt = *It; double angp = atan2(vt->m_p.y - arc.m_c.y, vt->m_p.x - arc.m_c.x); if(arc.m_dir) { // make sure angp > angs if(angp < angs)angp += 6.2831853071795864; if(angp > ange)return false; } else { // make sure angp > ange if(angp < ange)angp += 6.2831853071795864; if(angp > angs)return false; } } arc_returned = arc; return true; }
/** * Sort elements of a stem variable as if it was an array. This * routine assumes that element ".0" of the stem contains a size * value for the array portion of the elements, and that tail * indices ".start" to ".end", inclusive all exist in the tail. * Sorting will be performed on the string values of all elements, * and in the final result, all values will be replaced by the * string values. * * @param prefix * @param order * @param type * @param _first * @param last * @param firstcol * @param lastcol * * @return */ bool StemClass::sort(RexxString *prefix, int order, int type, size_t _first, size_t last, size_t firstcol, size_t lastcol) { SortData sd; sd.startColumn = 0; sd.columnLength = 0; CompoundVariableTail stem_size(prefix, (size_t)0); CompoundTableElement *size_element = findCompoundVariable(stem_size); if (size_element == OREF_NULL) { return false; } RexxInternalObject *size_value = size_element->getVariableValue(); if (size_value == OREF_NULL) { return false; } size_t count; // get the integer value of this. It must be a valid numeric value. if (!size_value->unsignedNumberValue(count, Numerics::DEFAULT_DIGITS)) { return false; } if (count == 0) // if the count is zero, sorting is easy! { return true; } // if this is not specified, sort to the end if (last == SIZE_MAX) { last = count; } // verify we're fully within the bounds if (_first > count || last > count) { return false; } size_t bounds = last - _first + 1; // get an array item and protect it. We need to have space for // the the variable anchors, the variable values, and a working buffer for the merge. */ ArrayClass *array = new_array(bounds * 3); ProtectedObject p1(array); size_t i; size_t j; for (j = 1, i = _first; i <= last; i++, j++) { CompoundVariableTail nextStem(prefix, (size_t)i); CompoundTableElement *next_element = findCompoundVariable(nextStem); if (next_element == OREF_NULL) { return false; } RexxInternalObject *nextValue = next_element->getVariableValue(); if (nextValue == OREF_NULL) { return false; } // force this to a string value. nextValue = nextValue->requestString(); // now anchor both in the sorting array array->put(next_element, j); array->put(nextValue, j + bounds); } // the data to be sorted RexxString **aData = (RexxString **)array->data(bounds + 1); // the merge sort work area RexxString **working = (RexxString **)array->data((bounds * 2) + 1); { // we're releasing kernel access during the process. The sort is being // done on a locally allocated array, so this will not be accessed by another thread. // All the rest of the operations are thread safe. UnsafeBlock block; if ((firstcol == 0) && (lastcol == SIZE_MAX)) { /* no special columns to check */ switch (type) { case SORT_CASESENSITIVE: mergeSort(&sd, order == SORT_ASCENDING ? compare_asc : compare_desc, aData, working, 0, bounds - 1); break; case SORT_CASEIGNORE: mergeSort(&sd, order == SORT_ASCENDING ? compare_asc_i : compare_desc_i, aData, working, 0, bounds - 1); break; } } else { /* set columns to sort */ sd.startColumn = firstcol; sd.columnLength = lastcol - firstcol + 1; switch (type) { case SORT_CASESENSITIVE: mergeSort(&sd, order == SORT_ASCENDING ? compare_asc_cols : compare_desc_cols, aData, working, 0, bounds - 1); break; case SORT_CASEIGNORE: mergeSort(&sd, order == SORT_ASCENDING ? compare_asc_i_cols : compare_desc_i_cols, aData, working, 0, bounds - 1); break; } } } /* The values have now been sorted. We now need to set each */ /* each variable back to its new value. */ for (i = 1; i <= bounds; i++) { CompoundTableElement *element = (CompoundTableElement *)array->get(i); RexxObject *_value = (RexxObject *)array->get(i + bounds); element->set(_value); } return true; }
Flux_Pts Rectang_Object::lmr_all_pts(Pt2di dir) const { Elise_Rect r = box(); ASSERT_USER((r._dim == 2),"dim != 2 for lmr_all_pts(Pt2di dir)"); return line_map_rect(dir,p0(),p1()); }
int main() { CGAL_KD_SETDTHREAD(11); CGAL::set_pretty_mode ( std::cerr ); CGAL_TEST_START; { typedef CGAL::Homogeneous_d<RT> Kernel; typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d; typedef Convex_hull_d::Point_d Point; typedef Convex_hull_d::Hyperplane_d Plane; typedef Convex_hull_d::Simplex_handle Simplex_handle; typedef Convex_hull_d::Facet_handle Facet_handle; typedef Convex_hull_d::Vertex_handle Vertex_handle; Convex_hull_d T1(2); const Convex_hull_d* pT1 = &T1; Point p1(0,0,1); Point p2(1,0,1); Point p3(0,1,1); Point p4(1,1,1); CGAL_TEST(T1.dimension()==2); CGAL_TEST(T1.current_dimension()==-1); Vertex_handle v1 = T1.insert(p1); CGAL_TEST(T1.associated_point(v1)==p1); T1.insert(p2); CGAL_TEST(T1.current_dimension()==1); CGAL_TEST(T1.is_dimension_jump(p3)); T1.insert(p3); Simplex_handle s1 = T1.simplex(v1); int i1 = T1.index(v1); CGAL_TEST(T1.vertex_of_simplex(s1,i1)==v1); CGAL_TEST(T1.associated_point(T1.vertex_of_simplex(s1,1))== T1.point_of_simplex(s1,1)); T1.insert(p3); CGAL_TEST((T1.opposite_simplex(T1.opposite_simplex(s1,1), T1.index_of_vertex_in_opposite_simplex(s1,1)) == s1)); std::list<Simplex_handle> L = T1.all_simplices(); CGAL_TEST(L.size() == 4); std::list<Facet_handle> F = T1.all_facets(); CGAL_TEST(F.size() == 3); Facet_handle f1 = *(L.begin()); CGAL_TEST(T1.associated_point(T1.vertex_of_facet(f1,1))== T1.point_of_facet(f1,1)); CGAL_TEST((T1.opposite_facet(T1.opposite_facet(f1,1), T1.index_of_vertex_in_opposite_facet(f1,1)) == f1)); Point pf0 = T1.point_of_facet(f1,0); Point pf1 = T1.point_of_facet(f1,1); Plane h = T1.hyperplane_supporting(f1); CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)); std::list<Facet_handle> G = T1.facets_visible_from(p4); CGAL_TEST(G.size()==1); CGAL_TEST(T1.bounded_side(p4)==CGAL::ON_UNBOUNDED_SIDE && T1.bounded_side(Point(1,1,10))==CGAL::ON_BOUNDED_SIDE); Convex_hull_d::Point_const_iterator pit; Convex_hull_d::Vertex_iterator vit; Convex_hull_d::Simplex_iterator sit; for (pit = T1.points_begin(); pit != T1.points_end(); pit++) *pit; for (vit = T1.vertices_begin(); vit != T1.vertices_end(); vit++) *vit; for (sit = T1.simplices_begin(); sit != T1.simplices_end(); sit++) *sit; T1.is_valid(); T1.clear(2); CGAL_TEST(T1.number_of_vertices()==0); CGAL_TEST(T1.number_of_facets()==0); CGAL_TEST(T1.number_of_simplices()==0); std::vector<Point> V = make_vector(p1,p2,p3,p4); T1.initialize(V.begin(),V.end()); Convex_hull_d::Facet_iterator fit; int fnum(0); for (fit = T1.facets_begin(); fit != T1.facets_end(); ++fnum, ++fit) *fit; CGAL_TEST(fnum==4); #ifndef _MSC_VER // truncation due to name length exceeded Convex_hull_d::Hull_vertex_iterator hvit; int vnum(0); for (hvit = T1.hull_vertices_begin(); hvit != T1.hull_vertices_end(); ++vnum, ++hvit) *hvit; CGAL_TEST(vnum==4); Convex_hull_d::Facet_const_iterator fcit; for (fcit = pT1->facets_begin(); fcit != pT1->facets_end(); ++fcit) *fcit; Convex_hull_d::Hull_vertex_const_iterator hvcit; for (hvcit = pT1->hull_vertices_begin(); hvcit != pT1->hull_vertices_end(); ++hvcit) *hvcit; Convex_hull_d::Hull_point_const_iterator hpcit; for (hpcit = pT1->hull_points_begin(); hpcit != pT1->hull_points_end(); ++hpcit) *hpcit; #endif } { typedef CGAL::Cartesian<double> Kernel_3; typedef CGAL::Convex_hull_d_traits_3<Kernel_3> Kernel; typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d; typedef Convex_hull_d::Point_d Point; typedef Convex_hull_d::Hyperplane_d Plane; typedef Convex_hull_d::Simplex_handle Simplex_handle; typedef Convex_hull_d::Facet_handle Facet_handle; typedef Convex_hull_d::Vertex_handle Vertex_handle; Convex_hull_d T2(3); Point p1(0,0,0,1); Point p2(1,0,0,1); Point p3(0,1,0,1); Point p4(0,0,1,1); Point p5(1,1,1,1); CGAL_TEST(T2.dimension()==3); CGAL_TEST(T2.current_dimension()==-1); T2.insert(p1); T2.insert(p2); CGAL_TEST(T2.is_dimension_jump(p3)); T2.insert(p3); CGAL_TEST(T2.current_dimension()==2); CGAL_TEST(T2.is_dimension_jump(p4)); Vertex_handle v1 = T2.insert(p4); CGAL_TEST(T2.associated_point(v1)==p4); Simplex_handle s1 = T2.simplex(v1); int i1 = T2.index(v1); CGAL_TEST(T2.vertex_of_simplex(s1,i1)==v1); CGAL_TEST(T2.associated_point(T2.vertex_of_simplex(s1,1))== T2.point_of_simplex(s1,1)); CGAL_TEST((T2.opposite_simplex(T2.opposite_simplex(s1,1), T2.index_of_vertex_in_opposite_simplex(s1,1)) == s1)); std::list<Simplex_handle> L = T2.all_simplices(); CGAL_TEST(L.size() == 5); std::list<Facet_handle> F = T2.all_facets(); CGAL_TEST(F.size() == 4); Facet_handle f1 = *(L.begin()); CGAL_TEST(T2.associated_point(T2.vertex_of_facet(f1,1))== T2.point_of_facet(f1,1)); CGAL_TEST((T2.opposite_facet(T2.opposite_facet(f1,1), T2.index_of_vertex_in_opposite_facet(f1,1)) == f1)); Point pf0 = T2.point_of_facet(f1,0); Point pf1 = T2.point_of_facet(f1,1); Point pf2 = T2.point_of_facet(f1,2); Plane h = T2.hyperplane_supporting(f1); CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)&&h.has_on(pf2)); std::list<Facet_handle> G = T2.facets_visible_from(p5); CGAL_TEST(G.size()==1); CGAL_TEST(T2.bounded_side(p5)==CGAL::ON_UNBOUNDED_SIDE && T2.bounded_side(Point(1,1,1,10))==CGAL::ON_BOUNDED_SIDE); T2.is_valid(); T2.clear(3); } { typedef CGAL::Homogeneous<RT> Kernel_3; typedef CGAL::Convex_hull_d_traits_3<Kernel_3> Kernel; typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d; typedef Convex_hull_d::Point_d Point; typedef Convex_hull_d::Hyperplane_d Plane; typedef Convex_hull_d::Simplex_handle Simplex_handle; typedef Convex_hull_d::Facet_handle Facet_handle; typedef Convex_hull_d::Vertex_handle Vertex_handle; Convex_hull_d T2(3); Point p1(0,0,0,1); Point p2(1,0,0,1); Point p3(0,1,0,1); Point p4(0,0,1,1); Point p5(1,1,1,1); CGAL_TEST(T2.dimension()==3); CGAL_TEST(T2.current_dimension()==-1); T2.insert(p1); T2.insert(p2); CGAL_TEST(T2.is_dimension_jump(p3)); T2.insert(p3); CGAL_TEST(T2.current_dimension()==2); CGAL_TEST(T2.is_dimension_jump(p4)); Vertex_handle v1 = T2.insert(p4); CGAL_TEST(T2.associated_point(v1)==p4); Simplex_handle s1 = T2.simplex(v1); int i1 = T2.index(v1); CGAL_TEST(T2.vertex_of_simplex(s1,i1)==v1); CGAL_TEST(T2.associated_point(T2.vertex_of_simplex(s1,1))== T2.point_of_simplex(s1,1)); CGAL_TEST((T2.opposite_simplex(T2.opposite_simplex(s1,1), T2.index_of_vertex_in_opposite_simplex(s1,1)) == s1)); std::list<Simplex_handle> L = T2.all_simplices(); CGAL_TEST(L.size() == 5); std::list<Facet_handle> F = T2.all_facets(); CGAL_TEST(F.size() == 4); Facet_handle f1 = *(L.begin()); CGAL_TEST(T2.associated_point(T2.vertex_of_facet(f1,1))== T2.point_of_facet(f1,1)); CGAL_TEST((T2.opposite_facet(T2.opposite_facet(f1,1), T2.index_of_vertex_in_opposite_facet(f1,1)) == f1)); Point pf0 = T2.point_of_facet(f1,0); Point pf1 = T2.point_of_facet(f1,1); Point pf2 = T2.point_of_facet(f1,2); Plane h = T2.hyperplane_supporting(f1); CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)&&h.has_on(pf2)); std::list<Facet_handle> G = T2.facets_visible_from(p5); CGAL_TEST(G.size()==1); CGAL_TEST(T2.bounded_side(p5)==CGAL::ON_UNBOUNDED_SIDE && T2.bounded_side(Point(1,1,1,10))==CGAL::ON_BOUNDED_SIDE); T2.is_valid(); T2.clear(3); } { typedef CGAL::Cartesian_d<double> Kernel; typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d; typedef Convex_hull_d::Point_d Point; typedef Convex_hull_d::Hyperplane_d Plane; typedef Convex_hull_d::Simplex_handle Simplex_handle; typedef Convex_hull_d::Facet_handle Facet_handle; typedef Convex_hull_d::Vertex_handle Vertex_handle; Convex_hull_d T2(3); Point p1(0,0,0,1); Point p2(1,0,0,1); Point p3(0,1,0,1); Point p4(0,0,1,1); Point p5(1,1,1,1); CGAL_TEST(T2.dimension()==3); CGAL_TEST(T2.current_dimension()==-1); T2.insert(p1); T2.insert(p2); CGAL_TEST(T2.is_dimension_jump(p3)); T2.insert(p3); CGAL_TEST(T2.current_dimension()==2); CGAL_TEST(T2.is_dimension_jump(p4)); Vertex_handle v1 = T2.insert(p4); CGAL_TEST(T2.associated_point(v1)==p4); Simplex_handle s1 = T2.simplex(v1); int i1 = T2.index(v1); CGAL_TEST(T2.vertex_of_simplex(s1,i1)==v1); CGAL_TEST(T2.associated_point(T2.vertex_of_simplex(s1,1))== T2.point_of_simplex(s1,1)); CGAL_TEST((T2.opposite_simplex(T2.opposite_simplex(s1,1), T2.index_of_vertex_in_opposite_simplex(s1,1)) == s1)); std::list<Simplex_handle> L = T2.all_simplices(); CGAL_TEST(L.size() == 5); std::list<Facet_handle> F = T2.all_facets(); CGAL_TEST(F.size() == 4); Facet_handle f1 = *(L.begin()); CGAL_TEST(T2.associated_point(T2.vertex_of_facet(f1,1))== T2.point_of_facet(f1,1)); CGAL_TEST((T2.opposite_facet(T2.opposite_facet(f1,1), T2.index_of_vertex_in_opposite_facet(f1,1)) == f1)); Point pf0 = T2.point_of_facet(f1,0); Point pf1 = T2.point_of_facet(f1,1); Point pf2 = T2.point_of_facet(f1,2); Plane h = T2.hyperplane_supporting(f1); CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)&&h.has_on(pf2)); std::list<Facet_handle> G = T2.facets_visible_from(p5); CGAL_TEST(G.size()==1); CGAL_TEST(T2.bounded_side(p5)==CGAL::ON_UNBOUNDED_SIDE && T2.bounded_side(Point(1,1,1,10))==CGAL::ON_BOUNDED_SIDE); T2.is_valid(); T2.clear(3); } { typedef CGAL::Homogeneous_d<RT> Kernel; typedef CGAL::Convex_hull_d<Kernel> Convex_hull_d; typedef Convex_hull_d::Point_d Point; typedef Convex_hull_d::Hyperplane_d Plane; typedef Convex_hull_d::Simplex_handle Simplex_handle; typedef Convex_hull_d::Facet_handle Facet_handle; typedef Convex_hull_d::Vertex_handle Vertex_handle; Convex_hull_d T2(3); Point p1(0,0,0,1); Point p2(1,0,0,1); Point p3(0,1,0,1); Point p4(0,0,1,1); Point p5(1,1,1,1); CGAL_TEST(T2.dimension()==3); CGAL_TEST(T2.current_dimension()==-1); T2.insert(p1); T2.insert(p2); CGAL_TEST(T2.is_dimension_jump(p3)); T2.insert(p3); CGAL_TEST(T2.current_dimension()==2); CGAL_TEST(T2.is_dimension_jump(p4)); Vertex_handle v1 = T2.insert(p4); CGAL_TEST(T2.associated_point(v1)==p4); Simplex_handle s1 = T2.simplex(v1); int i1 = T2.index(v1); CGAL_TEST(T2.vertex_of_simplex(s1,i1)==v1); CGAL_TEST(T2.associated_point(T2.vertex_of_simplex(s1,1))== T2.point_of_simplex(s1,1)); CGAL_TEST((T2.opposite_simplex(T2.opposite_simplex(s1,1), T2.index_of_vertex_in_opposite_simplex(s1,1)) == s1)); std::list<Simplex_handle> L = T2.all_simplices(); CGAL_TEST(L.size() == 5); std::list<Facet_handle> F = T2.all_facets(); CGAL_TEST(F.size() == 4); Facet_handle f1 = *(L.begin()); CGAL_TEST(T2.associated_point(T2.vertex_of_facet(f1,1))== T2.point_of_facet(f1,1)); CGAL_TEST((T2.opposite_facet(T2.opposite_facet(f1,1), T2.index_of_vertex_in_opposite_facet(f1,1)) == f1)); Point pf0 = T2.point_of_facet(f1,0); Point pf1 = T2.point_of_facet(f1,1); Point pf2 = T2.point_of_facet(f1,2); Plane h = T2.hyperplane_supporting(f1); CGAL_TEST(h.has_on(pf0)&&h.has_on(pf1)&&h.has_on(pf2)); std::list<Facet_handle> G = T2.facets_visible_from(p5); CGAL_TEST(G.size()==1); CGAL_TEST(T2.bounded_side(p5)==CGAL::ON_UNBOUNDED_SIDE && T2.bounded_side(Point(1,1,1,10))==CGAL::ON_BOUNDED_SIDE); T2.is_valid(); T2.clear(3); } CGAL_TEST_END; }
//======================================================================= //function : Execute //purpose : //======================================================================= Standard_Integer GEOMImpl_MeasureDriver::Execute(TFunction_Logbook& log) const { if (Label().IsNull()) return 0; Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label()); GEOMImpl_IMeasure aCI (aFunction); Standard_Integer aType = aFunction->GetType(); TopoDS_Shape aShape; if (aType == CDG_MEASURE) { Handle(GEOM_Function) aRefBase = aCI.GetBase(); TopoDS_Shape aShapeBase = aRefBase->GetValue(); if (aShapeBase.IsNull()) { Standard_NullObject::Raise("Shape for centre of mass calculation is null"); } gp_Ax3 aPos = GEOMImpl_IMeasureOperations::GetPosition(aShapeBase); gp_Pnt aCenterMass = aPos.Location(); aShape = BRepBuilderAPI_MakeVertex(aCenterMass).Shape(); } else if (aType == VERTEX_BY_INDEX) { Handle(GEOM_Function) aRefBase = aCI.GetBase(); TopoDS_Shape aShapeBase = aRefBase->GetValue(); if (aShapeBase.IsNull()) { Standard_NullObject::Raise("Shape for centre of mass calculation is null"); } int index = aCI.GetIndex(); gp_Pnt aVertex; if (aShapeBase.ShapeType() == TopAbs_VERTEX) { if ( index != 1 ) Standard_NullObject::Raise("Vertex index is out of range"); else aVertex = BRep_Tool::Pnt(TopoDS::Vertex(aShapeBase)); } else if (aShapeBase.ShapeType() == TopAbs_EDGE) { TopoDS_Vertex aV1, aV2; TopoDS_Edge anEdgeE = TopoDS::Edge(aShapeBase); TopExp::Vertices(anEdgeE, aV1, aV2); gp_Pnt aP1 = BRep_Tool::Pnt(aV1); gp_Pnt aP2 = BRep_Tool::Pnt(aV2); if (index < 0 || index > 1) Standard_NullObject::Raise("Vertex index is out of range"); if ( ( anEdgeE.Orientation() == TopAbs_FORWARD && index == 0 ) || ( anEdgeE.Orientation() == TopAbs_REVERSED && index == 1 ) ) aVertex = aP1; else aVertex = aP2; } else if (aShapeBase.ShapeType() == TopAbs_WIRE) { TopTools_IndexedMapOfShape anEdgeShapes; TopTools_IndexedMapOfShape aVertexShapes; TopoDS_Vertex aV1, aV2; TopoDS_Wire aWire = TopoDS::Wire(aShapeBase); TopExp_Explorer exp (aWire, TopAbs_EDGE); for (; exp.More(); exp.Next()) { anEdgeShapes.Add(exp.Current()); TopoDS_Edge E = TopoDS::Edge(exp.Current()); TopExp::Vertices(E, aV1, aV2); if ( aVertexShapes.Extent() == 0) aVertexShapes.Add(aV1); if ( !aV1.IsSame( aVertexShapes(aVertexShapes.Extent()) ) ) aVertexShapes.Add(aV1); if ( !aV2.IsSame( aVertexShapes(aVertexShapes.Extent()) ) ) aVertexShapes.Add(aV2); } if (index < 0 || index > aVertexShapes.Extent()) Standard_NullObject::Raise("Vertex index is out of range"); if (aWire.Orientation() == TopAbs_FORWARD) aVertex = BRep_Tool::Pnt(TopoDS::Vertex(aVertexShapes(index+1))); else aVertex = BRep_Tool::Pnt(TopoDS::Vertex(aVertexShapes(aVertexShapes.Extent() - index))); } else { Standard_NullObject::Raise("Shape for vertex calculation is not an edge or wire"); } aShape = BRepBuilderAPI_MakeVertex(aVertex).Shape(); } else if (aType == VECTOR_FACE_NORMALE) { // Face Handle(GEOM_Function) aRefBase = aCI.GetBase(); TopoDS_Shape aShapeBase = aRefBase->GetValue(); if (aShapeBase.IsNull()) { Standard_NullObject::Raise("Face for normale calculation is null"); } if (aShapeBase.ShapeType() != TopAbs_FACE) { Standard_NullObject::Raise("Shape for normale calculation is not a face"); } TopoDS_Face aFace = TopoDS::Face(aShapeBase); // Point gp_Pnt p1 (0,0,0); Handle(GEOM_Function) aPntFunc = aCI.GetPoint(); if (!aPntFunc.IsNull()) { TopoDS_Shape anOptPnt = aPntFunc->GetValue(); if (anOptPnt.IsNull()) Standard_NullObject::Raise("Invalid shape given for point argument"); p1 = BRep_Tool::Pnt(TopoDS::Vertex(anOptPnt)); } else { gp_Ax3 aPos = GEOMImpl_IMeasureOperations::GetPosition(aFace); p1 = aPos.Location(); } // Point parameters on surface Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace); Handle(ShapeAnalysis_Surface) aSurfAna = new ShapeAnalysis_Surface (aSurf); gp_Pnt2d pUV = aSurfAna->ValueOfUV(p1, Precision::Confusion()); // Normal direction gp_Vec Vec1,Vec2; BRepAdaptor_Surface SF (aFace); SF.D1(pUV.X(), pUV.Y(), p1, Vec1, Vec2); if (Vec1.Magnitude() < Precision::Confusion()) { gp_Vec tmpV; gp_Pnt tmpP; SF.D1(pUV.X(), pUV.Y()-0.1, tmpP, Vec1, tmpV); } else if (Vec2.Magnitude() < Precision::Confusion()) { gp_Vec tmpV; gp_Pnt tmpP; SF.D1(pUV.X()-0.1, pUV.Y(), tmpP, tmpV, Vec2); } gp_Vec V = Vec1.Crossed(Vec2); Standard_Real mod = V.Magnitude(); if (mod < Precision::Confusion()) Standard_NullObject::Raise("Normal vector of a face has null magnitude"); // Set length of normal vector to average radius of curvature Standard_Real radius = 0.0; GeomLProp_SLProps aProperties (aSurf, pUV.X(), pUV.Y(), 2, Precision::Confusion()); if (aProperties.IsCurvatureDefined()) { Standard_Real radius1 = Abs(aProperties.MinCurvature()); Standard_Real radius2 = Abs(aProperties.MaxCurvature()); if (Abs(radius1) > Precision::Confusion()) { radius = 1.0 / radius1; if (Abs(radius2) > Precision::Confusion()) { radius = (radius + 1.0 / radius2) / 2.0; } } else { if (Abs(radius2) > Precision::Confusion()) { radius = 1.0 / radius2; } } } // Set length of normal vector to average dimension of the face // (only if average radius of curvature is not appropriate) if (radius < Precision::Confusion()) { Bnd_Box B; Standard_Real Xmin, Xmax, Ymin, Ymax, Zmin, Zmax; BRepBndLib::Add(aFace, B); B.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax); radius = ((Xmax - Xmin) + (Ymax - Ymin) + (Zmax - Zmin)) / 3.0; } if (radius < Precision::Confusion()) radius = 1.0; V *= radius / mod; // consider the face orientation if (aFace.Orientation() == TopAbs_REVERSED || aFace.Orientation() == TopAbs_INTERNAL) { V = - V; } // Edge gp_Pnt p2 = p1.Translated(V); BRepBuilderAPI_MakeEdge aBuilder (p1, p2); if (!aBuilder.IsDone()) Standard_NullObject::Raise("Vector construction failed"); aShape = aBuilder.Shape(); } else { } if (aShape.IsNull()) return 0; aFunction->SetValue(aShape); log.SetTouched(Label()); return 1; }
template <typename PointT, typename PointNT> bool pcl::SampleConsensusModelCone<PointT, PointNT>::computeModelCoefficients ( const std::vector<int> &samples, Eigen::VectorXf &model_coefficients) { // Need 3 samples if (samples.size () != 3) { PCL_ERROR ("[pcl::SampleConsensusModelCone::computeModelCoefficients] Invalid set of samples given (%zu)!\n", samples.size ()); return (false); } if (!normals_) { PCL_ERROR ("[pcl::SampleConsensusModelCone::computeModelCoefficients] No input dataset containing normals was given!\n"); return (false); } Eigen::Vector4f p1 (input_->points[samples[0]].x, input_->points[samples[0]].y, input_->points[samples[0]].z, 0); Eigen::Vector4f p2 (input_->points[samples[1]].x, input_->points[samples[1]].y, input_->points[samples[1]].z, 0); Eigen::Vector4f p3 (input_->points[samples[2]].x, input_->points[samples[2]].y, input_->points[samples[2]].z, 0); Eigen::Vector4f n1 (normals_->points[samples[0]].normal[0], normals_->points[samples[0]].normal[1], normals_->points[samples[0]].normal[2], 0); Eigen::Vector4f n2 (normals_->points[samples[1]].normal[0], normals_->points[samples[1]].normal[1], normals_->points[samples[1]].normal[2], 0); Eigen::Vector4f n3 (normals_->points[samples[2]].normal[0], normals_->points[samples[2]].normal[1], normals_->points[samples[2]].normal[2], 0); //calculate apex (intersection of the three planes defined by points and belonging normals Eigen::Vector4f ortho12 = n1.cross3(n2); Eigen::Vector4f ortho23 = n2.cross3(n3); Eigen::Vector4f ortho31 = n3.cross3(n1); float denominator = n1.dot(ortho23); float d1 = p1.dot (n1); float d2 = p2.dot (n2); float d3 = p3.dot (n3); Eigen::Vector4f apex = (d1 * ortho23 + d2 * ortho31 + d3 * ortho12) / denominator; //compute axis (normal of plane defined by: { apex+(p1-apex)/(||p1-apex||), apex+(p2-apex)/(||p2-apex||), apex+(p3-apex)/(||p3-apex||)} Eigen::Vector4f ap1 = p1 - apex; Eigen::Vector4f ap2 = p2 - apex; Eigen::Vector4f ap3 = p3 - apex; Eigen::Vector4f np1 = apex + (ap1/ap1.norm ()); Eigen::Vector4f np2 = apex + (ap2/ap2.norm ()); Eigen::Vector4f np3 = apex + (ap3/ap3.norm ()); Eigen::Vector4f np1np2 = np2 - np1; Eigen::Vector4f np1np3 = np3 - np1; Eigen::Vector4f axis_dir = np1np2.cross3 (np1np3); axis_dir.normalize (); // normalize the vector (apex->p) for opening angle calculation ap1.normalize (); ap2.normalize (); ap3.normalize (); //compute opening angle float opening_angle = ( acosf (ap1.dot (axis_dir)) + acosf (ap2.dot (axis_dir)) + acosf (ap3.dot (axis_dir)) ) / 3.0f; model_coefficients.resize (7); // model_coefficients.template head<3> () = line_pt.template head<3> (); model_coefficients[0] = apex[0]; model_coefficients[1] = apex[1]; model_coefficients[2] = apex[2]; // model_coefficients.template segment<3> (3) = line_dir.template head<3> (); model_coefficients[3] = axis_dir[0]; model_coefficients[4] = axis_dir[1]; model_coefficients[5] = axis_dir[2]; // cone radius model_coefficients[6] = opening_angle; if (model_coefficients[6] != -std::numeric_limits<double>::max() && model_coefficients[6] < min_angle_) return (false); if (model_coefficients[6] != std::numeric_limits<double>::max() && model_coefficients[6] > max_angle_) return (false); return (true); }
int OBJ::ParseLine(int lineno,int argc,const char **argv) // return TRUE to continue parsing, return FALSE to abort parsing process { int ret = 0; if ( argc >= 1 ) { const char *foo = argv[0]; if ( *foo != '#' ) { if (strcmp(argv[0], "v") == 0 && argc == 4 ) { float vx = (float) atof( argv[1] ); float vy = (float) atof( argv[2] ); float vz = (float) atof( argv[3] ); Resize(mVerts, mMaxVerts, mNumVerts, mNumVerts + 3); mVerts[mNumVerts++] = vx; mVerts[mNumVerts++] = vy; mVerts[mNumVerts++] = vz; } else if (strcmp(argv[0],"vt") == 0 && (argc == 3 || argc == 4)) { // ignore 4rd component if present float tx = (float) atof( argv[1] ); float ty = (float) atof( argv[2] ); Resize(mTexels, mMaxTexels, mNumTexels, mNumTexels + 2); mTexels[mNumTexels++] = tx; mTexels[mNumTexels++] = ty; } else if (strcmp(argv[0],"vn") == 0 && argc == 4 ) { float normalx = (float) atof(argv[1]); float normaly = (float) atof(argv[2]); float normalz = (float) atof(argv[3]); Resize(mNormals, mMaxNormals, mNumNormals, mNumNormals + 3); mNormals[mNumNormals++] = normalx; mNormals[mNumNormals++] = normaly; mNormals[mNumNormals++] = normalz; } else if (strcmp(argv[0],"f") == 0 && argc >= 4 ) { GeometryVertex v[32]; int vcount = argc-1; for (int i=1; i<argc; i++) { GetVertex(v[i-1],argv[i] ); } // need to generate a normal! #if 0 // not currently implemented if ( mNormals.empty() ) { Vector3d<float> p1( v[0].mPos ); Vector3d<float> p2( v[1].mPos ); Vector3d<float> p3( v[2].mPos ); Vector3d<float> n; n.ComputeNormal(p3,p2,p1); for (int i=0; i<vcount; i++) { v[i].mNormal[0] = n.x; v[i].mNormal[1] = n.y; v[i].mNormal[2] = n.z; } } #endif mCallback->NodeTriangle(&v[0],&v[1],&v[2], mTextured); if ( vcount >=3 ) // do the fan { for (int i=2; i<(vcount-1); i++) { mCallback->NodeTriangle(&v[0],&v[i],&v[i+1], mTextured); } } } } } return ret; }
wxRect FenetreZoom::CalculPosRectDst(wxRect &src,wxPoint *p) { wxRect recSrc(0,0,fMere->ImAcq()->cols,fMere->ImAcq()->rows); wxRect rMax; long origX=0,origY=0; int fZoomNume,fZoomDeno; wxPoint refPos(0,0); if (p) refPos= *p; CalculZoom(fZoomNume,fZoomDeno); rMax=this->GetClientRect(); wxPoint p1(0,0); wxPoint p2( (rMax.GetRight()+fZoomNume-1)/fZoomDeno*fZoomDeno, (rMax.GetBottom()+fZoomNume-1)/fZoomDeno*fZoomDeno); wxPoint p1Img=RepereEcranImage(p1); wxPoint p2Img=RepereEcranImage(p2); wxPoint transLat(refPos.x-p2Img.x/2,refPos.y-p2Img.y/2); p2Img.x += fZoomDeno-1; p2Img.y += fZoomDeno-1; if (p) { p1Img += transLat; p2Img += transLat; } if (!recSrc.Contains(p1Img)) { if (p1Img.x<0) { p2Img.x+= -p1Img.x; p1Img.x =0; } if (p1Img.y<0) { p2Img.y+= -p1Img.y; p1Img.y =0; } } if (!recSrc.Contains(p2Img)) { if (p2Img.x>=recSrc.GetRight()) { p1Img.x += recSrc.GetRight()-p2Img.x-1; p2Img.x = recSrc.GetRight()-1; } if (p2Img.y>=recSrc.GetBottom()) { p1Img.y += recSrc.GetBottom()-p2Img.y-1; p2Img.y = recSrc.GetBottom()-1; } } p2 = RepereImageEcran(p2Img); p1 = RepereImageEcran(p1Img); wxRect dst(p1,p2); src=wxRect(p1Img,p2Img); return dst; long largeur = p2Img.x - p1Img.x; long hauteur = p2Img.y - p1Img.y; origX = p->x-largeur/2; long right = p->x+largeur/2; origY = p->y-hauteur/2; long bottom = p->y+hauteur/2; if (recSrc.GetRight()<right) { right= recSrc.GetRight(); origX = right-largeur; } if (recSrc.GetBottom()<bottom) { bottom= recSrc.GetBottom(); origY = bottom-hauteur; } if (recSrc.GetLeft()>origX) { origX= recSrc.GetLeft(); right = origX+largeur; } if (recSrc.GetTop()>origY) { origY= recSrc.GetTop(); bottom = origY +hauteur; } src=wxRect(origX,origY,right,bottom); return dst; }
void EventCanvas::actionCommand(int action)/*{{{*/ { switch(action) { case LOCATORS_TO_SELECTION: { int tick_max = 0; int tick_min = INT_MAX; bool found = false; for (iCItem i = _items.begin(); i != _items.end(); i++) { if (!i->second->isSelected()) continue; int tick = i->second->x(); int len = i->second->event().lenTick(); found = true; if (tick + len > tick_max) tick_max = tick + len; if (tick < tick_min) tick_min = tick; } if (found) { Pos p1(tick_min, true); Pos p2(tick_max, true); song->setPos(1, p1); song->setPos(2, p2); } } break; case SEL_RIGHT ... SEL_RIGHT_ADD: { if (action == SEL_RIGHT && allItemsAreSelected()) { deselectAll(); selectAtTick(song->cpos()); return; } iCItem i, iRightmost; CItem* rightmost = NULL; // get a list of items that belong to the current part // since multiple parts have populated the _items list // we need to filter on the actual current Part! CItemList list = _items; if(multiPartSelectionAction && !multiPartSelectionAction->isChecked()) list = getItemlistForCurrentPart(); //Get the rightmost selected note (if any) i = list.begin(); while (i != list.end()) { if (i->second->isSelected()) { iRightmost = i; rightmost = i->second; } ++i; } if (rightmost) { iCItem temp = iRightmost; temp++; //If so, deselect current note and select the one to the right if (temp != list.end()) { if (action != SEL_RIGHT_ADD) deselectAll(); iRightmost++; iRightmost->second->setSelected(true); itemPressed(iRightmost->second); m_tempPlayItems.append(iRightmost->second); QTimer::singleShot(NOTE_PLAY_TIME, this, SLOT(playReleaseForItem())); if(editor->isGlobalEdit()) populateMultiSelect(iRightmost->second); updateSelection(); } } else // there was no item selected at all? Then select nearest to tick if there is any { selectAtTick(song->cpos()); updateSelection(); } } break; case SEL_LEFT ... SEL_LEFT_ADD: { if (action == SEL_LEFT && allItemsAreSelected()) { deselectAll(); selectAtTick(song->cpos()); return; } iCItem i, iLeftmost; CItem* leftmost = NULL; // get a list of items that belong to the current part // since multiple parts have populated the _items list // we need to filter on the actual current Part! CItemList list = _items; if(multiPartSelectionAction && !multiPartSelectionAction->isChecked()) list = getItemlistForCurrentPart(); if (list.size() > 0) { i = list.end(); while (i != list.begin()) { --i; if (i->second->isSelected()) { iLeftmost = i; leftmost = i->second; } } if (leftmost) { if (iLeftmost != list.begin()) { //Add item if (action != SEL_LEFT_ADD) deselectAll(); iLeftmost--; iLeftmost->second->setSelected(true); itemPressed(iLeftmost->second); m_tempPlayItems.append(iLeftmost->second); QTimer::singleShot(NOTE_PLAY_TIME, this, SLOT(playReleaseForItem())); if(editor->isGlobalEdit()) populateMultiSelect(iLeftmost->second); updateSelection(); } else { leftmost->setSelected(true); itemPressed(leftmost); m_tempPlayItems.append(leftmost); QTimer::singleShot(NOTE_PLAY_TIME, this, SLOT(playReleaseForItem())); if(editor->isGlobalEdit()) populateMultiSelect(leftmost); updateSelection(); } } else // there was no item selected at all? Then select nearest to tick if there is any { selectAtTick(song->cpos()); updateSelection(); } } } break; case INC_PITCH_OCTAVE: { modifySelected(NoteInfo::VAL_PITCH, 12); } break; case DEC_PITCH_OCTAVE: { modifySelected(NoteInfo::VAL_PITCH, -12); } break; case INC_PITCH: { modifySelected(NoteInfo::VAL_PITCH, 1); } break; case DEC_PITCH: { modifySelected(NoteInfo::VAL_PITCH, -1); } break; case INC_POS: { // TODO: Check boundaries modifySelected(NoteInfo::VAL_TIME, editor->raster()); } break; case DEC_POS: { // TODO: Check boundaries modifySelected(NoteInfo::VAL_TIME, 0 - editor->raster()); } break; case INCREASE_LEN: { // TODO: Check boundaries modifySelected(NoteInfo::VAL_LEN, editor->raster()); } break; case DECREASE_LEN: { // TODO: Check boundaries modifySelected(NoteInfo::VAL_LEN, 0 - editor->raster()); } break; case GOTO_SEL_NOTE: { CItem* leftmost = getLeftMostSelected(); if (leftmost) { unsigned newtick = leftmost->event().tick() + leftmost->part()->tick(); Pos p1(newtick, true); song->setPos(0, p1, true, true, false); } } break; case MIDI_PANIC: { song->panic(); } break; } }/*}}}*/
TEST_F(ch_chanFixture, Point_OverLoads_LessThan_OnXY){ Point_2 p1(0,0),p2(1,1); EXPECT_TRUE(p1<p2); EXPECT_FALSE(p1>p2); }